full_path
stringlengths
31
232
filename
stringlengths
4
167
content
stringlengths
0
48.3M
PowerShellCorpus/PowerShellGallery/vscodeextensions/0.1.2/Private/Get-VSCodeVsix.ps1
Get-VSCodeVsix.ps1
Function Get-VSCodeVsix { [CmdletBinding()] param ( [Parameter(Mandatory=$true,ValueFromPipelineByPropertyName=$true)] [string[]]$FullName, [Parameter(Mandatory=$true,ValueFromPipelineByPropertyName=$true)] [string[]]$Version, [Parameter(Mandatory=$true,ValueFromPipelineByPropertyName=$true)] [string[]]$assetUri ) Process { $VsixUri = "$($assetUri)/Microsoft.VisualStudio.Services.VSIXPackage?install=true" $ExtensionFolder = "$($Fullname)-$($version)" Invoke-RestMethod -Method Get -Uri $VsixUri -ErrorVariable CodeError -OutFile "$Env:TEMP\$ExtensionFolder.zip" -ErrorAction SilentlyContinue if ($CodeError) { $JsonError = $CodeError.Message | ConvertFrom-Json $HttpResponse = $CodeError.ErrorRecord.Exception.Response Throw "Error: $($JsonError.error) `nDescription: $($JsonError.error_description) `nErrorCode: $($JsonError.error_code) `nHttp Status Code: $($HttpResponse.StatusCode.value__) `nHttp Description: $($HttpResponse.StatusDescription)" } } }
PowerShellCorpus/PowerShellGallery/vscodeextensions/0.1.2/Private/Get-VSCodeExtensionFolder.ps1
Get-VSCodeExtensionFolder.ps1
Function Get-VSCodeExtensionFolder { [CmdletBinding()] [OutputType([String])] param ( [parameter(Position=0)] [switch]$Insiders ) Process { if ($Insiders) { $Folder = "$HOME\.vscode-insiders\extensions" } else { $Folder = "$HOME\.vscode\extensions" } Return $Folder } }
PowerShellCorpus/PowerShellGallery/vscodeextensions/0.1.2/Private/Add-VSCodeMetadata.ps1
Add-VSCodeMetadata.ps1
Function Add-VSCodeMetadata { [CmdletBinding()] param ( [Parameter(Mandatory=$true,ValueFromPipeline=$true,Position=0)] [PSCustomObject]$Extension, [Parameter(Position=1)] [switch]$Insiders ) Process { Try { $ExtensionFolder = "$($Extension.Fullname)-$($Extension.version)" $ExtensionPath = Join-Path -Path (Get-VSCodeExtensionFolder -Insiders:$Insiders) -ChildPath $ExtensionFolder $Packagejson = Get-ChildItem -Path "$ExtensionPath\package.json" $ExtensionId = $Extension.extensionid $PublisherId = $Extension.publisher.publisherId $PublisherName = $Extension.publisherName $Metadata = @" { "__metadata": { "id": "$ExtensionId", "publisherId": "$PublisherId", "publisherDisplayName": "$PublisherName" }, "@ $Content = [IO.File]::ReadAllText($Packagejson) -replace '^{',$Metadata [IO.File]::WriteAllText($Packagejson, $Content) } catch { Throw } } }
PowerShellCorpus/PowerShellGallery/vscodeextensions/0.1.2/Private/Expand-VSCodeVsix.ps1
Expand-VSCodeVsix.ps1
Function Expand-VSCodeVsix { [CmdletBinding()] param ( [Parameter(ParameterSetName="Name",Mandatory=$true,ValueFromPipelineByPropertyName=$true,Position=0)] [string[]]$FullName, [Parameter(ParameterSetName="Name",Mandatory=$true,ValueFromPipelineByPropertyName=$true,Position=1)] [string[]]$Version, [Parameter(ParameterSetName="Path",Mandatory=$true,ValueFromPipelineByPropertyName=$true,Position=0)] [string]$Source, [Parameter(ParameterSetName="Path",Mandatory=$true,ValueFromPipelineByPropertyName=$true,Position=1)] [string]$Destination ) Process { if (($psCmdlet.ParameterSetName) -eq 'Name') { $ExtensionFolder = "$($Fullname)-$($version)" $Source = "$Env:TEMP\$ExtensionFolder.zip" $Destination = "$Env:TEMP\$ExtensionFolder" } if (Test-Path -Path $Destination) { Remove-Item -Path $Destination -Recurse -Force -ErrorAction SilentlyContinue } Try { Add-Type -assembly system.io.compression.filesystem [io.compression.zipfile]::ExtractToDirectory($Source, $Destination) } catch { Throw "failed to unzip Vsix" } } }
PowerShellCorpus/PowerShellGallery/vscodeextensions/0.1.2/Private/Get-VSCodeInstallation.ps1
Get-VSCodeInstallation.ps1
Function Get-VSCodeInstallation { [CmdletBinding()] [OutputType([PSCustomObject])] param ( [parameter(Position=0)] [switch]$Insiders ) Process { if ($Insiders) { $DisplayName = 'Microsoft Visual Studio Code Insiders' } else { $DisplayName = 'Microsoft Visual Studio Code' } switch ($env:PROCESSOR_ARCHITECTURE) { 'AMD64' { $UninstallKey = 'HKLM:\\SOFTWARE\\WOW6432Node\\Microsoft\\Windows\\CurrentVersion\\Uninstall\\*' } 'x86' { $UninstallKey = 'HKLM:\\SOFTWARE\\Microsoft\\Windows\\CurrentVersion\\Uninstall\\*' } } $Products = Get-ItemProperty -Path $UninstallKey | Select DisplayName, DisplayVersion, InstallLocation if ($Products.DisplayName -contains $DisplayName) { return $Products.Where({$_.DisplayName -eq $DisplayName}) } } }
PowerShellCorpus/PowerShellGallery/vscodeextensions/0.1.2/Private/Install-VSCodeVsix.ps1
Install-VSCodeVsix.ps1
Function Install-VSCodeVsix { [CmdletBinding()] param ( [Parameter(Mandatory=$true,ValueFromPipelineByPropertyName=$true,Position=0)] [string[]]$FullName, [Parameter(Mandatory=$true,ValueFromPipelineByPropertyName=$true,Position=1)] [string[]]$Version, [Parameter(Position=2)] [switch]$Insiders ) Process { $ExtensionFolder = "$($Fullname)-$($version)" $Destination = Join-Path -Path (Get-VSCodeExtensionFolder -Insiders:$Insiders) -ChildPath $ExtensionFolder Try { Copy-Item -Path "$env:TEMP\$ExtensionFolder\Extension" -Destination $Destination -Recurse -Force } catch { Throw "Failed to Copy Extension Folder" } Try { Copy-Item -Path "$env:TEMP\$ExtensionFolder\extension.vsixmanifest" -Destination "$Destination\.vsixmanifest" -Force } catch { Throw "Failed to Copy Manifest" } } }
PowerShellCorpus/PowerShellGallery/vscodeextensions/0.1.2/Public/Install-VSCodeExtension.ps1
Install-VSCodeExtension.ps1
# .ExternalHelp VSCodeExtensions-Help.xml function Install-VSCodeExtension { [CmdletBinding(DefaultParameterSetName="ExtensionName",SupportsShouldProcess=$true)] param ( [Parameter(ParameterSetName="ExtensionName",Mandatory=$true,ValueFromPipelineByPropertyName=$true,Position=0)] [string[]]$ExtensionName, [Parameter(ParameterSetName="DisplayName",Mandatory=$true,ValueFromPipelineByPropertyName=$true,Position=0)] [string[]]$DisplayName, [Parameter(Mandatory=$false,ValueFromPipelineByPropertyName=$true,Position=1)] [string[]]$PublisherName, [ValidateSet('Languages','Snippets','Linters','Debuggers','Other','Themes','Productivity')] [string[]]$Category, [string[]]$Tag, [switch]$Insiders ) Begin {} Process { $Null = $PSBoundParameters.Remove('Insiders') $Null = $PSBoundParameters.Remove('WhatIf') $Null = $PSBoundParameters.Remove('Confirm') $Extensions = Find-VSCodeExtension @PSBoundParameters $InstalledExtensions = Get-VSCodeExtension -Insiders:$Insiders $ExtensionGroups = $InstalledExtensions | Group-Object -Property 'FullName' if ($Extensions) { foreach ($Extension in $Extensions) { $InstalledVersion = $ExtensionGroups | Where-Object { $_.Name -eq $Extension.FullName } | Select-Object -ExpandProperty Group | Sort-Object -Descending -Property Version | Select-Object -First 1 if ($InstalledExtensions.FullName -contains $Extension.FullName -AND $InstalledVersion.Version -ge $Extension.Version ) { Write-Verbose -Message "Extension $($Extension.FullName) is already Installed" } else { Write-Verbose -Message "Installing Extension: $($Extension.FullName)" if ($PSCmdlet.ShouldProcess($($Extension.FullName), 'Install Extension')) { Try { Write-Debug -Message "Downloading the VSIX Package" $Extension | Get-VSCodeVsix Write-Debug -Message "Expanding the VSIX Archive" $Extension | Expand-VSCodeVsix Write-Debug -Message "Installing the VSIX to Extension Directory" $Extension | Install-VSCodeVsix -Insiders:$Insiders Write-Debug -Message "Adding Metadata to the package.json" $Extension | Add-VSCodeMetadata -Insiders:$Insiders Write-Debug -Message "Gathering Installed Extensions" $InstalledExtensions = Get-VSCodeExtension -Insiders:$Insiders } catch { Throw } if ($InstalledExtensions.FullName -contains $Extension.FullName) { Write-Verbose "Extension $($Extension.FullName) install complete. Restart VS code if open." } else { Write-Error "Extension $($Extension.FullName) install failed" } } } } } else { Write-Warning -Message "Could not find Extension" } } }
PowerShellCorpus/PowerShellGallery/vscodeextensions/0.1.2/Public/Uninstall-VSCodeExtension.ps1
Uninstall-VSCodeExtension.ps1
# .ExternalHelp VSCodeExtensions-Help.xml function Uninstall-VSCodeExtension { [CmdletBinding(DefaultParameterSetName="ExtensionName",SupportsShouldProcess=$true)] param ( [Parameter(ParameterSetName="ExtensionName",Mandatory=$true,ValueFromPipelineByPropertyName=$true,Position=0)] [string[]]$ExtensionName, [Parameter(ParameterSetName="DisplayName",Mandatory=$true,ValueFromPipelineByPropertyName=$true,Position=0)] [string[]]$DisplayName, [Parameter(Mandatory=$false,ValueFromPipelineByPropertyName=$true,Position=1)] [string[]]$PublisherName, [switch]$Insiders ) Begin {} Process { $InstalledExtensions = Get-VSCodeExtension $Insiders $Name = $psCmdlet.MyInvocation.BoundParameters["$($psCmdlet.ParameterSetName)"] Write-Verbose -Message "Uninstalling: $($Name)" switch ($psCmdlet.ParameterSetName) { 'ExtensionName' { $Extensions = $InstalledExtensions | Where-Object { $_.ExtensionName -Like $ExtensionName } } 'DisplayName' { $Extensions = $InstalledExtensions | Where-Object { $_.DisplayName -like $DisplayName } } } if ($PublisherName) { $PubExts = @() foreach ($Item in $PublisherName) { $PubExts += $Extensions | Where-Object { $_.PublisherName -like $item } } $Extensions = $PubExts | Sort-Object -Property ExtensionName -Unique } If ($Extensions) { foreach ($Extension in $Extensions) { if ($PSCmdlet.ShouldProcess($($Extension.ExtensionName), 'Uninstall Extension')) { Write-Verbose -Message "Uninstalling Extension: $($Extension.ExtensionName)" Try { Write-Debug -Message "Removing Directory $($Extension.ExtensionPath)" Remove-Item -Path $Extension.ExtensionPath -Recurse -Force $InstalledExtensions = Get-VSCodeExtension $Insiders } Catch { Throw } if ($InstalledExtensions.ExtensionPath -notcontains $Extension.ExtensionPath) { Write-Verbose "Extension $($Extension.ExtensionName) uninstall complete." } else { Write-Error "Extension $($Extension.ExtensionName) uninstall failed" } } } } else { Write-Warning -Message "No Matching Installed Extensions found for $($Name)" } } }
PowerShellCorpus/PowerShellGallery/vscodeextensions/0.1.2/Public/Find-VSCodeExtension.ps1
Find-VSCodeExtension.ps1
# .ExternalHelp VSCodeExtensions-Help.xml function Find-VSCodeExtension { [CmdletBinding(DefaultParameterSetName="ExtensionName")] [OutputType([PSCustomObject])] param ( [Parameter(ParameterSetName="ExtensionName",Mandatory=$true,ValueFromPipelineByPropertyName=$true,Position=0)] [SupportsWildcards()] [PSDefaultValue(Help='*')] [string[]]$ExtensionName = '*', [Parameter(ParameterSetName="DisplayName",Mandatory=$true,ValueFromPipelineByPropertyName=$true,Position=0)] [string[]]$DisplayName, [Parameter(Mandatory=$false,ValueFromPipelineByPropertyName=$true,Position=1)] [string[]]$PublisherName, [Parameter(Mandatory=$false)] [ValidateSet('Languages','Snippets','Linters','Debuggers','Other','Themes','Productivity')] [string[]]$Category, [Parameter(Mandatory=$false)] [string[]]$Tag ) Begin { $Results = Invoke-RestMethod -Method Get -Uri 'https://vscode.blob.core.windows.net/gallery/index' } Process { $Name = $psCmdlet.MyInvocation.BoundParameters["$($psCmdlet.ParameterSetName)"] Write-Verbose -Message "Finding: $($Name)" switch ($psCmdlet.ParameterSetName) { 'ExtensionName' { $Extensions = $Results.results.extensions | Where-Object { $_.ExtensionName -like $ExtensionName } } 'DisplayName' { $Extensions = $Results.results.extensions | Where-Object { $_.DisplayName -like $DisplayName } } } if ($PublisherName) { $PubExts = @() foreach ($Item in $PublisherName) { $PubExts += $Extensions | Where-Object { $_.Publisher.PublisherName -like $item } } $Extensions = $PubExts | Sort-Object -Property ExtensionName -Unique } if ($Category) { $CatExts = @() foreach ($Item in $Category) { $CatExts += $Extensions | Where-Object { $_.categories -contains $item } } $Extensions = $CatExts | Sort-Object -Property ExtensionName -Unique } if ($Tag) { $TagExts = @() foreach ($Item in $Tag) { $TagExts += $Extensions | Where-Object { $_.tags -like $item } } $Extensions = $TagExts | Sort-Object -Property ExtensionName -Unique } if ($Extensions) { foreach ($Extension in $Extensions) { $Extension | Add-Member -MemberType NoteProperty -Name Installs -Value (($Extension.statistics | Where-Object { $_.statisticName -eq 'Install' }).value) $Extension | Add-Member -MemberType NoteProperty -Name publisherName -Value $Extension.publisher.publisherName $Extension | Add-Member -MemberType NoteProperty -Name FullName -Value ($Extension.publisher.publisherName + '.' + $Extension.ExtensionName) $Extension | Add-Member -MemberType NoteProperty -Name Version -Value $Extension.Versions[0].version $Extension | Add-Member -MemberType NoteProperty -Name assetUri -Value $Extension.versions[0].assetUri $Extension } } else { Write-Warning "Could not find Extension like $($Name)" } } }
PowerShellCorpus/PowerShellGallery/vscodeextensions/0.1.2/Public/Update-VSCodeExtension.ps1
Update-VSCodeExtension.ps1
# .ExternalHelp VSCodeExtensions-Help.xml function Update-VSCodeExtension { [CmdletBinding(SupportsShouldProcess=$true)] [OutputType([PSCustomObject])] param ( [switch]$Insiders, [switch]$Passthru ) Begin {} Process { $InstalledExtensions = Get-VSCodeExtension -Insiders:$Insiders $GalleryExtensions = Find-VSCodeExtension -ExtensionName '*' $ExtensionGroups = $InstalledExtensions | Group-Object -Property 'FullName' foreach ($Group in $ExtensionGroups) { if ($Group.Count -gt '1') { Write-Debug -Message "Filtering out old Versions" $Extension = ($Group.Group | Sort-Object -Descending -Property Version)[0] } else { $Extension = $Group.Group } $LatestVersion = $GalleryExtensions | Where-Object { $_.FullName -eq $Extension.FullName } if ($LatestVersion) { If ([Version]$Extension.Version -lt [Version]$LatestVersion.Version) { Write-Verbose -Message "Extension $($Extension.FullName) with Version $($Extension.Version) needs to be updated" Write-Verbose -Message "New Version $($LatestVersion.Version) available." if ($PSCmdlet.ShouldProcess($($Extension.FullName), 'Update Extension')) { Try { Write-Verbose -Message "Installing Extension Update $($Extension.FullName)" Install-VSCodeExtension -ExtensionName $Extension.ExtensionName -PublisherName $Extension.PublisherName -Insiders:$Insiders if ($Passthru) { [PSCustomObject]@{ Name = $Extension.FullName Version = $LatestVersion.Version } } } catch { Throw } } } else { Write-Verbose -Message "No Updates available for Extension $($Extension.FullName)" } } else { Write-Warning -Message "Extension $($Extension.FullName) was not found in the Gallery" } } } }
PowerShellCorpus/PowerShellGallery/vscodeextensions/0.1.2/Public/Get-VSCodeExtension.ps1
Get-VSCodeExtension.ps1
# .ExternalHelp VSCodeExtensions-Help.xml function Get-VSCodeExtension { [CmdletBinding()] [OutputType([PSCustomObject])] param ( [Parameter(Position=0)] [switch]$Insiders ) Begin {} Process { #TODO: Make this searchable by Packages $ExtensionPath = Get-VSCodeExtensionFolder -Insiders:$Insiders Write-Debug -Message "Using Extension Path: $($ExtensionPath)" If (Test-Path -Path $ExtensionPath) { $ExtensionDirs = Get-ChildItem -Path $ExtensionPath -Directory -ErrorAction SilentlyContinue if ($ExtensionDirs) { foreach ($ExtensionDir in $ExtensionDirs) { $PackageJson = Get-Content -Path "$($ExtensionDir.FullName)\package.json" -Raw -ErrorAction SilentlyContinue | ConvertFrom-Json if ($PackageJson) { $Extension = [PSCustomObject]@{ 'FullName' = "$($PackageJson.Publisher).$($PackageJson.Name)" 'ExtensionName' = $PackageJson.Name 'DisplayName' = $PackageJson.DisplayName 'Version' = $PackageJson.Version 'PublisherName' = $PackageJson.Publisher 'Homepage' = $PackageJson.Homepage 'ExtensionPath' = $ExtensionDir.FullName } If ($Insiders) { $Extension | Add-Member -MemberType NoteProperty -Name 'Insiders' -Value $True } $Extension } } } else { Write-Verbose -Message 'No extensions installed.' } } else { Write-Verbose -Message "${ExtensionPath} does not exist. Creating it." $null = New-Item -Path $ExtensionPath -ItemType Directory -Force } } }
PowerShellCorpus/PowerShellGallery/vscodeextensions/0.1.2/Public/Get-VSCodeExtensionStats.ps1
Get-VSCodeExtensionStats.ps1
# .ExternalHelp VSCodeExtensions-Help.xml function Get-VSCodeExtensionStats { [CmdletBinding(DefaultParameterSetName="ExtensionName")] [OutputType([PSCustomObject])] param ( [Parameter(ParameterSetName="ExtensionName",Mandatory=$true,ValueFromPipelineByPropertyName=$true,Position=0)] [string[]]$ExtensionName, [Parameter(ParameterSetName="DisplayName",Mandatory=$true,ValueFromPipelineByPropertyName=$true,Position=0)] [string[]]$DisplayName, [Parameter(Mandatory=$false,ValueFromPipelineByPropertyName=$true,Position=1)] [string[]]$PublisherName, [Parameter(Mandatory=$false)] [ValidateSet('Languages','Snippets','Linters','Debuggers','Other','Themes','Productivity')] [string[]]$Category, [Parameter(Mandatory=$false)] [string[]]$Tag ) Begin {} Process { Update-FormatData -AppendPath $PSScriptRoot\..\Formats\ExtensionStats.format.ps1xml Try { $Results = Find-VSCodeExtension @PSBoundParameters } catch { throw } if ($Results) { foreach ($Result in $Results) { Write-Verbose -Message "Gathering Statistics for $($Result)" $ExtensionStats = [PSCustomObject]@{ 'DisplayName' = $Result.DisplayName 'PublisherName' = $Result.Publisher.PublisherName 'InstallCount' = ($Result.statistics | Where-Object { $_.statisticName -eq 'Install' }).value 'AverageRating' = ($Result.statistics | Where-Object { $_.statisticName -eq 'averagerating' }).value 'ratingcount' = ($Result.statistics | Where-Object { $_.statisticName -eq 'ratingcount' }).value 'trendingdaily' = ($Result.statistics | Where-Object { $_.statisticName -eq 'trendingdaily' }).value 'trendingweekly' = ($Result.statistics | Where-Object { $_.statisticName -eq 'trendingweekly' }).value 'trendingmonthly' = ($Result.statistics | Where-Object { $_.statisticName -eq 'trendingmonthly' }).value } $ExtensionStats.pstypenames.insert(0,'VSCodeExtensions.ExtensionStats') $ExtensionStats } } else { Write-Error "No Results were found" } } }
PowerShellCorpus/PowerShellGallery/vscodeextensions/0.1.2/Public/Get-VSCodePublisherStats.ps1
Get-VSCodePublisherStats.ps1
# .ExternalHelp VSCodeExtensions-Help.xml function Get-VSCodePublisherStats { [CmdletBinding()] [OutputType([PSCustomObject])] param ( [Parameter(Mandatory=$true)] [string]$PublisherName ) Begin { $Results = Invoke-RestMethod -Method Get -Uri 'https://vscode.blob.core.windows.net/gallery/index' } Process { $Installs = $null Update-FormatData -AppendPath $PSScriptRoot\..\Formats\PublisherStats.format.ps1xml $Extensions = $Results.results.extensions | Where-Object { $_.Publisher.PublisherName -like $PublisherName } if ($Extensions) { Write-Verbose -Message "Collecting Publisher Statistics" foreach ($Extension in $Extensions) { $Count = ($Extension.statistics | Where-Object { $_.statisticName -eq 'Install' }).value $Installs = $Installs + $Count } $PublisherID = $Extensions.Publisher.PublisherID | Select-Object -Unique $MostDownloads = $Extensions.displayName[0] $MostDownloadsCount = $Extensions.statistics | Where-Object { $_.statisticName -eq 'Install' } | Select-Object -ExpandProperty value -First 1 Write-Verbose -Message "PublisherName: $($PublisherName)" Write-Verbose -Message "PublisherID: $($PublisherID)" Write-Verbose -Message "Most Downloads: $($MostDownloads)" Write-Verbose -Message "Most Downloads Count: $($MostDownloadsCount)" Write-Verbose -Message "Total Installs: $($Installs)" $PublisherStats = [PSCustomObject]@{ 'PublisherName' = $PublisherName 'PublisherID' = $PublisherID 'TotalInstalls' = $Installs 'ExtensionCount' = $Extensions.count 'MostDownloads' = $MostDownloads 'MostDownloadsCount' = $MostDownloadsCount } $PublisherStats.pstypenames.insert(0,'VSCodeExtensions.PublisherStats') } else { Write-Error "There were no Results for $($PublisherName)" } $PublisherStats } }
PowerShellCorpus/PowerShellGallery/PSCommonSql.Sqlite/1.0.37/New-SqliteConnectionString.Tests.ps1
New-SqliteConnectionString.Tests.ps1
[Diagnostics.CodeAnalysis.SuppressMessageAttribute("PSAvoidUsingConvertToSecureStringWithPlainText","")] param() $here = Split-Path -Parent $MyInvocation.MyCommand.Path #$sut = (Split-Path -Leaf $MyInvocation.MyCommand.Path).Replace(".Tests.", ".") Import-Module $here Describe "New-SqliteConnectionString" { It "Generates a valid connection string with DataSource" { $ConnectionString = New-SqliteConnectionString -DataSource "c:\pester.db" $ConnectionString.ConnectionString | Should Be "DataSource=c:\pester.db" } It "Generates a valid connection string with DataSource and Password" { $PesterPassword = ConvertTo-SecureString -AsPlainText -Force -String "pass" $ConnectionString = New-SqliteConnectionString -DataSource "c:\pester.db" -Password $PesterPassword $ConnectionString.ConnectionString | Should Be "DataSource=c:\pester.db;Password=pass" } It "Generates a valid connection string with DataSource and ReadOnly" { $ConnectionString = New-SqliteConnectionString -DataSource "c:\pester.db" -ReadOnly $ConnectionString.ConnectionString | Should Be "DataSource=c:\pester.db;ReadOnly=True" } It "Includes the DbProviderName" { $ConnectionString = New-SqliteConnectionString -DataSource "c:\pester.db" $ConnectionString.DbProviderName | Should Be "System.Data.Sqlite" } }
PowerShellCorpus/PowerShellGallery/PSCommonSql.Sqlite/1.0.37/New-SqliteConnection.ps1
New-SqliteConnection.ps1
function New-SQLiteConnection { <# .SYNOPSIS Creates a SQLiteConnection to a SQLite data source .DESCRIPTION Creates a SQLiteConnection to a SQLite data source .PARAMETER DataSource SQLite Data Source to connect to. .PARAMETER Password Specifies A Secure String password to use in the SQLite connection string. SECURITY NOTE: If you use the -Debug switch, the connectionstring including plain text password will be sent to the debug stream. .PARAMETER ReadOnly If specified, open SQLite data source as read only .PARAMETER Open We open the connection by default. You can use this parameter to create a connection without opening it. .OUTPUTS System.Data.SQLite.SQLiteConnection .EXAMPLE $Connection = New-SQLiteConnection -DataSource C:\NAMES.SQLite Invoke-SQLiteQuery -SQLiteConnection $Connection -query $Query # Connect to C:\NAMES.SQLite, invoke a query against it .EXAMPLE $Connection = New-SQLiteConnection -DataSource :MEMORY: Invoke-SqliteQuery -SQLiteConnection $Connection -Query "CREATE TABLE OrdersToNames (OrderID INT PRIMARY KEY, fullname TEXT);" Invoke-SqliteQuery -SQLiteConnection $Connection -Query "INSERT INTO OrdersToNames (OrderID, fullname) VALUES (1,'Cookie Monster');" Invoke-SqliteQuery -SQLiteConnection $Connection -Query "PRAGMA STATS" # Create a connection to a SQLite data source in memory # Create a table in the memory based datasource, verify it exists with PRAGMA STATS $Connection.Close() $Connection.Open() Invoke-SqliteQuery -SQLiteConnection $Connection -Query "PRAGMA STATS" #Close the connection, open it back up, verify that the ephemeral data no longer exists .LINK https://github.com/RamblingCookieMonster/Invoke-SQLiteQuery .LINK Invoke-SQLiteQuery .FUNCTIONALITY SQL #> [cmdletbinding()] [OutputType([System.Data.Common.DbConnection])] [Diagnostics.CodeAnalysis.SuppressMessageAttribute("PSUseShouldProcessForStateChangingFunctions","")] param( [Parameter( Position=0, Mandatory=$true, ValueFromPipeline=$true, ValueFromPipelineByPropertyName=$true, ValueFromRemainingArguments=$false, HelpMessage='Connection String required...' )] [ValidateNotNullOrEmpty()] [string[]] $ConnectionString, [Parameter( Position=1, Mandatory=$false, ValueFromPipelineByPropertyName=$true, ValueFromRemainingArguments=$false )] [bool] $Open = $True ) Process { foreach($String in $ConnectionString) { $conn = New-SqlConnection @PSBoundParameters -DbProviderName $Script:DbProviderName $conn.ParseViaFramework = $true $conn } } }
PowerShellCorpus/PowerShellGallery/PSCommonSql.Sqlite/1.0.37/Get-SqliteDbProviderFactory.ps1
Get-SqliteDbProviderFactory.ps1
function Get-SqliteDbProviderFactory { PSCommonSql\Get-DbProviderFactory -DbProviderName "System.Data.Sqlite" }
PowerShellCorpus/PowerShellGallery/PSCommonSql.Sqlite/1.0.37/New-SqliteConnectionString.ps1
New-SqliteConnectionString.ps1
function New-SQLiteConnectionString { [cmdletbinding()] [OutputType([String])] [Diagnostics.CodeAnalysis.SuppressMessageAttribute("PSUseShouldProcessForStateChangingFunctions","")] param( [Parameter( Position=0, Mandatory=$true, ValueFromPipeline=$true, ValueFromPipelineByPropertyName=$true, ValueFromRemainingArguments=$false, HelpMessage='SQL Server Instance required...' )] [Alias( 'Instance', 'Instances', 'ServerInstance', 'Server', 'Servers','cn','Path','File','FullName','Database' )] [ValidateNotNullOrEmpty()] [string[]] $DataSource, [Parameter( Position=2, Mandatory=$false, ValueFromPipelineByPropertyName=$true, ValueFromRemainingArguments=$false )] [System.Security.SecureString] $Password, [Parameter( Position=3, Mandatory=$false, ValueFromPipelineByPropertyName=$true, ValueFromRemainingArguments=$false )] [Switch] $ReadOnly ) Begin { $SqliteFactory = Get-SqliteDbProviderFactory } Process { foreach($DataSRC in $DataSource) { $ConnectionStringBuilder = $SqliteFactory.CreateConnectionStringBuilder() Write-Verbose "Creating connection string for Data Source '$DataSRC'" $PSBoundParameters.Keys | ForEach-Object { $Name = $_ switch($Name) { "Password" { $BSTR = [System.Runtime.InteropServices.Marshal]::SecureStringToBSTR($Password) $PlainPassword = [System.Runtime.InteropServices.Marshal]::PtrToStringAuto($BSTR) $ConnectionStringBuilder.Password = $PlainPassword } "DataSource" { $ConnectionStringBuilder.DataSource = $DataSrc } default { if($PSBoundParameters[$Name] -is [System.Management.Automation.SwitchParameter]) { $Value = [Boolean]$PSBoundParameters[$Name] } else { $Value = $PSBoundParameters[$Name] } $ConnectionStringBuilder."$Name" = $Value } } } $ConnectionString = $ConnectionStringBuilder.ConnectionString Write-Debug "ConnectionString $ConnectionString" [PSCustomObject]@{ ConnectionString = $ConnectionString DbProviderName = "System.Data.SQLite" } } } }
PowerShellCorpus/PowerShellGallery/AzureRM.BootStrapper/0.1.0/AzureRM.BootStrapper.Tests.ps1
AzureRM.BootStrapper.Tests.ps1
#Requires -Modules AzureRM.BootStrapper $global:testProfileMap = "{`"Profile1`": { `"Module1`": [`"1.0`"], `"Module2`": [`"1.0`"] }, `"Profile2`": { `"Module1`": [`"2.0`", `"1.0`"], `"Module2`": [`"2.0`"] }}" Describe "Get-ProfileCachePath" { InModuleScope AzureRM.Bootstrapper { Context "Windows OS Admin" { $IsWindows = $true $Script:IsAdmin = $true It "Should return ProgramData path" { $result = Get-ProfileCachePath $result | Should Match "(.*)ProfileCache$" $result.Contains("ProgramData") | Should Be $true } } Context "Windows OS Non-Admin" { $IsWindows = $true $Script:IsAdmin = $false It "Should return LOCALAPPDATA path" { $result = Get-ProfileCachePath $result | Should Match "(.*)ProfileCache$" $result.Contains("AppData\Local") | Should Be $true } } Context "Linux OS Admin" { $IsWindows = $false $Script:IsCoreEdition = $true It "Should return .config path" { $result = Get-ProfileCachePath $result | Should Match "(.*)ProfileCache$" $result.Contains(".config") | Should Be $true } } # Cleanup $Script:IsCoreEdition = ($PSVersionTable.PSEdition -eq 'Core') $script:IsAdmin = $false if ((-not $Script:IsCoreEdition) -or ($IsWindows)) { If (([Security.Principal.WindowsPrincipal] [Security.Principal.WindowsIdentity]::GetCurrent()).IsInRole([Security.Principal.WindowsBuiltInRole] "Administrator")) { $script:IsAdmin = $true } } else { # on Linux, tests run via sudo will generally report "root" for whoami if ( (whoami) -match "root" ) { $script:IsAdmin = $true } } } } Describe "Get-LatestProfileMapPath" { InModuleScope AzureRM.Bootstrapper { Mock Get-ProfileCachePath -Verifiable { "foo\bar" } Context "ProfileCache is empty/no profilemaps available" { Mock Test-Path -Verifiable { $true } Mock Get-ChildItem -Verifiable { $null } It "Should return null" { Get-LatestProfileMapPath | Should be $null } } Context "Two profile maps available at profile cache" { Mock Test-Path -Verifiable {$true} $profilemap1 = New-Object -TypeName PSObject $profilemap1 | Add-Member NoteProperty -Name "Name" -Value '123-pmap1.json' $profilemap2 = New-Object -TypeName PSObject $profilemap2 | Add-Member NoteProperty -Name "Name" -Value '42-pmap2.json' Mock Get-ChildItem -Verifiable { @($profilemap1, $profilemap2)} Mock Get-LargestNumber -Verifiable { 123 } It "Should return Latest map" { Get-LatestProfileMapPath | Should Be $profilemap1 } } } } Describe "Get-LargestNumber" { InModuleScope AzureRM.BootStrapper { Context "Profile cache is empty" { Mock Get-ChildItem -Verifiable { } It "Should return null" { Get-LargestNumber | Should Be $null } } Context "ProfileMaps weren't numbered" { $profilemap1 = New-Object -TypeName PSObject $profilemap1 | Add-Member NoteProperty -Name "Name" -Value 'pmap1.json' $profilemap2 = New-Object -TypeName PSObject $profilemap2 | Add-Member NoteProperty -Name "Name" -Value 'pmap2.json' Mock Get-ChildItem -Verifiable { @($profilemap1, $profilemap2) } It "Should return null" { Get-LargestNumber | Should Be $null } } Context "Two numbered Profiles were returned" { $profilemap1 = New-Object -TypeName PSObject $profilemap1 | Add-Member NoteProperty -Name "Name" -Value '123-pmap1.json' $profilemap2 = New-Object -TypeName PSObject $profilemap2 | Add-Member NoteProperty -Name "Name" -Value '456-pmap2.json' Mock Get-ChildItem -Verifiable { @($profilemap1, $profilemap2) } It "Should return largest number" { Get-LargestNumber | Should Be 456 } } } } Describe "Get-AzureStorageBlob" { InModuleScope AzureRM.Bootstrapper { Context "Invoke-WebRequest is properly made" { It "Returns proper response" { $result = Get-AzureStorageBlob $result.Headers["Content-Type"] | Should Be "application/json" $result.StatusCode | Should Be "200" } } Context "Invoke-WebRequest threw exception" { $PSProfileMapEndpoint = "http://foo.bar" It "Throws exception" { { Get-WebResponse } | Should throw } } } } Describe "RetryGetContent" { InModuleScope AzureRM.Bootstrapper { Context "Gets content at first attempt" { Mock Get-Content -Verifiable { $global:testProfileMap } It "Should return successfully" { $result = RetryGetContent -FilePath ".\MockPath" $result.Profile1 | Should Not Be Empty $result.Profile2 | Should Not Be Empty Assert-VerifiableMocks } } Context "Gets content at one of the retries" { $Script:mockCalled = 0 $mockTestPath = { $Script:mockCalled++ if ($Script:mockCalled -eq 1) { throw } else { return $global:testProfileMap } } Mock -CommandName Get-Content -MockWith $mockTestPath Mock Start-Sleep -Verifiable {} It "Should return successfully" { RetryGetContent -FilePath ".\MockPath" Assert-MockCalled Get-Content -Times 2 Assert-VerifiableMocks } } Context "Fails to get content during all retries" { Mock Get-Content -Verifiable { throw } Mock Start-Sleep -Verifiable {} It "Returns null" { RetryGetContent -FilePath ".\MockPath" | Should Be $null } } } } Describe "Get-AzureProfileMap" { InModuleScope AzureRM.Bootstrapper { $script:LatestProfileMapPath = New-Object -TypeName PSObject $script:LatestProfileMapPath | Add-Member NoteProperty -Name "FullName" -Value "C:\mock\123-MockETag.json" Mock Get-ProfileCachePath -Verifiable { return "MockPath\ProfileCache"} $WebResponse = New-Object -TypeName PSObject $Header = @{"Headers" = @{"ETag" = "MockETag"}} $WebResponse | Add-Member $Header Mock Get-AzureStorageBlob -Verifiable { return $WebResponse } Mock RetryGetContent -Verifiable { ($testProfileMap | ConvertFrom-Json) } Context "ProfileCachePath Exists and Etags are equal" { Mock Test-Path -Verifiable { $true } It "Returns Correct ProfileMap" { $result = Get-AzureProfileMap $result.Profile1 | Should Not Be Empty $result.Profile2 | Should Not Be Empty Assert-VerifiableMocks } } Context "ProfileCachePath Exists and ETags are different" { Mock Out-File -Verifiable {} $script:LatestProfileMapPath.FullName = "123-MockedDifferentETag.json" Mock RetrieveProfileMap -Verifiable {$global:testProfileMap | ConvertFrom-Json} Mock Get-LargestNumber -Verifiable {} $ProfileMapPath = New-Object -TypeName PSObject $ProfileMapPath | Add-Member NoteProperty 'FullName' -Value '124-MockedDifferentETag.json' Mock Get-ChildItem -Verifiable { @($ProfileMapPath)} It "Returns Correct ProfileMap" { $result = Get-AzureProfileMap $result.Profile1 | Should Not Be Empty $result.Profile2 | Should Not Be Empty Assert-VerifiableMocks } } Context "Get-AzureStorageBlob throws exception" { Mock Get-AzureStorageBlob { throw [System.Net.WebException] } Mock Test-Path -Verifiable { $true } It "Throws Web Exception" { { Get-AzureProfileMap } | Should throw } } } } Describe "RetrieveProfileMap" { InModuleScope AzureRM.Bootstrapper { Context "WebResponse content has extra line breaks" { $WebResponse = New-Object -TypeName PSObject $WebResponse | Add-Member NoteProperty -Name "Content" -Value "{`n`"Profile1`":`t { `"Module1`": [`"1.0`"], `n`"Module2`": [`"1.0`"] }, `"Profile2`": `n{ `"Module1`": [`"2.0`", `"1.0`"],`n `r`"Module2`": `t[`"2.0`"] }}" It "Should return proper profile map" { (RetrieveProfileMap -WebResponse $WebResponse) -like ($global:testProfileMap | ConvertFrom-Json) | Should Be $true } } Context "WebResponse content has no extra line breaks" { $WebResponse = New-Object -TypeName PSObject $WebResponse | Add-Member NoteProperty -Name "Content" -Value $global:testProfileMap It "Should return proper profile map" { (RetrieveProfileMap -WebResponse $WebResponse) -like ($global:testProfileMap | ConvertFrom-Json) | Should Be $true } } } } Describe Get-AzProfile { InModuleScope AzureRM.Bootstrapper { Context "Forces update from Azure Endpoint" { Mock Get-AzureProfileMap { ($testProfileMap | ConvertFrom-Json) } It "Should get ProfileMap from Azure Endpoint" { $result = Get-AzProfile -Update $result.Profile1 | Should Not Be Empty $result.Profile2 | Should Not Be Empty } It "Checks Mock calls to Get-AzureProfileMap" { Assert-MockCalled Get-AzureProfileMap -Exactly 1 } } Context "Gets Azure ProfileMap from Cache" { $script:LatestProfileMapPath = New-Object -TypeName PSObject $script:LatestProfileMapPath | Add-Member NoteProperty -Name "FullName" -Value "C:\mock\MockETag.json" Mock RetryGetContent -Verifiable { $global:testProfileMap | ConvertFrom-Json } Mock Test-Path -Verifiable { $true } It "Should get ProfileMap from Cache" { $result = Get-AzProfile $result.Profile1 | Should Not Be Empty $result.Profile2 | Should Not Be Empty Assert-VerifiableMocks } } Context "ProfileMap is not available from cache" { Mock Test-Path -Verifiable { $false } Mock RetryGetContent -Verifiable { return $global:testProfileMap | ConvertFrom-Json} It "Should get ProfileMap from Embedded source" { $result = Get-AzProfile $result.Profile1 | Should Not Be Empty $result.Profile2 | Should Not Be Empty Assert-VerifiableMocks } } Context "ProfileMap is not available in cache or Embedded source" { Mock Test-Path -Verifiable { $false } Mock RetryGetContent -Verifiable {} It "Should throw FileNotFound Exception" { { Get-AzProfile } | Should Throw Assert-VerifiableMocks } } } } Describe "Get-ProfilesAvailable" { InModuleScope AzureRM.Bootstrapper { Context "Valid ProfilMap" { It "Should return array of profiles and module versions" { $result = Get-ProfilesAvailable ($global:testProfileMap | ConvertFrom-Json) $result.contains("Profile: Profile1") | Should Be $true $result.contains("Module1 : {1.0}") | Should Be $true } } Context "Null ProfileMap" { It "Should throw exception" { { Get-ProfilesAvailable -ProfileMap $null } | Should throw } } } } Describe "Get-ProfilesInstalled" { InModuleScope AzureRM.Bootstrapper { Context "Valid ProfileMap and Invoke with IncompleteProfiles parameter" { # Arrange $VersionObj = New-Object -TypeName System.Version -ArgumentList "1.0" $moduleObj = New-Object -TypeName PSObject $moduleObj | Add-Member NoteProperty Version($VersionObj) $Script:mockCalled = 0 $mockTestPath = { $Script:mockCalled++ if ($Script:mockCalled -le 4) { return $moduleObj } else { return $null } } Mock -CommandName Get-Module -MockWith $mockTestPath $IncompleteProfiles = @() $expected = @{'Profile1'= @{'Module1' = @('1.0') ;'Module2'= @('1.0')}} # Act $result = (Get-ProfilesInstalled -ProfileMap ($global:testProfileMap | ConvertFrom-Json) ([REF]$IncompleteProfiles)) # Assert It "Should return profiles installed" { $expected -like $result | Should Be $true } It "Should return Incomplete profiles" { $incompleteprofiles[0] -eq 'Profile2' | Should Be $true } } Context "No profiles Installed and invoke without IncompleteProfiles parameter" { Mock Get-Module -Verifiable {} It "Should return empty" { $result = (Get-ProfilesInstalled -ProfileMap ($global:testProfileMap | ConvertFrom-Json)) $result.count | Should Be 0 } } Context "Null ProfileMap" { It "Should throw exception" { { Get-ProfilesInstalled -ProfileMap $null } | Should Throw } } } } Describe "Remove-ProfileMapFile" { InModuleScope AzureRM.Bootstrapper { Context "ProfileMapPath exists" { Mock Test-Path -Verifiable { $true } Mock RemoveWithRetry -Verifiable {} It "Should call RemovewithRetry function" { Remove-ProfileMapFile ".\MockPath" Assert-VerifiableMocks } } Context "ProfileMapPath does not exist" { Mock Test-Path -Verifiable { $false } Mock RemoveWithRetry {} It "Should not call RemoveWithRetry" { Remove-ProfileMapFile ".\MockPath" Assert-MockCalled RemoveWithRetry -Exactly 0 Assert-VerifiableMocks } } } } Describe "RemoveWithRetry" { InModuleScope AzureRM.Bootstrapper { Context "Removes item at first attempt" { Mock Remove-Item -Verifiable {} It "Should return successfully" { RemoveWithRetry -Path ".\MockPath" Assert-VerifiableMocks } } Context "Removes item at one of the retries" { $Script:mockCalled = 0 $mockTestPath = { $Script:mockCalled++ if ($Script:mockCalled -eq 1) { throw } else { return $null } } Mock -CommandName Remove-Item -MockWith $mockTestPath Mock Start-Sleep -Verifiable {} It "Should return successfully" { RemoveWithRetry -Path ".\MockPath" Assert-MockCalled Remove-Item -Times 2 Assert-VerifiableMocks } } Context "Fails to remove item during all retries" { Mock Remove-Item -Verifiable { throw } Mock Start-Sleep -Verifiable {} It "Should throw" { { RemoveWithRetry -Path ".\MockPath" } | Should throw } } } } Describe "Test-ProfilesInstalled" { InModuleScope AzureRm.Bootstrapper { Context "Profile associated with Module version is installed" { $AllProfilesInstalled = @{'Module11.0'= @('Profile1', 'Profile2'); 'Module22.0'= @('Profile2')} It "Should return ProfilesAssociated" { $Result = (Test-ProfilesInstalled -Module 'Module1' -Profile 'Profile1' -PMap ($global:testProfileMap | ConvertFrom-Json) -AllProfilesInstalled $AllProfilesInstalled) $Result[0] | Should Be 'Profile1' $Result[1] | Should Be 'Profile2' } } Context "Profile associated with Module version is not installed" { $AllProfilesInstalled = @{'Module11.0'= @('Profile1', 'Profile2')} It "Should return empty array" { $Result = (Test-ProfilesInstalled -Module 'Module2' -Profile 'Profile2' -PMap ($global:testProfileMap | ConvertFrom-Json) -AllProfilesInstalled $AllProfilesInstalled) $Result.Count | Should Be 0 } } } } Describe "Uninstall-ModuleHelper" { InModuleScope AzureRM.Bootstrapper { Mock Remove-Module -Verifiable { } Mock Uninstall-Module -Verifiable { } Context "Modules are installed" { # Arrange $VersionObj = New-Object -TypeName System.Version -ArgumentList "1.0" $moduleObj = New-Object -TypeName PSObject $moduleObj | Add-Member NoteProperty Version($VersionObj) $Script:mockCalled = 0 $mockTestPath = { $Script:mockCalled++ if ($Script:mockCalled -eq 1) { return $moduleObj } else { return $null } } Mock -CommandName Get-Module -MockWith $mockTestPath It "Should call Remove-Module and Uninstall-Module" { Uninstall-ModuleHelper -Module 'Module1' -Version '1.0' -Profile 'Profile1' -RemovePreviousVersions $Script:mockCalled | Should Be 2 Assert-VerifiableMocks } } Context "Modules are not installed" { Mock Get-Module -Verifiable {} It "Should not call Remove-Module or Uninstall-Module" { Uninstall-ModuleHelper -Module 'Module1' -Version '1.0' -Profile 'Profile1' Assert-MockCalled Remove-Module -Exactly 0 Assert-MockCalled Uninstall-Module -Exactly 0 } } } } Describe "Uninstall-ProfileHelper" { InModuleScope AzureRM.Bootstrapper { Mock Get-AllProfilesInstalled -Verifiable {} Mock Invoke-UninstallModule -Verifiable {} Context "Profile associated with the module is installed" { It "Should call Invoke-UninstallModule" { Uninstall-ProfileHelper -Profile 'Profile1' -PMap ($global:testProfileMap | ConvertFrom-Json) -Force Assert-VerifiableMocks Assert-MockCalled Invoke-UninstallModule -Exactly 2 } } } } Describe "Invoke-UninstallModule" { InModuleScope AzureRM.Bootstrapper { Context "Module not associated with any other profile" { Mock Test-ProfilesInstalled -Verifiable { 'profile1'} Mock Uninstall-ModuleHelper -Verifiable {} It "Should Call Uninstall module helper" { Invoke-UninstallModule -PMap ($global:testProfileMap | ConvertFrom-Json) -Profile 'profile1' -module 'module1' Assert-VerifiableMocks } } Context "Module associated with more than one profile" { Mock Test-ProfilesInstalled -Verifiable { @('Profile1', 'Profile2')} Mock Uninstall-ModuleHelper {} It "Should not invoke Uninstall module helper" { Invoke-UninstallModule -PMap ($global:testProfileMap | ConvertFrom-Json) -Profile 'profile1' -module 'module1' Assert-MockCalled Uninstall-ModuleHelper -Exactly 0 Assert-VerifiableMocks } } } } Describe "Remove-PreviousVersion" { InModuleScope AzureRM.Bootstrapper { $AllProfilesInstalled = @{} Context "Previous versions are installed" { $PreviousMap = "{`"Profile1`": { `"Module1`": [`"0.1`"], `"Module2`": [`"0.1`"] }, `"Profile2`": { `"Module1`": [`"2.0`", `"1.0`"], `"Module2`": [`"2.0`"] }}" $VersionObj = New-Object -TypeName System.Version -ArgumentList "0.1" $moduleObj = New-Object -TypeName PSObject $moduleObj | Add-Member NoteProperty Version($VersionObj) Mock Get-Module -Verifiable { $moduleObj} Mock Import-Module -Verifiable {} Mock Invoke-UninstallModule -Verifiable {} It "Should call Invoke-UninstallModule" { Remove-PreviousVersion -Profile 'Profile1' -PreviousMap ($PreviousMap|ConvertFrom-Json) -LatestMap ($global:testProfileMap|ConvertFrom-Json) Assert-VerifiableMocks } It "Invoke with Module parameter: Should call Invoke-UninstallModule" { Remove-PreviousVersion -Profile 'Profile1' -Module 'Module1' -PreviousMap ($PreviousMap|ConvertFrom-Json) -LatestMap ($global:testProfileMap|ConvertFrom-Json) Assert-VerifiableMocks } } Context "Previous versions are not installed" { $PreviousMap = "{`"Profile1`": { `"Module1`": [`"0.1`"], `"Module2`": [`"0.1`"] }, `"Profile2`": { `"Module1`": [`"2.0`", `"1.0`"], `"Module2`": [`"2.0`"] }}" Mock Get-Module -Verifiable {} Mock Import-Module -Verifiable {} Mock Invoke-UninstallModule {} It "Should not call Invoke-UninstallModule" { Remove-PreviousVersion -Profile 'Profile1' -PreviousMap ($PreviousMap|ConvertFrom-Json) -LatestMap ($global:testProfileMap|ConvertFrom-Json) Assert-VerifiableMocks Assert-MockCalled Invoke-UninstallModule -Exactly 0 } } Context "No previous versions" { $PreviousMap = "{`"Profile0`": { `"Module1`": [`"0.1`"], `"Module2`": [`"0.1`"] }, `"Profile3`": { `"Module1`": [`"2.0`", `"1.0`"], `"Module2`": [`"2.0`"] }}" Mock Get-Module -Verifiable {} Mock Invoke-UninstallModule -Verifiable {} It "Should not call Invoke-UninstallModule" { Remove-PreviousVersion -Profile 'Profile1' -PreviousMap ($PreviousMap|ConvertFrom-Json) -LatestMap ($global:testProfileMap|ConvertFrom-Json) Assert-MockCalled Get-Module -Exactly 0 Assert-MockCalled Invoke-UninstallModule -Exactly 0 } } Context "Previous version is same as the latest version" { $PreviousMap = "{`"Profile1`": { `"Module1`": [`"1.0`"], `"Module2`": [`"1.0`"] }, `"Profile2`": { `"Module1`": [`"2.0`", `"1.0`"], `"Module2`": [`"2.0`"] }}" Mock Get-Module -Verifiable {} Mock Invoke-UninstallModule -Verifiable {} It "Should not call Invoke-UninstallModule" { Remove-PreviousVersion -Profile 'Profile1' -PreviousMap ($PreviousMap|ConvertFrom-Json) -LatestMap ($global:testProfileMap|ConvertFrom-Json) Assert-MockCalled Get-Module -Exactly 0 Assert-MockCalled Invoke-UninstallModule -Exactly 0 } } } } Describe "Get-AllProfilesInstalled" { InModuleScope AzureRM.Bootstrapper { Mock Get-ProfileCachePath -Verifiable { '.\MockPath'} Mock RetryGetContent { $global:testProfileMap | ConvertFrom-Json } Context "Profile Maps are available from cache" { $ProfileMapHash = New-Object -TypeName PSObject $ProfileMapHash | Add-Member NoteProperty 'Name' -Value 'ProfileMap.json' Mock Get-ChildItem -Verifiable { @($ProfileMapHash, 'MockHash.json')} Mock Get-ProfilesInstalled -Verifiable { @{'Profile1'= @{'Module1'= '1.0'}}} $expectedResult = @{"Module21.0"=@('Profile1'); "Module11.0"=@('Profile1')} It "Should return Modules & Profiles Installed" { (Get-AllProfilesInstalled) -like $expectedResult | Should Be $true Assert-MockCalled RetryGetContent -Exactly 2 Assert-MockCalled Get-ProfilesInstalled -exactly 2 Assert-VerifiableMocks } } Context "Profiles are not installed" { $ProfileMapHash = New-Object -TypeName PSObject $ProfileMapHash | Add-Member NoteProperty 'Name' -Value 'ProfileMap.json' Mock Get-ChildItem -Verifiable { @($ProfileMapHash, 'MockHash.json')} Mock Get-ProfilesInstalled -Verifiable {} It "Should return empty" { $AllProfilesInstalled = @() $result = (Get-AllProfilesInstalled) $result.Count | Should Be 0 Assert-MockCalled RetryGetContent -Exactly 2 Assert-MockCalled Get-ProfilesInstalled -exactly 2 Assert-VerifiableMocks } } Context "Cache is empty" { Mock Get-ChildItem {} Mock Get-ProfilesInstalled {} It "Should return empty" { $result = (Get-AllProfilesInstalled) $result.Count | Should Be 0 Assert-MockCalled RetryGetContent -Exactly 0 Assert-MockCalled Get-ProfilesInstalled -exactly 0 Assert-VerifiableMocks } } } } Describe "Update-ProfileHelper" { InModuleScope AzureRM.Bootstrapper { Mock Get-ProfileCachePath -Verifiable { '.\MockPath'} $profilemapFileInfo = New-Object -TypeName psobject $profilemapFileInfo | Add-Member NoteProperty 'Name' -Value 'ProfileMap.json' Mock Get-ChildItem -Verifiable { @($profilemapFileInfo, 'MockETag.json')} -ParameterFilter { $Path -eq '.\MockPath'} Mock RetryGetContent -Verifiable { $global:testProfileMap } -ParameterFilter { $FilePath -eq "C:\mock\MockETag.json"} $script:LatestProfileMapPath = New-Object -TypeName PSObject $script:LatestProfileMapPath | Add-Member NoteProperty -Name "FullName" -Value "C:\mock\MockETag.json" Mock Get-AllProfilesInstalled -Verifiable {} Mock Remove-PreviousVersion -Verifiable {} Mock Remove-ProfileMapFile {} Context "Previous Profile versions are available and they are installed" { $PreviousMap = "{`"Profile1`": { `"Module1`": [`"0.1`"], `"Module2`": [`"0.1`"] }, `"Profile2`": { `"Module1`": [`"2.0`", `"1.0`"], `"Module2`": [`"2.0`"] }}" Mock RetryGetContent -Verifiable { $PreviousMap } $Script:mockCalled = 0 $mockTestPath = { $Script:mockCalled++ if ($Script:mockCalled -eq 1) { return @{'Profile1'= @{'Module1'= '1.0'}} } else { return @{'Profile2' = @{ 'Module2' = '0.1'}} } } Mock -CommandName Get-ProfilesInstalled -MockWith $mockTestPath It "Should remove previous profile map" { Update-ProfileHelper -profile 'Profile1' Assert-MockCalled Remove-ProfileMapFile -Exactly 1 Assert-VerifiableMocks } It "Invoke with -Module param: Should remove previous profile map" { Update-ProfileHelper -profile 'Profile1' -Module 'Module1' -RemovePreviousVersions Assert-MockCalled Remove-ProfileMapFile -Exactly 1 Assert-VerifiableMocks } } Context "Previous profile versions are available but they are not installed" { $PreviousMap = "{`"Profile1`": { `"Module1`": [`"0.1`"], `"Module2`": [`"0.1`"] }, `"Profile2`": { `"Module1`": [`"2.0`", `"1.0`"], `"Module2`": [`"2.0`"] }}" Mock RetryGetContent -Verifiable { $PreviousMap } $Script:mockCalled = 0 $mockTestPath = { $Script:mockCalled++ if ($Script:mockCalled -eq 1) { return @{'Profile1'= @{'Module1'= '1.0'}} } else { return @{} } } Mock -CommandName Get-ProfilesInstalled -MockWith $mockTestPath It "Should remove the previous profile map" { Update-ProfileHelper -profile 'Profile1' Assert-MockCalled Remove-ProfileMapFile -Times 1 Assert-VerifiableMocks } } Context "Previous profile versions are same as latest profile versions" { $PreviousMap = "{`"Profile1`": { `"Module1`": [`"0.1`"], `"Module2`": [`"0.1`"] }, `"Profile2`": { `"Module1`": [`"2.0`", `"1.0`"], `"Module2`": [`"2.0`"] }}" Mock RetryGetContent -Verifiable { $PreviousMap } Mock Get-ProfilesInstalled -Verifiable {@{'Profile1'= @{'Module1'= '1.0'}}} It "Should remove the previous profile map" { Update-ProfileHelper -profile 'Profile1' Assert-MockCalled Remove-ProfileMapFile -Times 1 Assert-VerifiableMocks } } Context "Previous profile versions are installed - and part of other profiles" { $PreviousMap = "{`"Profile1`": { `"Module1`": [`"0.1`"], `"Module2`": [`"0.1`"] }, `"Profile2`": { `"Module1`": [`"2.0`", `"1.0`"], `"Module2`": [`"2.0`"] }}" Mock RetryGetContent -Verifiable { $PreviousMap } $Script:mockCalled = 0 $mockTestPath = { $Script:mockCalled++ if ($Script:mockCalled -eq 1) { return @{'Profile2'= @{'Module1'= '1.0'}} } else { return @{'Profile2' = @{ 'Module2' = '0.1'}} } } Mock -CommandName Get-ProfilesInstalled -MockWith $mockTestPath It "Should not remove previous map" { Update-ProfileHelper -profile 'Profile1' Assert-MockCalled Remove-ProfileMapFile -Times 0 Assert-VerifiableMocks } } } } Describe "Find-PotentialConflict" { InModuleScope AzureRM.Bootstrapper { Context "Modules are installed in other scope" { $script:IsAdmin = $true $moduleobj = New-Object -TypeName PSObject $moduleobj | Add-Member NoteProperty -Name "Path" -Value $Env:HOMEPATH Mock Get-Module -Verifiable { $moduleobj} It "Should return false, because force is present" { (Find-PotentialConflict -Module 'Module1' -Force) | Should Be $false } } Context "Modules are not installed in other scope" { $script:IsAdmin = $false $moduleobj = New-Object -TypeName PSObject $moduleobj | Add-Member NoteProperty -Name "Path" -Value $Env:HOMEPATH Mock Get-Module -Verifiable { $moduleobj} It "Should return false, no conflict" { (Find-PotentialConflict -Module 'Module1') | Should Be $false } } } } Describe "Add-ScopeParam" { InModuleScope AzureRM.Bootstrapper { $params = New-Object -Type System.Management.Automation.RuntimeDefinedParameterDictionary It "Should return Scope parameter object" { (Add-ScopeParam $params) $params.ContainsKey("Scope") | Should Be $true } } } Describe "Add-ProfileParam" { InModuleScope AzureRM.Bootstrapper { $params = New-Object -Type System.Management.Automation.RuntimeDefinedParameterDictionary Mock Get-AzProfile -Verifiable { ($global:testProfileMap | ConvertFrom-Json) } It "Should return Profile parameter object" { (Add-ProfileParam $params) $params.ContainsKey("Profile") | Should Be $true Assert-VerifiableMocks } } } Describe "Add-ForceParam" { InModuleScope AzureRM.Bootstrapper { $params = New-Object -Type System.Management.Automation.RuntimeDefinedParameterDictionary It "Should return Force parameter object" { Add-ForceParam $params $params.ContainsKey("Force") | Should Be $true } } } Describe "Add-RemoveParam" { InModuleScope AzureRM.Bootstrapper { $params = New-Object -Type System.Management.Automation.RuntimeDefinedParameterDictionary It "Should return RemovePreviousVersions parameter object" { (Add-RemoveParam $params) $params.ContainsKey("RemovePreviousVersions") | Should Be $true } } } Describe "Add-SwitchParam" { InModuleScope AzureRM.Bootstrapper { $params = New-Object -Type System.Management.Automation.RuntimeDefinedParameterDictionary It "Should return Switch parameter object" { Add-SwitchParam $params "TestParam" $params.ContainsKey("TestParam") | Should Be $true } } } Describe "Add-ModuleParam" { InModuleScope AzureRM.Bootstrapper { $params = New-Object -Type System.Management.Automation.RuntimeDefinedParameterDictionary Mock Get-AzProfile -Verifiable { ($global:testProfileMap | ConvertFrom-Json) } It "Should return Module parameter object" { (Add-ModuleParam $params) $params.ContainsKey("Module") | Should Be $true Assert-VerifiableMocks } } } Describe "Get-AzureRmModule" { InModuleScope AzureRM.Bootstrapper { Mock Get-AzProfile -Verifiable { ($global:testProfileMap | ConvertFrom-Json) } Context "Module is installed" { Mock Get-Module -Verifiable { @( [PSCustomObject] @{ Name='Module1'; Version='1.0'; RepositorySourceLocation='foo\bar' }, [PSCustomObject] @{ Name='Module1'; Version='2.0'}) } It "Should return installed version" { Get-AzureRmModule -Profile 'Profile1' -Module 'Module1' | Should Be "1.0" Assert-VerifiableMocks } } Context "Module is not installed" { Mock Get-Module -Verifiable {} It "Should return null" { Get-AzureRmModule -Profile 'Profile1' -Module 'Module1' | Should be $null Assert-VerifiableMocks } } Context "Module not in the list" { Mock Get-Module -Verifiable { @( [PSCustomObject] @{ Name='Module1'; Version='1.0'; RepositorySourceLocation='foo\bar' }, [PSCustomObject] @{ Name='Module1'; Version='2.0'}) } It "Should return null" { Get-AzureRmModule -Profile 'Profile2' -Module 'Module2' | Should be $null Assert-VerifiableMocks } } Context "Invoke with invalid parameters" { It "Should throw" { { Get-AzureRmModule -Profile 'XYZ' -Module 'ABC' } | Should Throw } } Context "Invoke with null parameters" { It "Should throw" { { Get-AzureRmModule -Profile $null -Module $null } | Should Throw } } } } Describe "Get-AzureRmProfile" { InModuleScope AzureRM.Bootstrapper { Mock Get-AzProfile -Verifiable { ($global:testProfileMap | ConvertFrom-Json) } Context "With ListAvailable Switch" { It "Should return available profiles" { $Result = (Get-AzureRmProfile -ListAvailable) $Result.Contains("Profile: Profile1") | Should Be $true $Result.Contains("Profile: Profile2") | Should Be $true Assert-VerifiableMocks } } Context "With ListAvailable and update Switches" { It "Should return available profiles" { $Result = (Get-AzureRmProfile -ListAvailable -Update) $Result.Contains("Profile: Profile1") | Should Be $true $Result.Contains("Profile: Profile2") | Should Be $true Assert-VerifiableMocks } } Context "Without ListAvailable Switch" { $IncompleteProfiles = @('Profile2') Mock Get-ProfilesInstalled -Verifiable -ParameterFilter {[REF]$IncompleteProfiles} { @{'Profile1'= @{'Module1' = @('1.0') ;'Module2'= @('1.0')}} } It "Returns installed Profile" { $Result = (Get-AzureRmProfile) $result[0] | Should be "Profile : Profile1" Assert-VerifiableMocks } } Context "No profiles installed" { Mock Get-ProfilesInstalled -Verifiable {} It "Returns null" { (Get-AzureRmProfile) | Should Be $null Assert-VerifiableMocks } } } } Describe "Use-AzureRmProfile" { InModuleScope AzureRM.Bootstrapper { $RollupModule = 'Module1' Mock Get-AzProfile -Verifiable { ($global:testProfileMap | ConvertFrom-Json) } Mock Install-Module { "Installing module..."} Mock Import-Module -Verifiable { "Importing Module..."} Mock Find-PotentialConflict {} Context "Modules not installed" { Mock Get-AzureRmModule -Verifiable {} -ParameterFilter {$Profile -eq "Profile1" -and $Module -eq "Module1"} It "Should install modules" { $Result = (Use-AzureRmProfile -Profile 'Profile1' -Force) $Result.Length | Should Be 3 # Includes "Loading module" $Result[1] | Should Be "Installing module..." $Result[2] | Should Be "Importing Module..." Assert-VerifiableMocks } It "Invoke with Module param: Should install modules" { $Result = (Use-AzureRmProfile -Profile 'Profile1' -Module 'Module1' -Force) $Result.Length | Should Be 3 $Result[1] | Should Be "Installing module..." $Result[2] | Should Be "Importing Module..." Assert-VerifiableMocks } } Context "Modules are installed" { $RollupModule = "None" Mock Get-AzureRmModule -Verifiable { "1.0" } -ParameterFilter {$Profile -eq "Profile1" -and $Module -eq "Module1"} Mock Get-AzureRmModule -Verifiable { "1.0" } -ParameterFilter {$Profile -eq "Profile1" -and $Module -eq "Module2"} Mock Import-Module { "Module1 1.0 Imported"} -ParameterFilter { $Name -eq "Module1" -and $RequiredVersion -eq "1.0"} Mock Import-Module { "Module2 1.0 Imported"} -ParameterFilter { $Name -eq "Module2" -and $RequiredVersion -eq "1.0"} It "Should skip installing modules, imports the right version module" { $Result = (Use-AzureRmProfile -Profile 'Profile1' -Force) $Result.length | Should Be 3 $Result[1] | Should Be "Module1 1.0 Imported" Assert-MockCalled Install-Module -Exactly 0 Assert-MockCalled Import-Module -Exactly 2 Assert-VerifiableMocks } It "Invoke with Module param: Should skip installing modules, imports the right version module" { $Result = (Use-AzureRmProfile -Profile 'Profile1' -Module 'Module1', 'Module2' -Force) $Result.length | Should Be 3 $Result[1] | Should Be "Module1 1.0 Imported" Assert-MockCalled Install-Module -Exactly 0 Assert-VerifiableMocks } } Context "Invoke with invalid profile" { It "Should throw" { { Use-AzureRmProfile -Profile 'WrongProfileName'} | Should Throw } } Context "Invoke with $null profile" { It "Should throw" { { Use-AzureRmProfile -Profile $null} | Should Throw } } Context "Invoke with Scope as CurrentUser" { Mock Get-AzureRmModule -Verifiable {} -ParameterFilter {$Profile -eq "Profile1" -and $Module -eq "Module1"} Mock Install-Module -Verifiable {} -ParameterFilter { $Scope -eq "CurrentUser"} It "Should invoke Install-ModuleHelper with scope currentuser" { (Use-AzureRmProfile -Profile 'Profile1' -Force -scope CurrentUser) Assert-VerifiableMocks } } Context "Invoke with Scope as AllUsers" { Mock Get-AzureRmModule -Verifiable {} -ParameterFilter {$Profile -eq "Profile1" -and $Module -eq "Module1"} Mock Install-Module -Verifiable {} -ParameterFilter { $Scope -eq "AllUsers"} It "Should invoke Install-ModuleHelper with scope AllUsers" { (Use-AzureRmProfile -Profile 'Profile1' -Force -scope AllUsers) Assert-VerifiableMocks } } Context "Invoke with invalide module name" { It "Should throw" { { Use-AzureRmProfile -Profile 'Profile1' -Module 'MockModule'} | Should Throw } } Context "Potential Conflict found" { Mock Find-PotentialConflict -Verifiable { $true } It "Should skip installing module" { $Result = (Use-AzureRmProfile -Profile 'Profile1' -Force) $Result.Contains("Installing module...") | Should Be $false Assert-VerifiableMocks } } Context "Other versions of the same module found imported" { Mock Get-AzureRmModule -Verifiable { "1.0" } Mock Find-PotentialConflict -Verifiable { $false } $VersionObj = New-Object -TypeName System.Version -ArgumentList "2.0" $moduleObj = New-Object -TypeName PSObject $moduleObj | Add-Member NoteProperty Version($VersionObj) Mock Get-Module -Verifiable { $moduleObj } It "Should skip importing module" { $result = Use-AzureRmProfile -Profile 'Profile1' -ErrorVariable useError -ErrorAction SilentlyContinue $useError.exception.message.contains("A different version of module") | Should Be $true } } } } Describe "Install-AzureRmProfile" { InModuleScope AzureRM.Bootstrapper { Mock Get-AzProfile -Verifiable { ($global:testProfileMap | ConvertFrom-Json) } Mock Get-AzureRmModule -Verifiable {} -ParameterFilter { $Profile -eq 'Profile1' -and $Module -eq 'Module1'} Mock Get-AzureRmModule -Verifiable { "1.0"} -ParameterFilter { $Profile -eq 'Profile1' -and $Module -eq 'Module2'} Mock Find-PotentialConflict -Verifiable { $false } Context "Invoke with valid profile name" { Mock Install-Module -Verifiable { "Installing module Module1... Version 1.0"} It "Should install Module1" { (Install-AzureRmProfile -Profile 'Profile1') | Should be "Installing module Module1... Version 1.0" Assert-VerifiableMocks } } Context "Invoke with invalid profile name" { It "Should throw" { { Install-AzureRmProfile -Profile 'WrongProfileName'} | Should Throw } } Context "Invoke with null profile name" { It "Should throw" { { Install-AzureRmProfile -Profile $null } | Should Throw } } Context "Invoke with Scope as CurrentUser" { Mock Get-AzureRmModule -Verifiable {} -ParameterFilter {$Profile -eq "Profile1" -and $Module -eq "Module1"} Mock Install-Module -Verifiable {} -ParameterFilter { $Scope -eq "CurrentUser"} It "Should invoke Install-ModuleHelper with scope currentuser" { (Install-AzureRmProfile -Profile 'Profile1' -scope CurrentUser) Assert-VerifiableMocks } } Context "Invoke with Scope as AllUsers" { Mock Get-AzureRmModule -Verifiable {} -ParameterFilter {$Profile -eq "Profile1" -and $Module -eq "Module1"} Mock Install-Module -Verifiable {} -ParameterFilter { $Scope -eq "AllUsers"} It "Should invoke Install-ModuleHelper with scope AllUsers" { (Install-AzureRmProfile -Profile 'Profile1' -scope AllUsers) Assert-VerifiableMocks } } } } Describe "Uninstall-AzureRmProfile" { InModuleScope AzureRM.Bootstrapper { Mock Get-AzProfile -Verifiable { ($global:testProfileMap | ConvertFrom-Json) } Mock Uninstall-ProfileHelper -Verifiable {} Context "Valid profile name" { It "Should invoke Uninstall-ProfileHelper" { Uninstall-AzureRmProfile -Profile 'Profile1' -Force Assert-VerifiableMocks } } Context "Invoke with invalid profile name" { It "Should throw" { { Uninstall-AzureRmProfile -Profile 'WrongProfileName' } | Should Throw } } Context "Invoke with null profile name" { It "Should throw" { { Uninstall-AzureRmProfile -Profile $null } | Should Throw } } } } Describe "Update-AzureRmProfile" { InModuleScope AzureRM.Bootstrapper { # Arrange Mock Get-AzProfile -Verifiable { ($global:testProfileMap | ConvertFrom-Json) } Mock Get-AzProfile -Verifiable -ParameterFilter { $Update.IsPresent } { ($global:testProfileMap | ConvertFrom-Json) } Context "Proper profile with '-RemovePreviousVersions' and '-Force' params" { Mock Use-AzureRmProfile -Verifiable {} -ParameterFilter { ($Force.IsPresent)} Mock Update-ProfileHelper -Verifiable {} It "Imports profile modules and invokes Update-ProfileHelper" { Update-AzureRmProfile -Profile 'Profile2' -RemovePreviousVersions -Force Assert-VerifiableMocks } It "Invoke with Module param: Imports profile modules and invokes Update-ProfileHelper" { Update-AzureRmProfile -Profile 'Profile2' -module 'Module1' -RemovePreviousVersions -Force Assert-VerifiableMocks } } Context "Invoke with invalid profile name" { It "Should throw" { { Update-AzureRmProfile -Profile 'WrongProfileName'} | Should Throw } } Context "Invoke with null profile name" { It "Should throw" { { Update-AzureRmProfile -Profile $null } | Should Throw } } Context "Invoke with Scope as CurrentUser" { Mock Use-AzureRmProfile -Verifiable {} -ParameterFilter { ($Force.IsPresent) -and {$Scope -like 'CurrentUser'}} Mock Update-ProfileHelper -Verifiable {} It "Should invoke Use-AzureRmProfile with scope currentuser" { (Update-AzureRmProfile -Profile 'Profile1' -scope CurrentUser -Force -r) Assert-VerifiableMocks } } Context "Invoke with Scope as AllUsers" { Mock Use-AzureRmProfile -Verifiable {} -ParameterFilter { ($Force.IsPresent) -and {$Scope -like 'CurrentUser'}} Mock Update-ProfileHelper -Verifiable {} It "Should invoke Use-AzureRmProfile with scope AllUsers" { (Update-AzureRmProfile -Profile 'Profile1' -scope AllUsers -Force -r) Assert-VerifiableMocks } } Context "Invoke with invalid module name" { It "Should throw" { { Update-AzureRmProfile -Profile 'Profile1' -module 'MockModule' } | Should Throw } } # Cleanup if (Test-Path '.\MockPath') { Remove-Item -Path '.\MockPath' -Force -Recurse } } } # Cleanup: Reset $script:LatestProfileMapPath #$script:LatestProfileMapPath = Get-LatestProfileMapPath
PowerShellCorpus/PowerShellGallery/AzureRM.BootStrapper/0.1.0/Run-ScenarioTests.ps1
Run-ScenarioTests.ps1
#Requires -Modules AzureRM.Bootstrapper, Pester $defaults = [System.IO.Path]::GetDirectoryName($PSCommandPath) Set-Location $defaults . .\AzureRM.Bootstrapper.ScenarioTests.ps1
PowerShellCorpus/PowerShellGallery/AzureRM.BootStrapper/0.1.0/AzureRM.Bootstrapper.ScenarioTests.ps1
AzureRM.Bootstrapper.ScenarioTests.ps1
Import-Module -Name AzureRM.Bootstrapper $RollupModule = 'AzureRM' InModuleScope AzureRM.Bootstrapper { $ProfileMap = (Get-AzProfile) $ProfileCachePath = Get-ProfileCachePath # Helper function to uninstall all profiles function Remove-InstalledProfile { $installedProfiles = Get-ProfilesInstalled -ProfileMap $ProfileMap if ($installedProfiles.Keys -ne $null) { foreach ($profile in $installedProfiles.Keys) { Write-Host "Removing profile $profile" Uninstall-AzureRmProfile -Profile $profile -Force -ErrorAction SilentlyContinue } $profiles = (Get-ProfilesInstalled -ProfileMap $ProfileMap) if ($profiles.Count -ne 0) { Throw "Uninstallation was not successful: Profile(s) $(@($profiles.Keys) -join ',') were not uninstalled correctly." } } } Describe "A machine with no profile installed can install profile" { # Using Install-AzureRmProfile Context "New Profile Install - Latest" { # Arrange # Uninstall previously installed profiles Remove-InstalledProfile # Launch the test in a new powershell session # Create a new PS session $session = New-PSSession # Act # Install latest version Invoke-Command -Session $session -ScriptBlock { Install-AzureRmProfile -Profile 'Latest' -Force } # Assert It "Should return Latest Profile" { $result = Invoke-Command -Session $session -ScriptBlock { Get-AzureRmProfile } $result[0].Contains('Latest') | Should Be $true } # Clean up Remove-PSSession -Session $session } # Using Use-AzureRmProfile Context "New Profile Install - 2016-04-consistent" { # Arrange # Uninstall previously installed profiles Remove-InstalledProfile # Create a new PS session $session = New-PSSession # Act # Install profile '2016-04-consistent' Invoke-Command -Session $session -ScriptBlock { Use-AzureRmProfile -Profile '2016-04-consistent' -Force } # Assert It "Should return 2016-04-consistent" { $result = Invoke-Command -Session $session -ScriptBlock { Get-AzureRmProfile } $result[0].Contains('2016-04-consistent') | Should Be $true } # Clean up Remove-PSSession -Session $session } } Describe "Add: A Machine with a Profile installed can install latest profile" { InModuleScope AzureRM.Bootstrapper { Context "Profile 2016-04-consistent already installed" { # Arrange # Create a new PS session $session = New-PSSession # Ensure 2016-09-consistent is installed $profilesInstalled = Invoke-Command -Session $session -ScriptBlock { Get-AzureRmProfile } $profilesInstalled[0].Contains('2016-04-consistent') | Should Be $true # Act # Install profile 'Latest' Invoke-Command -Session $session -ScriptBlock { Use-AzureRmProfile -Profile 'Latest' -Force } $result = Invoke-Command -Session $session -ScriptBlock { Get-AzureRmProfile } # Assert It "Should return 2016-09-consistent & Latest" { ($result -like "*latest*") -ne $null | Should Be $true ($result -like "*2016-04-consistent*") -ne $null | Should Be $true } # Clean up Remove-PSSession -Session $session } } } Describe "Attempting to use already installed profile will import the modules to the current session" { InModuleScope AzureRM.Bootstrapper { Context "Profile Latest is installed" { # Should import Latest profile to current session # Arrange # Create a new PS session $session = New-PSSession # Ensure profile Latest is installed $profilesInstalled = Invoke-Command -Session $session -ScriptBlock { Get-AzureRmProfile } ($profilesInstalled -like "*latest*") -ne $null | Should Be $true # Act Invoke-Command -Session $session -ScriptBlock { Use-AzureRmProfile -Profile 'Latest' -Force } # Get the version of the Latest profile $ProfileMap = Get-AzProfile $latestVersion = $ProfileMap.'Latest'.$RollupModule # Assert It "Should return AzureRm module Latest version" { # Get-module script block $getModule = { Param($RollupModule) Get-Module -Name $RollupModule } $modules = Invoke-Command -Session $session -ScriptBlock $getModule -ArgumentList $RollupModule $modules.Name | Should Be $RollupModule $modules.version | Should Be $latestVersion } # Cleanup Invoke-Command -Session $session -ScriptBlock { Uninstall-AzureRmProfile -Profile 'Latest' -Force -ea SilentlyContinue } Remove-PSSession -Session $session } } } Describe "User can update their machine to a latest profile" { InModuleScope AzureRM.Bootstrapper { # Using Use-AzureRmProfile Context "Profile 2016-09-consistent is installed: Use-AzureRmProfile" { # Should refresh profile map from Azure end point and update modules. # Arrange # Create a new PS session $session = New-PSSession # Check if '2016-04-consistent' is installed $profilesInstalled = Invoke-Command -Session $session -ScriptBlock { Get-AzureRmProfile } ($profilesInstalled -like "*2016-04-consistent*") -ne $null | Should Be $true # Remove latest profile map from cache for testing if it updates from online. $latestMap = Get-LatestProfileMapPath if (($latestMap -ne $null) -and (Test-Path $latestMap.FullName)) { Remove-Item -Path $latestMap.FullName -Force } # Act Invoke-Command -Session $session -ScriptBlock { Get-AzureRmProfile -Update } Invoke-Command -Session $session -ScriptBlock { Use-AzureRmProfile -Profile 'Latest' -Force } # Assert It "Should return 2016-04-consistent & Latest" { $result = Invoke-Command -Session $session -ScriptBlock { Get-AzureRmProfile } ($result -like "*latest*") -ne $null | Should Be $true ($result -like "*2016-04-consistent*") -ne $null | Should Be $true } It "Latest version of modules are imported" { # Get the version of the Latest profile $ProfileMap = Get-AzProfile $latestVersion = $ProfileMap.'Latest'.$RollupModule # Get-module script block $getModule = { Param($RollupModule) Get-Module -Name $RollupModule } $modules = Invoke-Command -Session $session -ScriptBlock $getModule -ArgumentList $RollupModule # Are latest modules imported? $modules.Name | Should Be $RollupModule $modules.version | Should Be $latestVersion } It "Last Write Time should be less than 5 minutes" { # Get LastWriteTime for ProfileMap $lastWriteTime = (Get-Item -Path (Get-LatestProfileMapPath).FullName).LastWriteTime (((Get-Date) - $lastWriteTime).TotalMinutes -lt 5) | Should Be $true } # Cleanup Remove-PSSession -Session $session } # Using Update-AzureRmProfile; Previous Versions do not exist Context "Profile 2016-04-consistent is installed: Update-AzureRmProfile" { # Arrange # Remove existing profiles Remove-InstalledProfile # Create a new PS session $session = New-PSSession # Install profile 2016-04-consistent Install-AzureRmProfile -Profile '2016-04-consistent' -Force # Ensure profile 2016-04-consistent is installed $profilesInstalled = Invoke-Command -Session $session -ScriptBlock { Get-AzureRmProfile } ($profilesInstalled -like "*2016-04-consistent*") -ne $null | Should Be $true # Act # Update to profile 'Latest' Invoke-Command -Session $session -ScriptBlock { Update-AzureRmProfile -Profile 'Latest' -Force -RemovePreviousVersions } # Assert # Returns 2016-04-consistent & Latest It "Should Return 2016-04-consistent & Latest" { $result = Invoke-Command -Session $session -ScriptBlock { Get-AzureRmProfile } ($result -like "*latest*") -ne $null | Should Be $true ($result -like "*2016-04-consistent*") -ne $null | Should Be $true } It "Latest version of modules are imported" { # Get the version of the Latest profile $ProfileMap = Get-AzProfile $latestVersion = $ProfileMap.'Latest'.$RollupModule # Get-module script block $getModule = { Param($RollupModule) Get-Module -Name $RollupModule } $modules = Invoke-Command -Session $session -ScriptBlock $getModule -ArgumentList $RollupModule # Are latest modules imported? $modules.Name | Should Be $RollupModule $modules.version | Should Be $latestVersion } Remove-PSSession -Session $session } # Using Update-AzureRmProfile; Previous Versions exist Context "Profile 2016-04-consistent is installed: Update-AzureRmProfile with PreviousVerisons" { # Arrange # Remove existing profiles Remove-InstalledProfile # Create a new PS session $session = New-PSSession # Install profile 2016-04-consistent Install-AzureRmProfile -Profile '2016-04-consistent' -Force # Ensure profile 2016-04-consistent is installed $profilesInstalled = Invoke-Command -Session $session -ScriptBlock { Get-AzureRmProfile } ($profilesInstalled -like "*2016-04-consistent*") -ne $null | Should Be $true # Remove latest profile map from cache for testing if it updates from online. $latestMap = Get-LatestProfileMapPath if (($latestMap -ne $null) -and (Test-Path $latestMap.FullName)) { Remove-Item -Path $latestMap.FullName -Force } # Add a version of old profilemap with older versions of 'latest' profile to cache $testProfileMap = "{`"Latest`": { `"AzureRM`": [`"3.3.0`"], `"Azure.Storage`": [`"2.4.0`"] }}" $testProfileMap | Out-File -FilePath "$ProfileCachePath\TestMap.json" -Force # Install the modules from that profilemap $testProfileMap = ($testProfileMap | ConvertFrom-Json) foreach ($Module in ($testProfileMap.'Latest' | Get-Member -MemberType NoteProperty).Name) { $oldVersion = $testProfileMap.'Latest'.$Module Install-Module $Module -RequiredVersion $oldVersion[0] -ErrorAction Stop -AllowClobber } # Act # Invoke Update-AzureRmProfile 'latest' with -RemovePreviousVersions Invoke-Command -Session $session -ScriptBlock { Get-AzureRmProfile -update } Invoke-Command -Session $session -ScriptBlock { Update-AzureRmProfile -Profile 'Latest' -Force -RemovePreviousVersions } # Assert # Check if new versions of 'latest' are installed $latestVersion = $ProfileMap.'Latest'.$RollupModule It "Should return latest module versions" { # Get-module script block $getModule = { Param($RollupModule) Get-AzureRmModule -Profile 'Latest' -Module $RollupModule } $version = Invoke-Command -Session $session -ScriptBlock $getModule -ArgumentList $RollupModule $version | Should Be $latestVersion } # Check if old versions of 'latest' are uninstalled It "Should return null for old versions" { # Get-module script block $getModule = { Param($RollupModule) Get-Module -Name $RollupModule -ListAvailable } $modules = Invoke-Command -Session $session -ScriptBlock $getModule -ArgumentList $RollupModule foreach ($module in $modules) { $module.Version -eq $oldVersion | Should Be $false } } # Check if the old profilemap was removed It "Should return false for old profile map in cache" { (Test-Path "$ProfileCachePath\TestMap.json") | Should Be $false } } } } Describe "User can uninstall a profile" { InModuleScope AzureRM.Bootstrapper { Context "Latest profile is installed" { # Should uninstall latest profile # Arrange # Create a new PS session $session = New-PSSession # Check if 'Latest' is installed $profilesInstalled = Invoke-Command -Session $session -ScriptBlock { Get-AzureRmProfile } ($profilesInstalled -like "*latest*") -ne $null | Should Be $true # Get the version of the Latest profile $ProfileMap = Get-AzProfile $latestVersion = $ProfileMap.'Latest'.$RollupModule # Act Invoke-Command -Session $session -ScriptBlock { Uninstall-AzureRmProfile -Profile 'Latest' -Force } # Assert It "Profile Latest is uninstalled" { $result = Invoke-Command -Session $session -ScriptBlock { Get-AzureRmProfile } if($result -ne $null) { $result.Contains('Latest') | Should Be $false } else { $true } } It "Available Modules should not contain uninstalled modules" { $getModule = { Param($RollupModule) Get-Module -Name $RollupModule -ListAvailable } $results = Invoke-Command -Session $session -ScriptBlock $getModule -ArgumentList $RollupModule # Result won't be null because profile 2016-04-consistent is installed. foreach ($result in $results) { $result.Version -eq $latestVersion | Should Be $false } } # Cleanup Remove-PSSession -Session $session } } } Describe "Install Two named profiles and selecting each" { InModuleScope AzureRM.Bootstrapper { # Get the version of the respective profile $ProfileMap = Get-AzProfile $Version1 = $ProfileMap.'Latest'.$RollupModule $Version2 = $ProfileMap.'2016-04-consistent'.$RollupModule Context "Install Two Profiles" { # Arrange # Remove all profiles Remove-InstalledProfile # Create a new PS session $session = New-PSSession # Act # Install Profile: 2016-08 Invoke-Command -Session $session -ScriptBlock { Install-AzureRmProfile -Profile 'Latest' -Force } # Install Profile: 2016-04 Invoke-Command -Session $session -ScriptBlock { Install-AzureRmProfile -Profile '2016-04-consistent' -Force } # Assert It "Should return Profiles Latest & 2016-04-consistent" { $profilesInstalled = Invoke-Command -Session $session -ScriptBlock { Get-AzureRmProfile } ($profilesInstalled -like "*2016-04-consistent*") -ne $null | Should Be $true ($profilesInstalled -like "*latest*") -ne $null | Should Be $true } # Clean up Remove-PSSession -Session $session } Context "Select diff profiles" { # Arrange # Create two new PS sessions $session1 = New-PSSession $session2 = New-PSSession # Act # Use-AzureRmProfile will import the respective versions of modules in the session Invoke-Command -Session $session1 -ScriptBlock { Use-AzureRmProfile -Profile 'Latest' -Force } Invoke-Command -Session $session2 -ScriptBlock { Use-AzureRmProfile -Profile '2016-04-consistent' -Force } $getModule = { Param($RollupModule) Get-Module -Name $RollupModule } $result = Invoke-Command -Session $session1 -ScriptBlock { Get-AzureRmProfile } $module1 = Invoke-Command -Session $session1 -ScriptBlock $getModule -ArgumentList $RollupModule $module2 = Invoke-Command -Session $session2 -ScriptBlock $getModule -ArgumentList $RollupModule # Assert It "Should return Latest & 2016-04-consistent" { ($result -like "*latest*") -ne $null | Should Be $true ($result -like "*2016-04-consistent*") -ne $null | Should Be $true } It "Respective versions of modules are imported" { # Are respective modules imported? $module1.Name | Should Be $RollupModule $module1.version | Should Be $Version1 $module2.Name | Should Be $RollupModule $module2.version | Should Be $Version2 } # "Uninstall All Profiles" Remove-InstalledProfile It "Should return null" { Get-AzureRmProfile | Should Be $null } It "Modules should return null" { $getModuleList = { Param($RollupModule) Get-Module -ListAvailable -Name $RollupModule } $result1 = Invoke-Command -Session $session1 -ScriptBlock $getModuleList -ArgumentList $RollupModule foreach ($result in $result1) { $result.Version -eq $Version1 | Should Be $false } $result2 = Invoke-Command -Session $session2 -ScriptBlock $getModuleList -ArgumentList $RollupModule foreach ($result in $result2) { $result.Version -eq $Version2 | Should Be $false } } # Cleanup Remove-PSSession -Session $session1 Remove-PSSession -Session $session2 } } } Describe "Invalid Cases" { Context "Install wrong profile name" { # Install profile 'abcTest' It "Throws Invalid argument error" { { Install-AzureRmProfile -Profile 'abcTest' } | Should Throw } } Context "Install null profile name" { # Install profile 'null' It "Throws Invalid argument error" { { Install-AzureRmProfile -Profile $null } | Should Throw } } Context "Install already installed profile" { # Arrange # Create a new PS session $session = New-PSSession # Ensure profile 2016-09 is installed Install-AzureRmProfile -Profile '2016-04-consistent' -Force $installedProfile = Invoke-Command -Session $session -ScriptBlock { Get-AzureRmProfile } ($installedProfile -like "*2016-04-consistent*") -ne $null | Should Be $true # Act # Install profile '2016-04-consistent' $result = Invoke-Command -Session $session -ScriptBlock { Install-AzureRmProfile -Profile '2016-04-consistent' -Force } # Get modules imported into the session $getModuleList = { Param($RollupModule) Get-Module -Name $RollupModule } $modules = Invoke-Command -Session $session -ScriptBlock $getModuleList -ArgumentList $RollupModule It "Doesn't install/import the profile" { $result | Should Be $null $modules | Should Be $null } # Cleanup Remove-PSSession -Session $session } Context "Uninstall not installed profile" { # Arrange # Create a new PS session $session = New-PSSession # Ensure profile latest is not installed $installedProfile = Invoke-Command -Session $session -ScriptBlock { Get-AzureRmProfile } ($installedProfile -like "*latest*") | Should Be $null # Act # Uninstall profile 'latest' $result = Invoke-Command -Session $session -ScriptBlock { Uninstall-AzureRmProfile -Profile 'latest' -Force} It "Doesn't uninstall/throw" { $result | Should Be $null } # Cleanup Remove-PSSession -Session $session } Context "Use-AzureRmProfile with wrong profile name" { # Install profile 'abcTest' It "Throws Invalid argument error" { { Use-AzureRmProfile -Profile 'abcTest' } | Should Throw } } } Describe "Failure Recovery: Attempt to install profile recovers from error" { InModuleScope AzureRM.Bootstrapper { Context "Azure ProfileMap endpoint threw exception" { # Arrange # Mock Get-ProfileMap returns error Mock Get-AzureProfileMap -Verifiable { throw [System.Net.WebException] } # Mock Install-Modules returns error Mock Install-Module -Verifiable { throw } Mock Get-AzureRmModule -Verifiable {} # Act & Assert It "Should not download/install the latest profile" { { Get-AzureRmProfile -Update } | Should Throw { Install-AzureRmProfile -Profile 'Latest' -Force } | Should Throw } It "Last Write time should not be less than 3 mins" { # Get LastWriteTime for ProfileMap $lastWriteTime = (Get-Item -Path (Get-LatestProfileMapPath).FullName).LastWriteTime (((Get-Date) - $lastWriteTime).TotalMinutes -gt 3) | Should Be $true Assert-VerifiableMocks } } Context "Retry install after ProfileMap update" { # Arrange # Create a new PS session $session = New-PSSession # Remove ProfileMap.json to test if it is updated from online Remove-Item -Path (Get-LatestProfileMapPath).FullName -Force # Act # Update ProfileMap Invoke-Command -Session $session -ScriptBlock { Get-AzureRmProfile -Update } # Install profile 'Latest' Invoke-Command -Session $session -ScriptBlock { Use-AzureRmProfile -Profile 'Latest' -Force } # Assert It "Installs & Imports Latest profile to the session" { $getModuleList = { Param($RollupModule) Get-Module -Name $RollupModule } $modules = Invoke-Command -Session $session -ScriptBlock $getModuleList -ArgumentList $RollupModule # Get the version of the Latest profile $ProfileMap = Get-AzProfile $latestVersion = $ProfileMap.'Latest'.$RollupModule # Are latest modules imported? $modules.Name | Should Be $RollupModule $modules.version | Should Be $latestVersion } It "Last Write time should be less than 5 mins" { # Get LastWriteTime for ProfileMap $lastWriteTime = (Get-Item -Path (Get-LatestProfileMapPath).FullName).LastWriteTime (((Get-Date) - $lastWriteTime).TotalMinutes -lt 5) | Should Be $true } # Cleanup Remove-PSSession -Session $session } } } Describe "Install profiles using Scope" { InModuleScope AzureRM.Bootstrapper { Context "Using Install-AzureRmProfile: Scope 'CurrentUser'" { # Arrange # Create a new PS session $session = New-PSSession # Remove installed profiles Remove-InstalledProfile # Act # Install profile Latest scope as current user Invoke-Command -Session $session -ScriptBlock { Install-AzureRmProfile -Profile 'Latest' -scope 'CurrentUser' -Force } # Assert It "Installs & Imports Latest profile to the session" { # Get the version of the Latest profile $ProfileMap = Get-AzProfile $latestVersion = $ProfileMap.'Latest'.$RollupModule $getModuleList = { Param($RollupModule, $latestVersion) Get-Module -Name $RollupModule -ListAvailable | Where-Object {$_.Version -like $latestVersion} } $modules = Invoke-Command -Session $session -ScriptBlock $getModuleList -ArgumentList @($RollupModule, $latestVersion) # Are latest modules imported? $modules.Name | Should Be $RollupModule $modules.version | Should Be $latestVersion } } Context "Using Use-AzureRmProfile: Scope 'AllUsers'" { # Arrange # Create a new PS session $session = New-PSSession # Remove installed profiles Remove-InstalledProfile # Act # Install profile 2016-04-consistent scope as all users Invoke-Command -Session $session -ScriptBlock { Use-AzureRmProfile -Profile '2016-04-consistent' -scope 'AllUsers' -Force } # Assert It "Installs & Imports 2016-04-consistent profile to the session" { $getModuleList = { Param($RollupModule) Get-Module -Name $RollupModule } $modules = Invoke-Command -Session $session -ScriptBlock $getModuleList -ArgumentList $RollupModule # Get the version of the 2016-04-consistent profile $ProfileMap = Get-AzProfile $version = $ProfileMap.'2016-04-consistent'.$RollupModule # Are appropriate modules imported? $modules.Name | Should Be $RollupModule $modules.version | Should Be $version } } Context "Using Update-AzureRmProfile: Scope 'CurrentUser' " { # Arrange # Create a new PS session $session = New-PSSession # Remove installed profiles Remove-InstalledProfile # Act # Install profile 2016-04-consistent scope as current user Invoke-Command -Session $session -ScriptBlock { Update-AzureRmProfile -Profile '2016-04-consistent' -scope 'CurrentUser' -Force -r } # Assert It "Installs & Imports 2016-04-consistent profile to the session" { $getModuleList = { Param($RollupModule) Get-Module -Name $RollupModule } $modules = Invoke-Command -Session $session -ScriptBlock $getModuleList -ArgumentList $RollupModule # Get the version of the 2016-04-consistent profile $ProfileMap = Get-AzProfile $version = $ProfileMap.'2016-04-consistent'.$RollupModule # Are correct modules imported? $modules.Name | Should Be $RollupModule $modules.version | Should Be $version } } } } Describe "Load/Import AzureRmProfile modules" { InModuleScope AzureRM.Bootstrapper { Context "Using Use-AzureRmProfile: Modules are not installed" { # Arrange # Create a new PS session $session = New-PSSession # Remove installed profiles Remove-InstalledProfile # Act # Use module from Latest profile scope as current user Invoke-Command -Session $session -ScriptBlock { Use-AzureRmProfile -Profile '2016-04-consistent' -Module 'AzureRM.Storage' -Force -scope 'CurrentUser'} # Assert $RollupModule = 'AzureRM.Storage' It "Installs & Imports 2016-04-consistent profile's module to the session" { $getModuleList = { Param($RollupModule) Get-Module -Name $RollupModule } $modules = Invoke-Command -Session $session -ScriptBlock $getModuleList -ArgumentList $RollupModule # Get the version of the 2016-04-consistent profile $ProfileMap = Get-AzProfile $version = $ProfileMap.'2016-04-consistent'.$RollupModule # Are 2016-04-consistent modules imported? $modules.Name | Should Be $RollupModule $modules.version | Should Be $version } } Context "Using Update-AzureRmProfile: Previous version of modules are installed" { # Arrange # Create a new PS session $session = New-PSSession # Remove installed profiles Remove-InstalledProfile # Remove latest profile map from cache for testing if it updates from online. $latestMap = Get-LatestProfileMapPath if (($latestMap -ne $null) -and (Test-Path $latestMap.FullName)) { Remove-Item -Path $latestMap.FullName -Force } # Add a version of old profilemap with older versions of 'latest' profile to cache $testProfileMap = "{`"Latest`": {`"Azure.Storage`": [`"2.4.0`"], `"AzureRM.Storage`": [`"2.4.0`"] }}" $testProfileMap | Out-File -FilePath "$ProfileCachePath\TestMap.json" -Force # Install the modules from that profilemap $testProfileMap = ($testProfileMap | ConvertFrom-Json) foreach ($Module in ($testProfileMap.'Latest' | Get-Member -MemberType NoteProperty).Name) { $oldVersion = $testProfileMap.'Latest'.$Module Install-Module $Module -RequiredVersion $oldVersion[0] -ErrorAction Stop -AllowClobber } # Act # Update profile Latest with -RemovePreviousVersions Invoke-Command -Session $session -ScriptBlock { Get-AzureRmProfile -Update } Invoke-Command -Session $session -ScriptBlock { Update-AzureRmProfile -Profile 'Latest' -Module 'AzureRM.Storage', 'Azure.Storage' -Force -r } # Assert It "Installs & Imports latest profile's module ('AzureRM.Storage') to the session" { $getModuleList = { Param($RollupModule) Get-Module -Name $RollupModule } $module1 = Invoke-Command -Session $session -ScriptBlock $getModuleList -ArgumentList 'AzureRM.Storage' # Get the version of the latest profile $ProfileMap = Get-AzProfile $version1 = $ProfileMap.'Latest'.'AzureRM.Storage' # Are latest modules imported? $module1.Name | Should Be 'AzureRM.Storage' $module1.version | Should Be $version1 } It "Installs & Imports latest profile's module ('Azure.Storage') to the session" { $getModuleList = { Param($RollupModule) Get-Module -Name $RollupModule } $module2 = Invoke-Command -Session $session -ScriptBlock $getModuleList -ArgumentList 'Azure.Storage' # Get the version of the latest profile $ProfileMap = Get-AzProfile $version2 = $ProfileMap.'Latest'.'Azure.Storage' # Are latest modules imported? $module2.Name | Should Be 'Azure.Storage' $module2.version | Should Be $version2 } # Check if the old profilemap was removed It "Should return false for old profile map in cache" { (Test-Path "$ProfileCachePath\TestMap.json") | Should Be $false } } } } }
PowerShellCorpus/PowerShellGallery/AzureRM.BootStrapper/0.1.0/Run-UnitTests.ps1
Run-UnitTests.ps1
#Requires -Modules AzureRM.Bootstrapper, Pester $defaults = [System.IO.Path]::GetDirectoryName($PSCommandPath) Set-Location $defaults Invoke-Pester -EnableExit
PowerShellCorpus/PowerShellGallery/Silk/0.2.0/Import-Silk.ps1
Import-Silk.ps1
<# .SYNOPSIS Imports the Silk module. .DESCRIPTION Imports the Silk module. If the Silk module is already loaded, it will remove it and then reloaded. .EXAMPLE Import-Silk.ps1 Imports the Silk module, re-loading it if its already loaded. #> # Copyright 2012 Aaron Jensen # # Licensed under the Apache License, Version 2.0 (the "License"); # you may not use this file except in compliance with the License. # You may obtain a copy of the License at # # http://www.apache.org/licenses/LICENSE-2.0 # # Unless required by applicable law or agreed to in writing, software # distributed under the License is distributed on an "AS IS" BASIS, # WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. # See the License for the specific language governing permissions and # limitations under the License. [CmdletBinding()] param( ) Set-StrictMode -Version Latest $PSScriptRoot = Split-Path -Parent -Path $MyInvocation.MyCommand.Definition if( (Get-Module Silk) ) { Remove-Module Silk -WhatIf:$false } Import-Module (Join-Path $PSScriptRoot Silk.psd1 -Resolve) -ErrorAction Stop
PowerShellCorpus/PowerShellGallery/Silk/0.2.0/Examples/Publish-Module.ps1
Publish-Module.ps1
<# .SYNOPSIS Packages and publishes Silk packages. .DESCRIPTION The `Publish-Silk.ps1` script packages and publishes a version of the Silk module. It uses the version defined in the Silk.psd1 file. Before publishing, it adds the current date to the version in the release notes, updates the module's website, then tags the latest revision with the version number. It then publishes the module to NuGet, Chocolatey, and the PowerShell Gallery. If the version of Silk being published already exists in a location, it is not re-published. If the PowerShellGet module isn't installed, the module is not publishes to the PowerShell Gallery. .EXAMPLE Publish-Silk.ps1 Yup. That's it. #> # Licensed under the Apache License, Version 2.0 (the "License"); # you may not use this file except in compliance with the License. # You may obtain a copy of the License at # # http://www.apache.org/licenses/LICENSE-2.0 # # Unless required by applicable law or agreed to in writing, software # distributed under the License is distributed on an "AS IS" BASIS, # WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. # See the License for the specific language governing permissions and # limitations under the License. [CmdletBinding(SupportsShouldProcess=$true)] param( ) #Requires -Version 4 Set-StrictMode -Version Latest & (Join-Path -Path $PSScriptRoot -ChildPath 'Silk\Import-Silk.ps1' -Resolve) $silkRoot = Join-Path -Path $PSScriptRoot -ChildPath 'Output\Silk' $releaseNotesPath = Join-Path -Path $silkRoot -ChildPath 'RELEASE_NOTES.md' -Resolve $manifestPath = Join-Path -Path $silkRoot -ChildPath 'Silk.psd1' $manifest = Test-ModuleManifest -Path $manifestPath if( -not $manifest ) { return } $nupkgPath = Join-Path -Path $PSScriptRoot ` -ChildPath ('Output\nuget.org\Silk.PowerShell.{0}.nupkg' -f $manifest.Version) Publish-NuGetPackage -NupkgPath $nupkgPath $nupkgPath = Join-Path -Path $PSScriptRoot ` -ChildPath ('Output\chocolatey.org\Silk.{0}.nupkg' -f $manifest.Version) Publish-ChocolateyPackage -NupkgPath $nupkgPath $tags = @( 'powershell', 'module', 'help', 'tools' ) Publish-PowerShellGalleryModule -ManifestPath $manifestPath ` -ModulePath $silkRoot ` -ReleaseNotesPath $releaseNotesPath ` -LicenseUri 'http://www.apache.org/licenses/LICENSE-2.0' ` -ProjectUri 'http://get-silk.org' ` -Tags $tags
PowerShellCorpus/PowerShellGallery/Silk/0.2.0/Examples/Invoke-Build.ps1
Invoke-Build.ps1
<# .SYNOPSIS Sets the version number for the LibGit2 module. #> # Licensed under the Apache License, Version 2.0 (the "License"); # you may not use this file except in compliance with the License. # You may obtain a copy of the License at # # http://www.apache.org/licenses/LICENSE-2.0 # # Unless required by applicable law or agreed to in writing, software # distributed under the License is distributed on an "AS IS" BASIS, # WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. # See the License for the specific language governing permissions and # limitations under the License. [CmdletBinding()] param( [Version] # The version to build. If not supplied, build the version as currently defined. $Version, [Switch] # Build and create packages that will be published. $ForRelease ) #Requires -Version 4 Set-StrictMode -Version Latest $ErrorActionPreference = 'Stop' & (Join-Path -Path $PSScriptRoot -ChildPath 'Silk\Import-Silk.ps1' -Resolve) $manifestPath = Join-Path -Path $PSScriptRoot -ChildPath 'Silk\Silk.psd1' $manifest = Test-ModuleManifest -Path $manifestPath if( -not $manifest ) { return } $nuspecPath = Join-Path -Path $PSScriptRoot -ChildPath 'Silk.nuspec' -Resolve $releaseNotesPath = Join-Path -Path $PSScriptRoot -ChildPath 'RELEASE_NOTES.md' -Resolve # If you need to compile an assembly or other code, add SolutionPath and AssemblyInfoPath parameters, e.g. # -SolutionPath (Join-Path -Path $PSScriptRoot -ChildPath 'Source\Silk.sln' -Resolve) ` # -AssemblyInfoPath (Join-Path -Path $PSScriptRoot -ChildPath 'Source\Silk\Properties\AssemblyInfo.cs' -Resolve) Set-ModuleVersion -ManifestPath $manifestPath ` -Version $Version ` -ReleaseNotesPath $releaseNotesPath ` -NuspecPath $nuspecPath Import-Module -Name (Join-Path -Path $PSScriptRoot -ChildPath 'Tools\Pester' -Resolve) $result = Invoke-Pester -Script (Join-Path -Path $PSScriptRoot -ChildPath 'Tests') -PassThru if( $result.FailedCount ) { exit } if( -not $ForRelease ) { return } $valid = Assert-ModuleVersion -ManifestPath $manifestPath -ReleaseNotesPath $releaseNotesPath -NuspecPath $nuspecPath -ExcludeAssembly 'LibGit2Sharp.dll' if( -not $valid ) { Write-Error -Message ('Silk isn''t at the right version. Please use the -Version parameter to set the version.') return } Set-ReleaseNotesReleaseDate -ManifestPath $manifestPath -ReleaseNotesPath $releaseNotesPath $tags = @( 'powershell', 'module', 'help', 'tools' ) Set-ModuleManifestMetadata -ManifestPath $manifestPath -Tag $tags -ReleaseNotesPath $releaseNotesPath $outputDirectory = Join-Path -Path $PSScriptRoot -ChildPath 'Output' if( (Test-Path -Path $outputDirectory -PathType Container) ) { Get-ChildItem -Path $outputDirectory | Remove-Item -Recurse } else { New-Item -Path $outputDirectory -ItemType 'directory' } Set-ModuleNuspec -ManifestPath $manifestPath ` -NuspecPath $nuspecPath ` -ReleaseNotesPath $releaseNotesPath ` -Tags $tags ` -PackageID 'Silk.PowerShell' ` -PackageTitle 'Silk.PowerShell' New-NuGetPackage -OutputDirectory (Join-Path -Path $outputDirectory -ChildPath 'nuget.org') ` -ManifestPath $manifestPath ` -NuspecPath $nuspecPath ` -NuspecBasePath $PSScriptRoot ` -PackageName 'Silk.PowerShell' Set-ModuleNuspec -ManifestPath $manifestPath ` -NuspecPath $nuspecPath ` -ReleaseNotesPath $releaseNotesPath ` -Tags $tags ` -PackageID 'Silk' ` -PackageTitle 'Silk' New-ChocolateyPackage -OutputDirectory (Join-Path -Path $outputDirectory -ChildPath 'chocolatey.org') ` -ManifestPath $manifestPath ` -NuspecPath $nuspecPath $source = Join-Path -Path $PSScriptRoot -ChildPath 'Silk' $destination = Join-Path -Path $outputDirectory -ChildPath 'Silk' robocopy.exe $source $destination /MIR /NJH /NJS /NP /NDL /XD /XF '*.pdb' $examplesDir = Join-Path -Path $destination -ChildPath 'Examples' New-Item -Path $examplesDir -ItemType 'Directory' Get-ChildItem -Path (Join-Path -Path $PSScriptRoot -ChildPath 'build.ps1') | Copy-Item -Destination (Join-Path -Path $examplesDir -ChildPath 'Invoke-Build.ps1') Get-ChildItem -Path (Join-Path -Path $PSScriptRoot -ChildPath 'New-Website.ps1') | Copy-Item -Destination $examplesDir Get-ChildItem -Path (Join-Path -Path $PSScriptRoot -ChildPath 'Publish-Silk.ps1') | Copy-Item -Destination (Join-Path -Path $examplesDir -ChildPath 'Publish-Module.ps1') Get-ChildItem -Path 'RELEASE_NOTES.md','LICENSE','NOTICE' | Copy-Item -Destination $destination
PowerShellCorpus/PowerShellGallery/Silk/0.2.0/Examples/New-Website.ps1
New-Website.ps1
<# .SYNOPSIS Creates the get-libgit2.org website. .DESCRIPTION The `New-Website.ps1` script generates the get-libgit2.org website. It uses the Silk module for Markdown to HTML conversion. #> # Licensed under the Apache License, Version 2.0 (the "License"); # you may not use this file except in compliance with the License. # You may obtain a copy of the License at # # http://www.apache.org/licenses/LICENSE-2.0 # # Unless required by applicable law or agreed to in writing, software # distributed under the License is distributed on an "AS IS" BASIS, # WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. # See the License for the specific language governing permissions and # limitations under the License. [CmdletBinding()] param( ) #Requires -Version 4 Set-StrictMode -Version 'Latest' function Out-HtmlPage { param( [Parameter(Mandatory=$true,ValueFromPipeline=$true,ValueFromPipelineByPropertyName=$true)] [Alias('Html')] # The contents of the page. $Content, [Parameter(Mandatory=$true)] # The title of the page. $Title, [Parameter(Mandatory=$true)] # The path under the web root of the page. $VirtualPath ) begin { Set-StrictMode -Version 'Latest' } process { $webRoot = Join-Path -Path $PSScriptRoot -ChildPath 'get-silk.org' $path = Join-Path -Path $webRoot -ChildPath $VirtualPath $templateArgs = @( $Title, $Content, (Get-Date).Year ) @' <!DOCTYPE HTML PUBLIC "-//W3C//DTD HTML 4.01 Transitional//EN" "http://www.w3.org/TR/html4/loose.dtd"> <html> <head> <title>{0}</title> <link href="silk.css" type="text/css" rel="stylesheet" /> <link href="styles.css" type="text/css" rel="stylesheet" /> </head> <body> <ul id="SiteNav"> <li><a href="index.html">Get-Silk</a></li> <li><a href="documentation.html">-Documentation</a></li> <li><a href="releasenotes.html">-ReleaseNotes</a></li> <li><a href="http://pshdo.com">-Blog</a></li> <li><a href="http://github.com/pshdo/Silk">-Project</a></li> </ul> {1} <div class="Footer"> Copyright {2} <a href="http://pshdo.com">Aaron Jensen</a>. </div> </body> </html> '@ -f $templateArgs | Set-Content -Path $path } end { } } $silkRoot = Join-Path -Path $PSScriptRoot -ChildPath '.\Silk' -Resolve if( (Get-Module -Name 'Blade') ) { Remove-Module 'Blade' } $headingMap = @{ } & (Join-Path -Path $silkRoot -ChildPath 'Import-Silk.ps1' -Resolve) try { Convert-ModuleHelpToHtml -ModuleName 'Silk' -HeadingMap $headingMap -Script 'Import-Silk.ps1' | ForEach-Object { Out-HtmlPage -Title ('PowerShell - {0} - Silk' -f $_.Name) -VirtualPath ('{0}.html' -f $_.Name) -Content $_.Html } } finally { } $tagsPath = Join-Path -Path $PSScriptRoot -ChildPath 'tags.json' New-ModuleHelpIndex -TagsJsonPath $tagsPath -ModuleName 'Silk' -Script 'Import-Silk.ps1' | Out-HtmlPage -Title 'PowerShell - Silk Module Documentation' -VirtualPath '/documentation.html' $moduleTitle = 'Silk: PowerShell module for PowerShell module authors and projects' Get-Item -Path (Join-Path -Path $PSScriptRoot -ChildPath 'Silk\en-US\about_Silk.help.txt') | Convert-AboutTopicToHtml -ModuleName 'Silk' -Script 'Import-Silk.ps1' | ForEach-Object { $_ -replace '<h1>about_Silk</h1>','<h1>Silk</h1>' } | Out-HtmlPage -Title $moduleTitle -VirtualPath '/index.html' $releaseNotesPath = Join-Path -Path $PSScriptRoot -ChildPath 'RELEASE_NOTES.md' Get-Content -Path $releaseNotesPath -Raw | Edit-HelpText -ModuleName 'Silk' | Convert-MarkdownToHtml | Out-HtmlPage -Title ('Release Notes - {0}' -f $moduleTitle) -VirtualPath '/releasenotes.html' $silkCssPath = Join-Path -Path $silkRoot -ChildPath 'Resources\silk.css' -Resolve $webroot = Join-Path -Path $PSScriptRoot -ChildPath 'get-silk.org' Copy-Item -Path $silkCssPath -Destination $webroot -Verbose
PowerShellCorpus/PowerShellGallery/Silk/0.2.0/Functions/Set-ModuleNuspec.ps1
Set-ModuleNuspec.ps1
function Set-ModuleNuspec { param( [Parameter(Mandatory=$true)] [string] # Path to the module's manifest. $ManifestPath, [Parameter(Mandatory=$true)] [string] # Path to the module's Nuspec file. $NuspecPath, [Parameter(Mandatory=$true)] [string] # Path to the releaes notes file. $ReleaseNotesPath, [string] # The ID of the package. If not provided, the existing ID in the .nuspec file is left in place. $PackageID, [string] # The title of the package. If not provided, the existing title in the .nuspec file is left in place. $PackageTitle, [string[]] # Tags to add to the manifest. Tags are space-delimited, so tags shouldn't have spaces. $Tags ) Set-StrictMode -Version 'Latest' $NuspecPath = Resolve-Path -Path $NuspecPath if( -not $NuspecPath ) { return } $nuspec = [xml](Get-Content -Path $NuspecPath -Raw) if( -not $nuspec ) { return } $manifest = Test-ModuleManifest -Path $ManifestPath if( -not $manifest ) { return } $releaseNotes = Get-ModuleReleaseNotes -ManifestPath $ManifestPath -ReleaseNotesPath $ReleaseNotesPath if( -not $releaseNotes ) { return } $nuspecMetadata = $nuspec.package.metadata if( $PackageID ) { $nuspecMetadata.id = $PackageID } if( $PackageTitle ) { $nuspecMetadata.title = $PackageTitle } $nuspecMetadata.description = $manifest.Description $nuspecMetadata.version = $manifest.Version.ToString() $nuspecMetadata.copyright = $manifest.Copyright $nuspecMetadata.releaseNotes = $releaseNotes if( $Tags ) { $nuspecMetadata.tags = $Tags -join ' ' } $nuspec.Save( $NuspecPath ) }
PowerShellCorpus/PowerShellGallery/Silk/0.2.0/Functions/Set-ModuleVersion.ps1
Set-ModuleVersion.ps1
function Set-ModuleVersion { <# .SYNOPSIS Updates a module's version. #> [CmdletBinding()] param( [Parameter(Mandatory=$true)] [string] # The path to the module's manifest. $ManifestPath, [string] # The path to the module's manifest. $SolutionPath, [string] # Path to an C# file to update with the assembly version. $AssemblyInfoPath, [string] # Path to a release notes file. $ReleaseNotesPath, [string] # Path to the module's Nuspec file. $NuspecPath, [Version] # The version to build. If not provided, pulled from the module's manifest. $Version, [string] # The pre-release version, e.g. alpha.39, rc.1, etc. $PreReleaseVersion, [string] # Build metadata. $BuildMetadata ) Set-StrictMode -Version 'Latest' if( -not $Version ) { $Version = Test-ModuleManifest -Path $ManifestPath | Select-Object -ExpandProperty 'Version' if( -not $Version ) { return } } if( $Version.Build -lt 0 ) { Write-Error ('Version number must have a build number, i.e. it must have three parts.' -f $Version) return } if( $Version.Revision -ge 0 ) { Write-Error ('Version number must not have a revision number, i.e. it must only have three parts.' -f $Version) return } $manifest = Test-ModuleManifest -Path $ManifestPath if( -not $manifest ) { return } $moduleVersionRegex = 'ModuleVersion\s*=\s*(''|")([^''"])+(''|")' $rawManifest = Get-Content -Raw -Path $manifestPath if( $rawManifest -notmatch ('ModuleVersion\s*=\s*(''|"){0}(''|")' -f [regex]::Escape($version.ToString())) ) { $rawManifest = $rawManifest -replace $moduleVersionRegex,('ModuleVersion = ''{0}''' -f $version) $rawManifest | Set-Content -Path $manifestPath -NoNewline } if( $AssemblyInfoPath ) { $assemblyVersionRegex = 'Assembly(File|Informational)?Version\("[^"]*"\)' $assemblyVersion = Get-Content -Path $AssemblyInfoPath | ForEach-Object { if( $_ -match $assemblyVersionRegex ) { $infoVersion = '' if( $Matches[1] -eq 'Informational' ) { if( $PreReleaseVersion ) { $infoVersion = '-{0}' -f $PreReleaseVersion } if( $BuildMetadata ) { $infoVersion = '{0}+{1}' -f $infoVersion,$BuildMetadata } } return $_ -replace $assemblyVersionRegex,('Assembly$1Version("{0}{1}")' -f $Version,$infoVersion) } elseif( $_ -match 'AssemblyCopyright' ) { return $_ -replace '\("[^"]*"\)',('("{0}")' -f $manifest.Copyright) } $_ } $assemblyVersion | Set-Content -Path $AssemblyInfoPath } if( $ReleaseNotesPath ) { $newVersionHeader = "# {0}" -f $Version $updatedVersion = $false $releaseNotes = Get-Content -Path $releaseNotesPath | ForEach-Object { if( -not $updatedVersion -and $_ -match '^#\s+' ) { $updatedVersion = $true return $newVersionHeader } return $_ } $releaseNotes | Set-Content -Path $releaseNotesPath } if( $SolutionPath ) { $msbuildRoot = Get-ItemProperty -Path HKLM:\SOFTWARE\Microsoft\MSBuild\ToolsVersions\12.0 -Name 'MSBuildToolsPath' | Select-Object -ExpandProperty 'MSBuildToolsPath' $msbuildExe = Join-Path -Path $msbuildRoot -ChildPath 'MSBuild.exe' -Resolve if( -not $msbuildExe ) { return } & $msbuildExe /target:"clean;build" $SolutionPath /v:m /nologo } if( $NuspecPath ) { $nuspec = [xml](Get-Content -Raw -Path $nuspecPath) if( $nuspec.package.metadata.version -ne $version.ToString() ) { $nuGetVersion = $version -replace '-([A-Z0-9]+)[^A-Z0-9]*(\d+)$','-$1$2' $nuspec.package.metadata.version = $nugetVersion $nuspec.Save( $nuspecPath ) } } }
PowerShellCorpus/PowerShellGallery/Silk/0.2.0/Functions/Get-TypeDocumentationLink.ps1
Get-TypeDocumentationLink.ps1
function Get-TypeDocumentationLink { param( [Parameter(Mandatory=$true)] [string] # The name of the command where the type was found. $CommandName, [Parameter(Mandatory=$true)] [string] # The name of the type whose documentation link to return. $TypeName ) Set-StrictMode -Version 'Latest' $displayName = $TypeName if( $TypeName.EndsWith('[]') ) { $TypeName = $TypeName -replace '\[\]','' } if( $TypeName -eq 'bool' ) { $TypeName = 'boolean' } $type = $null if( $loadedTypes.ContainsKey( $TypeName ) ) { $type = [Type]$loadedTypes[$TypeName] } else { try { $type = [Type]$TypeName } catch { Write-Warning ("[{0}] Type {1} not found." -f $CommandName,$TypeName) return $displayName } } $typeLink = $TypeName $typeFullName = $type.FullName $msdnUri = 'http://msdn.microsoft.com/en-us/library/{0}.aspx' -f $Type.FullName.ToLower() if( $Type.FullName -notlike 'System.*' ) { $result = $null try { $result = Invoke-WebRequest -Uri $msdnUri -Method Head -ErrorAction Ignore } catch { } if( -not $result ) { return $displayName } } return '<a href="{0}">{1}</a>' -f $msdnUri,$displayName }
PowerShellCorpus/PowerShellGallery/Silk/0.2.0/Functions/Edit-HelpText.ps1
Edit-HelpText.ps1
function Edit-HelpText { <# .SYNOPSIS Converts the command names in a block of text to links. .DESCRIPTION The `Edit-HelpText` function converts all a module's command names or help topic names into Markdown links. The command names or help topic names should be surrounded by backticks, e.g. `Invoke-Function`, `about_Module`. #> [CmdletBinding()] param( [Parameter(Mandatory=$true,VAlueFromPipeline=$true)] # The text to convert. $InputObject, [string] # The name of the module whose command names to convert. $ModuleName ) begin { Set-StrictMode -Version 'Latest' $commands = Invoke-Command -ScriptBlock { Get-Command -Module $ModuleName -CommandType Cmdlet Get-Command -Module $ModuleName -CommandType Function Get-Command -Module $ModuleName -CommandType Filter } $aliases = Get-Command -Module $ModuleName -CommandType Alias | Get-Alias $aboutTopicNames = Get-ChildItem -Path (Get-Module -Name $ModuleName).ModuleBase -Filter 'en-US\about_*' | Select-Object -ExpandProperty 'BaseName' | ForEach-Object { $_ -replace '\.help$','' } } process { $regex = $commands | Select-Object -ExpandProperty 'Name' | ForEach-Object { [regex]::Escape( $_ ) } $regex = $regex -join '|' $regex = '`({0})`' -f $regex $replacement = '[$1]($1.html)' $InputObject | ForEach-Object { $_ -replace $regex,$replacement } | ForEach-Object { $text = $_ foreach( $alias in $aliases ) { $text = $text -replace ('`({0})`' -f $alias.Name),('[$1]({0}.html)' -f $alias.Definition) } foreach( $aboutTopicName in $aboutTopicNames ) { $text = $text -replace ('`({0})`' -f $aboutTopicName),('[{0}]($1.html)' -f ($aboutTopicName -replace '_','\_')) } return $text } } end { } }
PowerShellCorpus/PowerShellGallery/Silk/0.2.0/Functions/Convert-HelpToHtml.ps1
Convert-HelpToHtml.ps1
function Convert-HelpToHtml { <# .SYNOPSIS Converts a command's help topic to HTML. .DESCRIPTION The `Convert-HelpToHtml` function convert's a command's help topic to HTML. This HTML can then be used in a complete HTML page. It will output the following parts of a help topic, in the following order: * Name (in an `h1` element). You can override this name with the `DisplayName` parameter. * Synopsis * Syntax (which you can override with the `Syntax` parameter) * Description * Related Commands (i.e. `.LINK`) * Parameters * Parameters * Input Types (i.e. `.INPUTS`) * Return Types (i.e. `.OUTPUTS`) * Notes * Examples `Convert-HelpToHtml` converts all help text to HTML using [MarkdownSharp](https://code.google.com/p/markdownsharp/), a C# [Markdown](https://daringfireball.net/projects/markdown/) implementation. Markdown "allows you to write using an easy-to-read, easy-to-write plain text format, [that is converted] to structurally valid XHTML (or HTML)". This makes your help web-friendly. If you want to convert an entire module's help to HTML, including any scripts and DSC resources, use the `Convert-ModuleHelpToHtml` function. When converting help for a module, pass the module's name with the `ModuleName` parameter, and any of the module's commands or about topics found enclosed in backticks (Markdown's span of code indicators) will be converted to an anchor element whose `href` attribute is the command's name with a .html extension. For example, this help text: > Silk's `Convert-HelpToHtml` function converts help text written with Markdown into HTML. would get converted to > Silk's <a href="Convert-HelpToHtml.html">Convert-HelpToHtml</a> function converts help text written with Markdown into HTML. `Convert-HelpToHtml` assumes you'll take its output, wrap it in a full HTML page, and save all of these generated pages into the same directory. For example, $html = Convert-HelpToHtml -Name 'Convert-HelpToHtml' -ModuleName 'Silk' @" <!DOCTYPE html> <html> <head> <title>Convert-HelpToHTml</title> <link href="silk.css" type="text/css" rel="stylesheet" /> </head> <body> $html </body> </html> "@ | Set-Content -Path (Join-Path -Path $webRoot -ChildPath 'Convert-HelpToHtml.html') `Convert-HelpToHtml` outputs HTML 5 (or tries to). For the best cross-browser compatability, make sure you define a doctype on each page. This is especially important for Internet Explorer. If you don't use a doctype, IE will display your pages in quirks mode, which won't display things correctly. Silk ships with a default cascading stylesheet (CSS) in the `Resources` directory. Copy this file into your webroot and link to it in each of your pages (via the `link` tag). To customize the appearance of your pages, we recommend you create your own stylesheet and link to it in each of your pages. Make all your style changes in yoru stylesheet. Future versions of Silk will contain fixes/enhancements to the default stylesheet. Using your own will make upgrading easier. .LINK https://daringfireball.net/projects/markdown/ .LINK Convert-ModuleHelpToHtml .EXAMPLE Convert-HelpToHtml -Name 'Get-Module' Demonstrates how to use `Convert-HelpToHtml` to generate help for a command. You can pass multiple command names to the `Name` parameter. .EXAMPLE Get-Command -Module 'Silk' | Convert-HelpToHtml -ModuleName 'Silk' Demonstrates how you can pipe commands to `Convert-HelpToHtml` to generate help for them. .EXAMPLE Convert-HelpToHtml -Name 'Set-TargetResource' -DisplayName 'My_Dsc_Resource' -Syntax (Get-DscResource -Name 'My_Dsc_Resource' -Syntax) Demonstrates how you can document DSC resources. In this case, the resource's `Set-TargetResource` function contains the help to convert. Because the syntax for using a DSC resource is different than a PowerShell function/cmdlet, we pass the resource's syntax with the `Syntax` parameter. #> param( [Parameter(Mandatory=$true,ValueFromPipeline=$true)] [string[]] # The name of the command(s) to document. $Name, [string] # The display name. When supplied, it is used as the command's name instead of `Name`. Useful if the command name being documented is different than its public name, e.g. DSC resources. $DisplayName, [string[]] # The syntax of the command. Useful when showing syntax for DSC resources. # # You can get the syntax for a DSC resource with the `Get-DscResource` cmdlet: # # Get-DscResource -Name 'My_Dsc_Resource' -Syntax $Syntax, [string] # The name of the module whose help is getting converted. Supplying this value will cause any of the module's cmdlets/functions surrounded by backticks (e.g. `Convert-HelpToHtml`) in help text to get replaced with an HTML link to that command's help topic. $ModuleName, [string[]] # The names of any scripts in the module. Supplying these values will cause any script names surround in backticks (e.g. `script.ps1`) in help text to get replaced with an HTML link to that script's help topic. $Script ) begin { Set-StrictMode -Version 'Latest' } process { foreach( $commandName in $Name ) { $html = New-Object 'Text.StringBuilder' $fullCommandName = $commandName if( (Get-Help -Name $commandName | Measure-Object).Count -gt 1 ) { $fullCommandName = '{0}\{1}' -f $ModuleName,$commandName } Write-Verbose -Message $fullCommandName $help = Get-Help -Name $fullCommandName -Full if( -not $DisplayName ) { $DisplayName = $commandName if( [IO.Path]::IsPathRooted($DisplayName) ) { $DisplayName = Split-Path -Leaf -Path $DisplayName } } [void]$html.AppendFormat( '<h1>{0}</h1>{1}', $DisplayName, [Environment]::NewLine ) $synopsis = $help.Synopsis | Convert-MarkdownToHtml if( $synopsis ) { [void]$html.AppendFormat( '<div class="Synopsis">{0}{1}{0}</div>{0}', [Environment]::NewLine, $synopsis ) } if( -not $Syntax ) { $help.Syntax | ForEach-Object { $_.syntaxItem } | Where-Object { [IO.Path]::IsPathRooted($_.name) } | ForEach-Object { $_.Name = Split-Path -Leaf -Path $_.name } $Syntax = $help.Syntax | Out-HtmlString | Format-ForHtml | ForEach-Object { $_ -split "`n" } } if( $Syntax ) { [void]$html.AppendLine( @" <h2>Syntax</h2> <pre class="Syntax"><code>{0}</code></pre> "@ -f ($Syntax -join "</code></pre>$([Environment]::NewLine)<pre class=""Syntax""><code>") ) } $description = $null if( $help | Get-Member -Name 'Description' ) { $description = $help.Description | Out-HtmlString | Convert-MarkdownToHtml } if( $description ) { [void]$html.AppendLine( @" <h2>Description</h2> <div class="Description"> $description </div> "@ ) } [string[]]$relatedCommands = $help | Convert-RelatedLinkToHtml -ModuleName $ModuleName -Script $Script if( $relatedCommands ) { $relatedCommands = $relatedCommands | ForEach-Object { "<li>{0}</li>" -f $_ } [void]$html.AppendLine( @" <h2>Related Commands</h2> <ul class="RelatedCommands"> {0} </ul> "@ -f ($relatedCommands -join ([Environment]::NewLine)) ) } $commonParameterNames = @{ 'Verbose' = $true; 'Debug' = $true; 'WarningAction' = $true; 'WarningVariable' = $true; 'ErrorAction' = $true; 'ErrorVariable' = $true; 'OutVariable' = $true; 'OutBuffer' = $true; 'WhatIf' = $true; 'Confirm' = $true; } $hasCommonParameters = $false $parameters = $help | Select-Object -ExpandProperty 'Parameters' | Where-Object { $_ | Get-Member -Name 'parameter' } | Select-Object -ExpandProperty 'parameter' | Where-Object { $_ } | ForEach-Object { if( $commonParameterNames.ContainsKey( $_.name ) ) { $hasCommonParameters = $true } $defaultValue = '&nbsp;' if( $_ | Get-Member -Name 'DefaultValue' ) { $defaultValue = $_.DefaultValue } $typeLink = Get-TypeDocumentationLink -CommandName $commandName -TypeName $_.type.name $paramDescription = $_ | Where-Object { $_ | Get-Member -name 'Description' } | Select-Object -ExpandProperty 'Description' | Out-HtmlString | Convert-MarkdownToHtml @" <tr valign='top'> <td>{0}</td> <td>{1}</td> <td class="ParamDescription">{2}</td> <td>{3}</td> <td>{4}</td> <td>{5}</td> </tr> "@ -f $_.Name,$typeLink,$paramDescription,$_.Required,$_.PipelineInput,$defaultValue } if( $parameters ) { $commonParameters = '' if( $hasCommonParameters ) { $commonParameters = @" <tr valign="top"> <td><a href="http://technet.microsoft.com/en-us/library/dd315352.aspx">CommonParameters</a></td> <td></td> <td>This cmdlet supports common parameters. For more information type <br> <code>Get-Help about_CommonParameters</code>.</td> <td></td> <td></td> <td></td> </tr> "@ } [void]$html.AppendLine( (@" <h2> Parameters </h2> <table id="Parameters"> <tr> <th>Name</th> <th>Type</th> <th>Description</th> <th>Required?</th> <th>Pipeline Input</th> <th>Default Value</th> </tr> {0} {1} </table> "@ -f ($parameters -join [Environment]::NewLine),$commonParameters)) } $inputTypes = @() if( ($help | Get-Member -Name 'inputTypes') -and ($help.inputTypes | Get-Member 'inputType') ) { $inputTypes = $help.inputTypes.inputType | Where-Object { ($_ | Get-Member -Name 'type') -and $_.type -and $_.type.name -match '^([^\s]+)\s*(.*)?$' } | ForEach-Object { $typeLink = Get-TypeDocumentationLink -CommandName $commandName -TypeName $Matches[1].Trim('.') '{0}. {1}' -f $typeLink,$matches[2] } | Convert-MarkdownToHtml } if( $inputTypes ) { [void]$html.AppendLine( @" <h2>Input Types</h2> <div class="InputTypes"> {0} </div> "@ -f ($inputTypes -join [Environment]::NewLine)) } $returnValues =@() if( ($help | Get-Member -Name 'returnValues') -and ($help.returnValues | Get-Member -Name 'returnValue') ) { $returnValues = $help.returnValues.returnValue | Where-Object { ($_ | Get-Member -Name 'type') -and $_.type -and $_.type.name -match '^([^\s]+)\s*(.*)?$' } | ForEach-Object { $typeLink = Get-TypeDocumentationLink -CommandName $commandName -TypeName $Matches[1].Trim('.') '{0}. {1}' -f $typeLink,$matches[2] } | Convert-MarkdownToHtml } if( $returnValues ) { [void]$html.AppendLine( @" <h2>Return Values</h2> <div class="ReturnValues"> {0} </div> "@ -f ($returnValues -join [Environment]::NewLine)) } $notes = '' if( $help | Get-Member -Name 'AlertSet' ) { $notes = $help.AlertSet | Out-HtmlString | ForEach-Object { $_ -replace "\r?\n ",[Environment]::NewLine } | Convert-MarkdownToHtml } if( $notes ) { [void]$html.AppendLine( @" <h2>Notes</h2> <div class="Notes"> {0} </div> "@ -f $notes) } $examples = @() if( $help | Get-Member -Name 'Examples' ) { $examples = $help.Examples | Where-Object { $_ } | Where-Object { $_ | Get-Member -Name 'example' } | Select-Object -ExpandProperty 'example' | ForEach-Object { $title = $_.title.Trim(('-',' ')) $code = '' if( $_.code ) { $code = $_.code | Out-HtmlString $code = '<pre><code>{0}</code></pre>' -f $code } $remarks = $_.remarks | Out-HtmlString | Convert-MarkdownToHtml @" <h2>{0}</h2> {1} {2} "@ -f $title,$code,($remarks -join [Environment]::NewLine) } } if( $examples ) { [void]$html.AppendLine( ($examples -join ([Environment]::NewLine * 2)) ) } $html.ToString() } } end { } }
PowerShellCorpus/PowerShellGallery/Silk/0.2.0/Functions/New-ChocolateyPackage.ps1
New-ChocolateyPackage.ps1
# Copyright 2012 Aaron Jensen # # Licensed under the Apache License, Version 2.0 (the "License"); # you may not use this file except in compliance with the License. # You may obtain a copy of the License at # # http://www.apache.org/licenses/LICENSE-2.0 # # Unless required by applicable law or agreed to in writing, software # distributed under the License is distributed on an "AS IS" BASIS, # WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. # See the License for the specific language governing permissions and # limitations under the License. function New-ChocolateyPackage { <# .SYNOPSIS Creates a NuGet package. #> [CmdletBinding(SupportsShouldProcess=$true)] param( [Parameter(Mandatory=$true)] [string] # The path to the module manifest of the module you want to publish. $ManifestPath, [Parameter(Mandatory=$true)] [string] # The path to the nuspec file for the NuGet package to publish. $NuspecPath, [Parameter(Mandatory=$true)] [string] # The directory where the .nupkg file should be saved. $OutputDirectory ) Set-StrictMode -Version 'Latest' Use-CallerPreference -Cmdlet $PSCmdlet -Session $ExecutionContext.SessionState if( -not (Get-Command -Name 'choco.exe' -ErrorAction Ignore) ) { Write-Error -Message ('choco.exe not found. Please install Chocoatey from chocolatey.org') return } if( -not (Test-Path -Path $OutputDirectory -PathType Container) ) { New-Item -Path $OutputDirectory -ItemType 'directory' -Force } $manifest = Test-ModuleManifest -Path $ManifestPath if( -not $manifest ) { return } Push-Location -Path $OutputDirectory try { Get-ChildItem -Path '*.nupkg' | Remove-Item $verbosity = '' if( $VerbosePreference -eq 'Continue' ) { $verbosity = '-v' } choco.exe pack $NuspecPath --version=$($manifest.Version) $verbosity if( -not (Test-Path -Path '*.nupkg' -PathType Leaf) ) { Write-Error -Message 'Chocolatey package not created.' } } finally { Pop-Location } }
PowerShellCorpus/PowerShellGallery/Silk/0.2.0/Functions/Split-MarkdownTopic.ps1
Split-MarkdownTopic.ps1
function Split-MarkdownTopic { <# .SYNOPSIS Parses a Markdown-formatted module help topic, e.g. about_Module. .DESCRIPTION A Markdown-formatted help topic should contain four sections, `Topic`, `Short Description`, `Long Description`, and `See Also`. These should all be formatted as level-1 headings. For example: # Topic about_Silk # Short Description Silk is a PowerShell module used to convert another module's help system into an HTML website. # Long Description MOre details here. Yadda, yadda, yadda. # See Also about_Silk_AdditionalTopic #> [CmdletBinding()] param( [Parameter(Mandatory=$true)] # The root where the config file was found. $ConfigFileRoot, [Parameter(Mandatory=$true,ValueFromPipeline=$true)] # An object containing information about the topic to parse. $TopicInfo ) process { Set-StrictMode -Version Latest $path = $TopicInfo.Path if( -not (Test-Path -Path $path -PathType Leaf) ) { Write-Error ('Markdown help topic <{0}> not found.' -f $path) return } $content = New-Object Collections.ArrayList $sectionName = $null $eof = [Guid]::NewGuid().ToString() $topic = New-Object PsObject -Property @{ Name = ''; Synopsis = ''; Description = ''; RelatedLinks = ''; FileName = $TopicInfo.FileName } $lineNum = 0 Invoke-Command { Get-Content -Path $path ; $eof } | ForEach-Object { if( $_ -match '^# (.*)$' -or $_ -eq $eof ) { if( $sectionName -or $_ -eq $eof ) { $topic.$sectionName = $content -join "`n" $topic.$sectionName = $topic.$sectionName.Trim() if( $_ -eq $eof ) { return } $content.Clear() } $sectionName = $matches[1] switch -Regex ($sectionName) { 'Topic|Name' { $sectionName = 'Name' } 'Short Description|Synopsis' { $sectionName = 'Synopsis' } 'Long Description|Description' { $sectionName = 'Description' } 'See Also|(Related )?Links?' { $sectionName = 'RelatedLinks' } default { Write-Error ('{0}: line {1}: Unknown top-level heading <{2}>. Expected <Name>, <Synopsis>, <Description>, or <Link>. <Link> may be used multiple times.' -f $path,$lineNum,$_) } } } else { if( -not $sectionName ) { Write-Error ('{0}: line {1}: Invalid Markdown help topic: the first line must be `# Name`.' -f $path,$lineNum) return } [void] $content.Add( $_ ) } ++$lineNum } if( $TopicInfo | Get-Member Title ) { $topic.Name = $TopicInfo.Title } return $topic } }
PowerShellCorpus/PowerShellGallery/Silk/0.2.0/Functions/Out-HtmlString.ps1
Out-HtmlString.ps1
filter Out-HtmlString { <# .SYNOPSIS Writes a string out to the pipeline, trimming whitespace. #> $_ | Out-String -Width 9999 | ForEach-Object { $_.Trim() } | Where-Object { $_ } }
PowerShellCorpus/PowerShellGallery/Silk/0.2.0/Functions/Get-ModuleVersion.ps1
Get-ModuleVersion.ps1
function Get-ModuleVersion { param( [Parameter(Mandatory=$true)] [string] # The path to the module's manifest. $ManifestPath ) Set-StrictMode -Version 'Latest' }
PowerShellCorpus/PowerShellGallery/Silk/0.2.0/Functions/Use-CallerPreference.ps1
Use-CallerPreference.ps1
# Licensed under the Apache License, Version 2.0 (the "License"); # you may not use this file except in compliance with the License. # You may obtain a copy of the License at # # http://www.apache.org/licenses/LICENSE-2.0 # # Unless required by applicable law or agreed to in writing, software # distributed under the License is distributed on an "AS IS" BASIS, # WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. # See the License for the specific language governing permissions and # limitations under the License. function Use-CallerPreference { <# .SYNOPSIS Sets the PowerShell preference variables in a module's function based on the callers preferences. .DESCRIPTION Script module functions do not automatically inherit their caller's variables, including preferences set by common parameters. This means if you call a script with switches like `-Verbose` or `-WhatIf`, those that parameter don't get passed into any function that belongs to a module. When used in a module function, `Use-CallerPreference` will grab the value of these common parameters used by the function's caller: * ErrorAction * Debug * Confirm * InformationAction * Verbose * WarningAction * WhatIf This function should be used in a module's function to grab the caller's preference variables so the caller doesn't have to explicitly pass common parameters to the module function. This function is adapted from the [`Get-CallerPreference` function written by David Wyatt](https://gallery.technet.microsoft.com/scriptcenter/Inherit-Preference-82343b9d). There is currently a [bug in PowerShell](https://connect.microsoft.com/PowerShell/Feedback/Details/763621) that causes an error when `ErrorAction` is implicitly set to `Ignore`. If you use this function, you'll need to add explicit `-ErrorAction $ErrorActionPreference` to every function/cmdlet call in your function. Please vote up this issue so it can get fixed. .LINK about_Preference_Variables .LINK about_CommonParameters .LINK https://gallery.technet.microsoft.com/scriptcenter/Inherit-Preference-82343b9d .LINK http://powershell.org/wp/2014/01/13/getting-your-script-module-functions-to-inherit-preference-variables-from-the-caller/ .EXAMPLE Use-CallerPreference -Cmdlet $PSCmdlet -SessionState $ExecutionContext.SessionState Demonstrates how to set the caller's common parameter preference variables in a module function. #> [CmdletBinding()] param ( [Parameter(Mandatory = $true)] #[Management.Automation.PSScriptCmdlet] # The module function's `$PSCmdlet` object. Requires the function be decorated with the `[CmdletBinding()]` attribute. $Cmdlet, [Parameter(Mandatory = $true)] [Management.Automation.SessionState] # The module function's `$ExecutionContext.SessionState` object. Requires the function be decorated with the `[CmdletBinding()]` attribute. # # Used to set variables in its callers' scope, even if that caller is in a different script module. $SessionState ) Set-StrictMode -Version 'Latest' # List of preference variables taken from the about_Preference_Variables and their common parameter name (taken from about_CommonParameters). $commonPreferences = @{ 'ErrorActionPreference' = 'ErrorAction'; 'DebugPreference' = 'Debug'; 'ConfirmPreference' = 'Confirm'; 'InformationPreference' = 'InformationAction'; 'VerbosePreference' = 'Verbose'; 'WarningPreference' = 'WarningAction'; 'WhatIfPreference' = 'WhatIf'; } foreach( $prefName in $commonPreferences.Keys ) { $parameterName = $commonPreferences[$prefName] # Don't do anything if the parameter was passed in. if( $Cmdlet.MyInvocation.BoundParameters.ContainsKey($parameterName) ) { continue } $variable = $Cmdlet.SessionState.PSVariable.Get($prefName) # Don't do anything if caller didn't use a common parameter. if( -not $variable ) { continue } if( $SessionState -eq $ExecutionContext.SessionState ) { Set-Variable -Scope 1 -Name $variable.Name -Value $variable.Value -Force -Confirm:$false -WhatIf:$false } else { $SessionState.PSVariable.Set($variable.Name, $variable.Value) } } }
PowerShellCorpus/PowerShellGallery/Silk/0.2.0/Functions/Publish-ChocolateyPackage.ps1
Publish-ChocolateyPackage.ps1
# Copyright 2012 Aaron Jensen # # Licensed under the Apache License, Version 2.0 (the "License"); # you may not use this file except in compliance with the License. # You may obtain a copy of the License at # # http://www.apache.org/licenses/LICENSE-2.0 # # Unless required by applicable law or agreed to in writing, software # distributed under the License is distributed on an "AS IS" BASIS, # WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. # See the License for the specific language governing permissions and # limitations under the License. function Publish-ChocolateyPackage { <# .SYNOPSIS Creates and publishes a NuGet package to nuget.org. #> [CmdletBinding(SupportsShouldProcess=$true)] param( [Parameter(Mandatory=$true)] [string] # The path to the module manifest of the module you want to publish. $NupkgPath, [string] # The API key(s) to use. To supply multiple API keys, use a hashtable where each key is a repository server name and the value is the API key for that repository. For example, # # @{ 'nuget.org' = '395edfa5-652f-4598-868e-c0a73be02c84' } # # If not specified, you'll be prompted for it. $ApiKey ) Set-StrictMode -Version 'Latest' Use-CallerPreference -Cmdlet $PSCmdlet -Session $ExecutionContext.SessionState if( -not (Get-Command -Name 'choco.exe' -ErrorAction Ignore) ) { Write-Error -Message ('Chocolatey is not installed. Go to http://chocolatey.org for installation instructions.') return } if( -not (Test-Path -Path $NupkgPath -PathType Leaf) ) { Write-Error -Message ('Chocolatey package ''{0}'' does not exist.' -f $NupkgPath) return } $nupkgName = [IO.Path]::GetFileNameWithoutExtension($NupkgPath) if( $nupkgName -notmatch '^(.+)\.(\d+\.\d+\.\d)+$' ) { Write-Error -Message ('Chocolatey package ''{0}'' does not have the version to publish in its name.' -f $nupkgName) return } $packageName = $Matches[1] $version = $Matches[2] try { $packageUrl = 'https://chocolatey.org/api/v2/package/{0}/{1}' -f $packageName,$version try { $resp = Invoke-WebRequest -Uri $packageUrl -ErrorAction Ignore $publish = ($resp.StatusCode -ne 200) } catch { $publish = $true } if( -not $publish ) { Write-Warning ('Chocolatey package {0} {1} already published to chocolatey.org.' -f $packageName,$version) return } if( $PSCmdlet.ShouldProcess(('publish package to chocolatey.org'),'','') ) { if( -not $ApiKey ) { $ApiKey = Read-Host -Prompt ('Please enter your chocolatey.org API key') if( -not $ApiKey ) { Write-Error -Message ('The chocolatey.org API key is required. Package not published to chocolatey.org') continue } } $verbosity = '' if( $VerbosePreference -eq 'Continue' ) { $verbosity = '-v' } choco.exe push --source 'https://chocolatey.org' --key $ApiKey $verbosity $nupkgPath $resp = Invoke-WebRequest -Uri $packageUrl $resp | Select-Object -Property 'StatusCode','StatusDescription',@{ Name = 'Uri'; Expression = { $packageUrl }} } } finally { Pop-Location } }
PowerShellCorpus/PowerShellGallery/Silk/0.2.0/Functions/Set-ReleaseNotesReleaseDate.ps1
Set-ReleaseNotesReleaseDate.ps1
function Set-ReleaseNotesReleaseDate { [CmdletBinding()] param( [Parameter(Mandatory=$true)] [string] # The path to the module manifest whose release notes to update. $ManifestPath, [Parameter(Mandatory=$true)] [string] # The path to the release notes file. $ReleaseNotesPath ) Set-StrictMode -Version 'Latest' $manifest = Test-ModuleManifest -Path $ManifestPath if( -not $manifest ) { return } $setHeader = $false $releaseNotes = Get-Content -Path $ReleaseNotesPath | ForEach-Object { if( $_ -match '^# {0}\s*$' -f [regex]::Escape($manifest.Version.ToString()) ) { $setHeader = $true return "# {0} ({1})" -f $manifest.Version,((Get-Date).ToString("d MMMM yyyy")) } return $_ } if( $setHeader ) { $releaseNotes | Set-Content -Path $releaseNotesPath } }
PowerShellCorpus/PowerShellGallery/Silk/0.2.0/Functions/Test-ModuleVersion.ps1
Test-ModuleVersion.ps1
function Assert-ModuleVersion { param( [Parameter(Mandatory=$true)] [string] # The path to the module's manifest. $ManifestPath, [string[]] # Path to any additional assemblies whose versions should get checked. $AssemblyPath, [string] # Path to a release notes file. $ReleaseNotesPath, [string] # The path to the module's nuspec file. $NuspecPath, [string[]] # A list of assembly file names that should be excluded from the version check. Wildcards allowed. Only assembly names are matched $ExcludeAssembly ) Set-StrictMode -Version 'Latest' $errorsAtStart = $Error.Count $manifest = Test-ModuleManifest -Path $ManifestPath if( -not $manifest ) { return } $version = $manifest.Version Write-Verbose -Message ('Checking that {0} module is at version {1}.' -f $manifest.Name,$version) $badAssemblies = Invoke-Command { $manifest.RequiredAssemblies | ForEach-Object { if( -not [IO.Path]::IsPathRooted($_) ) { Join-Path -Path (Split-Path -Parent -Path $manifest.Path) -ChildPath $_ } else { $_ } } if( $AssemblyPath ) { $AssemblyPath } } | Where-Object { foreach( $exclusion in $ExcludeAssembly ) { if( (Split-Path -Leaf -Path $_) -like $exclusion ) { return $false } } return $true } | Get-Item | Where-Object { -not ($_.VersionInfo.FileVersion.ToString().StartsWith($version.ToString())) -or -not ($_.VersionInfo.ProductVersion.ToString().StartsWith($version.ToString())) } | ForEach-Object { ' * {0} (FileVersion: {1}; ProductVersion: {2})' -f $_.Name,$_.VersionInfo.FileVersion,$_.VersionInfo.ProductVersion } if( $badAssemblies ) { Write-Error -Message ('The following assemblies are not at version {0}.{1}{2}' -f $version,([Environment]::NewLine),($badAssemblies -join ([Environment]::NewLine))) } if( $ReleaseNotesPath ) { $foundFirstVersion = $false $releaseNotesVersion = Get-Content -Path $ReleaseNotesPath | ForEach-Object { if( -not $foundFirstVersion -and $_ -match '^#\s+(\d+\.\d+\.\d+)' ) { $foundFirstVersion = $true return [Version]$Matches[1] } } if( -not $releaseNotesVersion ) { Write-Error -Message ('Version {0} not found in release notes ({1}).' -f $version,$ReleaseNotesPath) } } if( $NuspecPath ) { $nuspec = [xml](Get-Content -Raw -Path $NuspecPath) if( $nuspec ) { $nuspecVersion = [Version]($nuspec.package.metadata.version) if( $nuspecVersion ) { if( $version -ne $nuspecVersion ) { Write-Error -Message ('Nuspec file ''{0}'' is at version {1}, but should be at version {2}..' -f $NuspecPath,$nuspecVersion,$version) } } else { Write-Error -Message ('Nuspec file ''{0}'' contains an invalid version.' -f $NuspecPath) } } else { Write-Error -Message ('Nuspec file ''{0}'' does not contain valid XML.' -f $NuspecPath) } } return (($Error.Count - $errorsAtStart) -eq 0) }
PowerShellCorpus/PowerShellGallery/Silk/0.2.0/Functions/Convert-AboutTopicToHtml.ps1
Convert-AboutTopicToHtml.ps1
4 function Convert-AboutTopicToHtml { <# .SYNOPSIS Converts an about topic into HTML. .DESCRIPTION The `Convert-AboutTopicToHtml` converts a PowerShell about topic into HTML. The about topic is expected to be [formatted like PowerShell's internal topics](https://msdn.microsoft.com/en-us/library/Dd878343.aspx): TOPIC about_<subject or module name> SHORT DESCRIPTION A short, one-line description of the topic contents. LONG DESCRIPTION A detailed, full description of the subject or purpose of the module. EXAMPLES Examples of how to use the module or how the subject feature works in practice. KEYWORDS Terms or titles on which you might expect your users to search for the information in this topic. SEE ALSO Text-only references for further reading. Hyperlinks cannot work in the Windows PowerShell console. `Convert-AboutTopicToHtml` does the following: * Removes the `TOPIC` AND `SHORT DESCRIPTION` headers * Wraps the topic name in an <h1> tag * Renames the `LONG DESCRIPTION` heading to '<h2>Description</h2> * Wraps all other headers in <h2> elements. * Converts the bodies of each section to HTML Lines that don't begin with spaces are assumed to be headers. Lines that begin with spaces are assumed to be content written in Markdown. The `SEE ALSO` section is parsed, one line at a time for links, command names, and other help topics, e.g. SEE ALSO https://msdn.microsoft.com/en-us/library/Dd878343.aspx about_Silk Convert-AboutTopicToHtml Would convert into a three item list, the first a link to the web, the second a link to the `about_Silk.html` topic, and the third to the `Convert-AboutTopicToHtml.html` page. #> [CmdletBinding()] param( [Parameter(Mandatory=$true,ValueFromPipeline=$true)] # The name of the help topic, include the `about_` prefix, or a `FileInfo` object representing the help topic, or the help topic as a giant string. $InputObject, [string] # The name of the topic you're converting. Only used if `InputObject` is the text of the about topic. $TopicName, [Parameter(Mandatory=$true)] [string] # The name of the module being documented. $ModuleName, [string] # The heading used for the topic's name. Default is `TOPIC`. $TopicHeading = 'TOPIC', [string] # The heading used for the topic's short description. Default is `SHORT DESCRIPTION`. $ShortDescriptionHeading = 'SHORT DESCRIPTION', [string] # The heading used for the topic's long description. Default is `LONG DESCRIPTION`. $LongDescriptionHeading = 'LONG DESCRIPTION', [string] # The heading used for the topic's `See Also` section. Default is `SEE ALSO`. $SeeAlsoHeading = 'SEE ALSO', [hashtable] # A hashtable of headings to use. They key should be the section name. The value should be the heading name. $HeadingMap = @{}, [string[]] # The names of any scripts in the module. $Script ) begin { Set-StrictMode -Version 'Latest' } process { function Complete-Section { param( [string] $Heading, [Parameter(Mandatory=$true)] [AllowEmptyString()] [string] $Body ) $Body = $Body.Trim() switch( $Heading ) { $TopicHeading { # We just don't want to do any Markdown conversion. } $SeeAlsoHeading { $lines = $Body -split ([Environment]::NewLine) | Convert-RelatedLinkToHtml -ModuleName $ModuleName -Script $Script | ForEach-Object { '<li>{0}</li>' -f $_ } $Body = @' <ul> {0} </ul> '@ -f ($lines -join [Environment]::NewLine) } default { $Body = $Body | Edit-HelpText -ModuleName $ModuleName | Convert-MarkdownToHtml } } $topic | Add-Member -Name $Heading -MemberType NoteProperty -Value $Body } if( $InputObject -is [IO.FileInfo] ) { [string[]]$lines = $InputObject | Get-Content $TopicName = $InputObject.BaseName -replace '\.help$' -f '' } elseif( $InputObject -is [string] -and $InputObject -match '^about_' ) { [string[]]$lines = Get-Help -Name $InputObject if( -not $lines ) { Write-Error ('About topic ''{0}'' not found.' -f $InputObject) return } $TopicName = $InputObject } else { $lines = $InputObject -split ([Environment]::NewLine) } $topic = [pscustomobject]@{ } $currentHeader = $null $currentContent = $null $sectionOrder = New-Object 'Collections.Generic.List[string]' $lastLineIdx = $lines.Count - 1 for( $idx = 0; $idx -lt $lines.Count; ++$idx ) { $line = $lines[$idx] if( -not $line -or $line -match '^\s+' ) { if( $line.StartsWith(' ') ) { $line = $line -replace '^ ','' } elseif( $line.StartsWith(' ') ) { $line = $line -replace '^ ','' } [void]$currentContent.AppendLine( $line ) if( $idx -eq $lastLineIdx ) { Complete-Section -Heading $currentHeader -Body $currentContent.ToString() } continue } else { # Header if( $currentHeader ) { Complete-Section -Heading $currentHeader -Body $currentContent.ToString() } $currentContent = New-Object 'Text.StringBuilder' $currentHeader = [Globalization.CultureInfo]::CurrentCulture.TextInfo.ToTitleCase( $line.ToLowerInvariant() ) $sectionOrder.Add( $currentHeader ) } } if( -not ($topic | Get-Member -Name $TopicHeading) ) { Write-Warning ('Topic ''{0}'' doesn''t have a ''{1}'' heading. Defaulting to {0}. Use the `TopicHeading` parameter to set the topic''s topic heading.' -f $TopicName,$TopicHeading) Complete-Section -Heading 'TOPIC' -Body $TopicName } if( -not ($topic | Get-Member -Name $ShortDescriptionHeading) ) { Write-Warning ('Topic ''{0}'' doesn''t have a ''{1}'' heading. Use the `ShortDescription` parameter to set the topic''s SHORT DESCRIPTION heading.' -f $TopicName,$ShortDescriptionHeading) Complete-Section -Heading 'SHORT DESCRIPTION' -Body '' } if( -not $HeadingMap.ContainsKey($LongDescriptionHeading) ) { $HeadingMap[$LongDescriptionHeading] = 'Description' } $content = New-Object 'Text.StringBuilder' foreach( $section in $sectionOrder ) { if( $section -eq $TopicHeading -or $section -eq $ShortDescriptionHeading ) { continue } $heading = $section if( $HeadingMap.ContainsKey($section) ) { $heading = $HeadingMap[$section] } [void]$content.AppendLine( ('<h2>{0}</h2>' -f $heading) ) [void]$content.AppendLine( $topic.$Section ) } @' <h1>{0}</h1> {1} {2} '@ -f $topic.$TopicHeading,$topic.$ShortDescriptionHeading,$content } end { } }
PowerShellCorpus/PowerShellGallery/Silk/0.2.0/Functions/Format-ForHtml.ps1
Format-ForHtml.ps1
filter Format-ForHtml { <# .SYNOPSIS Encodes text for HTML. #> if( $_ ) { [Web.HttpUtility]::HtmlEncode($_) } }
PowerShellCorpus/PowerShellGallery/Silk/0.2.0/Functions/Get-Function.ps1
Get-Function.ps1
filter Get-Function { <# .SYNOPSIS Gets all of a module's functions. #> param( [Parameter(Mandatory=$true,ValueFromPipeline=$true)] # The file to parse for functions $Path ) Write-Verbose "Loading script '$Path'." $scriptContent = Get-Content "$Path" if( -not $scriptContent ) { return @() } $errors = [Management.Automation.PSParseError[]] @() $tokens = [System.Management.Automation.PsParser]::Tokenize( $scriptContent, [ref] $errors ) if( $errors -ne $null -and $errors.Count -gt 0 ) { Write-Error "Found $($errors.count) error(s) parsing '$Path'." return } Write-Verbose "Found $($tokens.Count) tokens in '$Path'." for( $idx = 0; $idx -lt $tokens.Count; ++$idx ) { $token = $tokens[$idx] if( $token.Type -eq 'Keyword'-and ($token.Content -eq 'Function' -or $token.Content -eq 'Filter') ) { $atFunction = $true } if( $atFunction -and $token.Type -eq 'CommandArgument' -and $token.Content -ne '' ) { Write-Verbose "Found function '$($token.Content).'" $token.Content $atFunction = $false } } }
PowerShellCorpus/PowerShellGallery/Silk/0.2.0/Functions/New-ModuleHelpIndex.ps1
New-ModuleHelpIndex.ps1
function New-ModuleHelpIndex { <# .SYNOPSIS Creates an index page for a module's help. #> [CmdletBinding()] param( [Parameter(Mandatory=$true)] [string] # The name of the module whose index page to create. $ModuleName, [string[]] # The names of any scripts that should be included. $Script, [string] # The path to the tags file. If not provided, no tag tab is generated. $TagsJsonPath ) Set-StrictMode -Version 'Latest' if( $TagsJsonPath ) { $tagsJson = Get-Content -Path $TagsJsonPath | ConvertFrom-Json $tags = @{ } foreach( $item in $tagsJson ) { foreach( $tagName in $item.Tags ) { if( -not $tags.ContainsKey( $tagName ) ) { $tags[$tagName] = New-Object 'Collections.Generic.List[string]' } $tags[$tagName].Add( $item.Name ) } } $tagCloud = $tags.Keys | Sort-Object | ForEach-Object { $commands = $tags[$_] | ForEach-Object { '<li><a href="{0}.html">{0}</a></li>' -f $_ } @' <h3>{0}</h3> <ul> {1} </ul> '@ -f $_,($commands -join ([Environment]::NewLine)) } } else { $tagCloud = '' } $verbs = @{ } $commands = Get-Command -Module $ModuleName -CommandType Cmdlet,Function,Filter foreach( $command in $commands ) { if( -not $verbs.ContainsKey( $command.Verb ) ) { $verbs[$command.Verb] = New-Object 'Collections.Generic.List[string]' } $verbs[$command.Verb].Add( $command.Name ) } $commandList = Invoke-Command { $commands | Select-Object -ExpandProperty 'Name' $moduleBase = Get-Module -Name $ModuleName | Select-Object -ExpandProperty 'ModuleBase' $dscResourceBase = Join-Path -Path $moduleBase -ChildPath 'DscResources' if( (Test-Path -Path $dscResourceBase -PathType Container) ) { Get-ChildItem -Directory -Path $dscResourceBase } } | Sort-Object | ForEach-Object { '<li><a href="{0}.html">{0}</a></li>' -f $_ } $commandList = @' <ul> {0} </ul> '@ -f ($commandList -join ([Environment]::NewLine)) $verbList = $verbs.Keys | Sort-Object | ForEach-Object { $verb = $_ $verbCommands = $verbs[$verb] | ForEach-Object { '<li><a href="{0}.html">{0}</a></li>' -f $_ } @' <h3>{0}</h3> <ul> {1} </ul> '@ -f $verb,($verbCommands -join ([Environment]::NewLine)) } $scriptContent = '' if( $Script ) { $scriptContent = @" <h2>Scripts</h2> <ul> $($Script | ForEach-Object { '<li><a href="{0}.html">{0}</a></li>' -f $_ }) </ul> "@ } $topicList = New-Object 'Collections.Generic.List[string]' $moduleBase = Get-Module -Name $ModuleName | Select-Object -ExpandProperty 'ModuleBase' $aboutTopics = @() if( (Test-Path -Path (Join-Path -Path $moduleBase -ChildPath 'en-US') -PathType Container) ) { $aboutTopics = Get-ChildItem -Path $moduleBase -Filter 'en-US\about_*.help.txt' } foreach( $aboutTopic in $aboutTopics ) { $topicName = $aboutTopic.BaseName -replace '\.help$','' $virtualPath = '{0}.html' -f $topicName $topicList.Add( ('<li><a href="{0}">{1}</a></li>' -f $virtualPath,$topicName) ) } function New-CommandsMenuItem { param( $ID, $Name ) Set-StrictMode -Version 'Latest' if( -not $tagCloud -and $ID -eq 'ByTag' ) { return } $selectedAttr = '' if( ($tagCloud -and $ID -eq 'ByTag') -or ($ID -eq 'ByName' -and -not $tagCloud) ) { $selectedAttr = 'class="selected"' } '<li id="{0}MenuItem" {1}><a href="#{0}">{2}</a></li>' -f $ID,$selectedAttr,$Name } function New-CommandContentDiv { param( $ID, $Line ) Set-StrictMode -Version 'Latest' if( -not $Line ) { return } $styleAttr = 'display:none;' if( ($ID -eq 'Tag' -and $tagCloud) -or ($ID -eq 'Name' -and -not $tagCloud) ) { $styleAttr = '' } @' <div id="By{0}Content" style="{2}"> <a id="By{0}"></a> {1} </div> '@ -f $ID,($Line -join ([Environment]::NewLine)),$styleAttr } @" <script src="https://code.jquery.com/jquery-2.1.4.min.js"></script> <script> jQuery( document ).ready(function() { jQuery("#CommandsMenu > li").click( function() { var selectedLi = jQuery("#CommandsMenu li.selected") selectedLi.removeClass("selected"); var selectedCmdID = selectedLi.attr("id").replace("MenuItem",""); jQuery("#" + selectedCmdID + 'Content').hide(); var li = jQuery(this); li.addClass("selected"); var id = li.attr( 'id' ) id = id.replace('MenuItem',''); jQuery('#' + id + 'Content').show(); return false; }); }); </script> <h2>About Help Topics</h2> <ul> $($topicList.ToArray() -join ([Environment]::NewLine)) </ul> $($scriptContent) <h2>Commands</h1> <ul id="CommandsMenu"> $( New-CommandsMenuItem 'ByTag' 'By Tag' ) $( New-CommandsMenuItem 'ByName' 'By Name' ) $( New-CommandsMenuItem 'ByVerb' 'By Verb' ) </ul> <div id="CommandsContent"> $( New-CommandContentDiv 'Tag' $tagCloud ) $( New-CommandContentDiv 'Name' $commandList ) $( New-CommandContentDiv 'Verb' $verbList ) </div> "@ }
PowerShellCorpus/PowerShellGallery/Silk/0.2.0/Functions/Publish-NuGetPackage.ps1
Publish-NuGetPackage.ps1
# Copyright 2012 Aaron Jensen # # Licensed under the Apache License, Version 2.0 (the "License"); # you may not use this file except in compliance with the License. # You may obtain a copy of the License at # # http://www.apache.org/licenses/LICENSE-2.0 # # Unless required by applicable law or agreed to in writing, software # distributed under the License is distributed on an "AS IS" BASIS, # WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. # See the License for the specific language governing permissions and # limitations under the License. function Publish-NuGetPackage { <# .SYNOPSIS Creates and publishes a NuGet package to nuget.org. #> [CmdletBinding(SupportsShouldProcess=$true)] param( [Parameter(Mandatory=$true)] [string] # The path to the module manifest of the module you want to publish. $NupkgPath, [object] # The API key(s) to use. To supply multiple API keys, use a hashtable where each key is a repository server name and the value is the API key for that repository. For example, # # @{ 'nuget.org' = '395edfa5-652f-4598-868e-c0a73be02c84' } # # If not specified, you'll be prompted for it. $ApiKey ) Set-StrictMode -Version 'Latest' Use-CallerPreference -Cmdlet $PSCmdlet -Session $ExecutionContext.SessionState $nugetPath = Join-Path -Path $PSScriptRoot -ChildPath '..\bin\NuGet.exe' -Resolve if( -not $nugetPath ) { return } if( -not (Test-Path -Path $NupkgPath -PathType Leaf) ) { Write-Error -Message ('NuGet package ''{0}'' does not exist.' -f $NupkgPath) return } $nupkgName = [IO.Path]::GetFileNameWithoutExtension($NupkgPath) if( $nupkgName -notmatch '^(.+)\.(\d+\.\d+\.\d)+$' ) { Write-Error -Message ('NuGet package ''{0}'' does not have the version to publish in its name.' -f $nupkgName) return } $packageName = $Matches[1] $version = $Matches[2] try { $packageUrl = 'https://nuget.org/api/v2/package/{0}/{1}' -f $packageName,$version try { $resp = Invoke-WebRequest -Uri $packageUrl -ErrorAction Ignore $publish = ($resp.StatusCode -ne 200) } catch { $publish = $true } if( -not $publish ) { Write-Warning ('NuGet package {0} {1} already published to nuget.org.' -f $packageName,$version) return } if( $PSCmdlet.ShouldProcess(('publish package to nuget.org'),'','') ) { if( -not $ApiKey ) { $ApiKey = Read-Host -Prompt ('Please enter your nuget.org API key') if( -not $ApiKey ) { Write-Error -Message ('The nuget.org API key is required. Package not published to nuget.org.') continue } } $verbosity = 'normal' if( $VerbosePreference -eq 'Continue' ) { $verbosity = 'detailed' } & $nugetPath push $nupkgPath -ApiKey $ApiKey -Source 'https://nuget.org/api/v2/package' -Verbosity $verbosity $resp = Invoke-WebRequest -Uri $packageUrl $resp | Select-Object -Property 'StatusCode','StatusDescription',@{ Name = 'Uri'; Expression = { $packageUrl }} } } finally { Pop-Location } }
PowerShellCorpus/PowerShellGallery/Silk/0.2.0/Functions/Convert-ModuleHelpToHtml.ps1
Convert-ModuleHelpToHtml.ps1
function Convert-ModuleHelpToHtml { <# .SYNOPSIS Converts a module's help into HTML. .DESCRIPTION The `Convert-ModuleHelpToHtml` function converts a module's help into HTML. It returns an object for each command and about help topic in the module. The object #> [CmdletBinding()] param( [Parameter(Mandatory=$true)] [string] # The name of the module whose help to convert. $ModuleName, [string[]] # Any scripts included in the module whose help should get generated. Scripts are assumed to be in the root of the module. $Script, [hashtable] # A hashtable of headings to use. They key should be the section name. The value should be the heading name. Only used when converting about help topics to HTML. $HeadingMap, [Switch] # Don't generate help for individual commands. $SkipCommandHelp ) Set-StrictMode -Version 'Latest' $commands = Get-Command -Module $ModuleName -CommandType Cmdlet,Function,Filter $moduleBase = Get-Module -Name $ModuleName | Select-Object -ExpandProperty 'ModuleBase' $aboutTopics = @() if( (Test-Path -Path (Join-Path -Path $moduleBase -ChildPath 'en-US') -PathType Container) ) { $aboutTopics = Get-ChildItem -Path $moduleBase -Filter 'en-US\about_*.help.txt' } $dscResources = Join-Path -Path $moduleBase -ChildPath 'DscResources' | Where-Object { Test-Path -Path $_ -PathType Container } | Get-ChildItem -Directory $scripts = @() if( $Script ) { $scripts = $Script | ForEach-Object { Join-Path -Path $moduleBase -ChildPath $_ } | Get-Item } [int]$numCommands = $commands | Measure-Object | Select-Object -ExpandProperty 'Count' [int]$numScripts = $scripts | Measure-Object | Select-Object -ExpandProperty 'Count' [int]$numAboutTopics = $aboutTopics | Measure-Object | Select-Object -ExpandProperty 'Count' [int]$numDscResources = $dscResources | Measure-Object | Select-Object -ExpandProperty 'Count' [int]$numPages = $numAboutTopics + $numDscResources + $numScripts if( -not $SkipCommandHelp ) { $numPages += $numCommands } $activity = 'Generating {0} Module HTML' -f $ModuleName $count = 0 foreach( $command in $commands ) { if( -not $SkipCommandHelp ) { Write-Progress -Activity $activity -PercentComplete ($count++ / $numPages * 100) -CurrentOperation $command.Name -Status 'Commands' $html = Convert-HelpToHtml -Name $command.Name -Script $Script -ModuleName $ModuleName [pscustomobject]@{ Name = $command.Name; Type = 'Command'; Html = $html; } } } foreach( $scriptItem in $scripts ) { Write-Progress -Activity $activity -PercentComplete ($count++ / $numPages * 100) -CurrentOperation $command.Name -Status 'Scripts' $html = Convert-HelpToHtml -Name $scriptItem.FullName -ModuleName $ModuleName -Script $Script [pscustomobject]@{ Name = $scriptItem.Name; Type = 'Script' Html = $html; } } foreach( $aboutTopic in $aboutTopics ) { $topicName = $aboutTopic.BaseName -replace '\.help','' Write-Progress -Activity $activity -PercentComplete ($count++ / $numPages * 100) -CurrentOperation $topicName -Status 'About Topics' $html = $aboutTopic | Convert-AboutTopicToHtml -ModuleName $ModuleName -Script $Script [pscustomobject]@{ Name = $topicName; Type = 'AboutTopic'; Html = $html } } foreach( $dscResource in $dscResources ) { $dscResourceName = $dscResource.BaseName Write-Progress -Activity $activity -PercentComplete ($count++ / $numPages * 100) -CurrentOperation $dscResourceName -Status 'DSC Resources' Import-Module -Name $dscResource.FullName $html = Convert-HelpToHtml -Name 'Set-TargetResource' -DisplayName $dscResourceName -Syntax (Get-DscResource -Name $dscResourceName -Syntax) -ModuleName $ModuleName -Script $Script [pscustomobject]@{ Name = $dscResourceName; Type = 'DscResource'; Html = $html; } } }
PowerShellCorpus/PowerShellGallery/Silk/0.2.0/Functions/Publish-PowerShellGalleryPackage.ps1
Publish-PowerShellGalleryPackage.ps1
#> # Copyright 2012 Aaron Jensen # # Licensed under the Apache License, Version 2.0 (the "License"); # you may not use this file except in compliance with the License. # You may obtain a copy of the License at # # http://www.apache.org/licenses/LICENSE-2.0 # # Unless required by applicable law or agreed to in writing, software # distributed under the License is distributed on an "AS IS" BASIS, # WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. # See the License for the specific language governing permissions and # limitations under the License. function Publish-PowerShellGalleryModule { <# .SYNOPSIS Publishes a module to the PowerShell gallery. .DESCRIPTION The `Publish-PowerShellGalleryModule` functin publishes a module to the PowerShell Gallery. If the given version of the module already exists in the Gallery, a warning is written and no other work is done. If you don't supply a PowerShell Gallery API key via the `ApiKey` parameter, you'll be prompted for it. Returns a `PSGetItemInfo` object if the module gets published (the object returned by the `Find-Module` cmdlet). If the version of the module already exists in the Gallery, you'll get a warning that the module has already been published. This function requires the `PowerShellGet` module. If it isn't available, you'll get an error. .OUTPUTS PSGetItemInfo .EXAMPLE Publish-PowerShellGalleryModule -Name 'Carbon' -Version '2.0.0' -LicenseUri ''http://www.apache.org/licenses/LICENSE-2.0' #> [CmdletBinding(SupportsShouldProcess=$true)] param( [Parameter(Mandatory=$true)] [string] # Path to the module's manifest. $ManifestPath, [Parameter(Mandatory=$true)] [string] # The path to the module. $ModulePath, [Parameter(Mandatory=$true)] [string] # The release notes. $ReleaseNotesPath, [string] # The name of the module being published. Defaults to the name in the module manifest. $Name, [string] # The API key for the PowerShell Gallery. $ApiKey, [Parameter(Mandatory=$true)] [string] # The URL to the module's license. $LicenseUri, [string[]] # Any tags for the module. $Tags, [string] # The URL to the project's home page. $ProjectUri ) Set-StrictMode -Version 'Latest' Use-CallerPreference -Cmdlet $PSCmdlet -Session $ExecutionContext.SessionState $manifest = Test-ModuleManifest -Path $ManifestPath if( -not $manifest ) { return } if( -not $Name ) { $Name = $manifest.Name } if( Get-Module -ListAvailable -Name 'PowerShellGet' ) { if( -not (Find-Module -Name $Name -RequiredVersion $manifest.Version -Repository 'PSGallery' -ErrorAction Ignore) ) { $releaseNotes = Get-ModuleReleaseNotes -ManifestPath $ManifestPath -ReleaseNotesPath $ReleaseNotesPath Write-Verbose -Message ('Publishing to PowerShell Gallery.') if( $PSCmdlet.ShouldProcess('publish module to PowerShell Gallery','','') ) { if( -not $ApiKey ) { $ApiKey = Read-Host -Prompt ('Please enter PowerShell Gallery API key') } Publish-Module -Path $ModulePath ` -Repository 'PSGallery' ` -NuGetApiKey $ApiKey ` -LicenseUri $LicenseUri ` -ReleaseNotes $releaseNotes ` -Tags $Tags ` -ProjectUri $ProjectUri Find-Module -Name $Name -RequiredVersion $manifest.Version -Repository 'PSGallery' } } else { Write-Warning -Message ('{0} {1} already exists in the PowerShell Gallery.' -f $Name,$manifest.Version) } } else { Write-Error -Message ('Unable to publish to PowerShell Gallery: PowerShellGet module not found.') } }
PowerShellCorpus/PowerShellGallery/Silk/0.2.0/Functions/Publish-BitbucketDownload.ps1
Publish-BitbucketDownload.ps1
# Copyright 2012 Aaron Jensen # # Licensed under the Apache License, Version 2.0 (the "License"); # you may not use this file except in compliance with the License. # You may obtain a copy of the License at # # http://www.apache.org/licenses/LICENSE-2.0 # # Unless required by applicable law or agreed to in writing, software # distributed under the License is distributed on an "AS IS" BASIS, # WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. # See the License for the specific language governing permissions and # limitations under the License. function Publish-BitbucketDownload { <# .SYNOPSIS Creates and publishes a ZIP file to Bitbucket so it is available on a project's download page. .DESCRIPTION The `Publish-BitbucketDownload` function creates a ZIP file and publishes it to a repository so it is availabe on a project's download page. If the file already exists on Bitbucket, nothing is uploaded. .LINK https://bitbucket.org/Swyter/bitbucket-curl-upload-to-repo-downloads #> [CmdletBinding()] param( [pscredential] # The Bitbucket credentials to use. $Credential, [Parameter(Mandatory=$true)] [string] # The account of the project you're uploading a file to. $Username, [Parameter(Mandatory=$true)] [string] # The name of the project you're uploading a file to. $ProjectName, [Parameter(Mandatory=$true)] [string[]] # The paths to the files and directories to include in the ZIP file. All files and sub-directories under directory are added. $Path, [Parameter(Mandatory=$true)] [string] # The path to the manifest of the module being published. $ManifestPath ) Set-StrictMode -Version 'Latest' function Assert-Response { param( [Microsoft.PowerShell.Commands.HtmlWebResponseObject] $Response, [Uri] $ExpectedUri ) if( -not $Response ) { Write-Error ('No response.') return $false } if( $Response.BaseResponse.StatusCode -ne [Net.HttpStatusCode]::OK ) { Write-Error ('Response failed.') return $false } if( $Response.BaseResponse.ResponseUri -ne $ExpectedUri ) { Write-Error ('Response didn''t finish on URI {0} ({1}).' -f $ExpectedUri,$Response.BaseResponse.ResponseUri) return $false } $errorElement = $Response.ParsedHtml.getElementById('error') if( $errorElement -and ($errorElement | Get-Member 'innerHtml') -and $erroElement.innerHtml ) { Write-Error $errorElement.innerHtml return $false } return $true } $manifest = Test-ModuleManifest -Path $ManifestPath if( -not $manifest ) { return } $baseProjectUri = 'https://bitbucket.org/{0}/{1}' -f $Username,$ProjectName $zipFileName = "{0}-{1}.zip" -f $manifest.Name,$manifest.Version $zipDownloadUrl = '{0}/downloads/{1}' -f $baseProjectUri,$zipFileName try { $resp = Invoke-WebRequest -Uri $zipDownloadUrl -ErrorAction Ignore $publish = ($resp.StatusCode -ne 200) } catch { $publish = $true } if( -not $publish ) { Write-Warning -Message ('{0} file already published.' -f $zipFileName) return } $zipFilePath = Join-Path -Path $env:TEMP -ChildPath $zipFileName $outFile = '{0}+{1}' -f $manifest.Name,[IO.Path]::GetRandomFileName() $outFile = Join-Path -Path $env:TEMP -ChildPath $outFile try { if( Test-Path $zipFilePath -PathType Leaf ) { Remove-Item $zipFilePath } Write-Verbose -Message ('Creating {0} ZIP file.' -f $zipFileName) Compress-Item -Path $Path -OutFile $zipFilePath $PSDefaultParameterValues.Clear() $PSDefaultParameterValues['Invoke-WebRequest:PassThru'] = $true $PSDefaultParameterValues['Invoke-WebRequest:OutFile'] = $outFile if( -not $Credential ) { $Credential = Get-Credential -Message ('Enter credentials for {0}' -f $baseProjectUri) } $session = $null $loginUri = 'https://bitbucket.org/account/signin/' $resp = Invoke-WebRequest -Uri $loginUri -SessionVariable 'session' -Method Get if( -not (Assert-Response -Response $resp -ExpectedUri $loginUri) ) { return } $PSDefaultParameterValues['Invoke-WebRequest:WebSession'] = $session $form = $resp.Forms | Where-Object { $_.Action -eq '/account/signin/' } $formFields = $form.Fields $formFields.id_username = $Credential.UserName $formFields.id_password = $Credential.GetNetworkCredential().Password $loginUri = 'https://bitbucket.org{0}' -f $form.Action $body = @{ 'username' = $Credential.UserName; 'password' = $Credential.GetNetworkCredential().Password; 'csrfmiddlewaretoken' = $formFields.csrfmiddlewaretoken; 'submit' = ''; 'next' = ''; } $resp = Invoke-WebRequest -Uri $loginUri -Method $form.Method -Body $body -Headers @{ Referer = $loginUri } if( -not (Assert-Response -Response $resp -ExpectedUri 'https://bitbucket.org/') ) { exit 1 } $downloadUri = '{0}/downloads' -f $baseProjectUri $resp = Invoke-WebRequest -Uri $downloadUri -Method Get if( -not (Assert-Response -Response $resp -ExpectedUri $downloadUri) ) { exit 1 } $csrfToken = $resp.Forms | Where-Object { $_.Fields.ContainsKey( 'csrfmiddlewaretoken' ) } | ForEach-Object { $_.Fields.csrfmiddlewaretoken } Write-Debug $csrfToken $boundary = [Guid]::NewGuid().ToString() $bodyStart = @" --$boundary Content-Disposition: form-data; name="csrfmiddlewaretoken" $csrfToken --$boundary Content-Disposition: form-data; name="token" --$boundary Content-Disposition: form-data; name="files"; filename="$(Split-Path -Leaf -Path $zipFilePath)" Content-Type: application/octet-stream "@ $bodyEnd = @" --$boundary-- "@ $requestInFile = Join-Path -Path $env:TEMP -ChildPath ([IO.Path]::GetRandomFileName()) try { $fileStream = New-Object 'System.IO.FileStream' ($requestInFile, [System.IO.FileMode]'Create', [System.IO.FileAccess]'Write') try { $bytes = [Text.Encoding]::UTF8.GetBytes($bodyStart) $fileStream.Write( $bytes, 0, $bytes.Length ) $bytes = [IO.File]::ReadAllBytes($zipFilePath) $fileStream.Write( $bytes, 0, $bytes.Length ) $bytes = [Text.Encoding]::UTF8.GetBytes($bodyEnd) $fileStream.Write( $bytes, 0, $bytes.Length ) } finally { $fileStream.Close() } $contentType = 'multipart/form-data; boundary={0}' -f $boundary $resp = Invoke-WebRequest -Uri $downloadUri ` -Method Post ` -InFile $requestInFile ` -ContentType $contentType ` -Headers @{ Referer = $downloadUri } if( -not (Assert-Response -Response $resp -ExpectedUri $downloadUri) ) { return } } finally { Remove-Item -Path $requestInFile } $numTries = 10 $tryNum = 0 while( $tryNum++ -lt $numTries ) { try { $resp = Invoke-WebRequest -Uri $zipDownloadUrl $resp | Select-Object -Property 'StatusCode','StatusDescription',@{ Name = 'Uri'; Expression = { $zipDownloadUrl }} break } catch { Start-Sleep -Seconds 1 } } } finally { if( (Test-Path -Path $outFile -PathType Leaf) ) { Remove-Item -Path $outFile } if( (Test-Path -Path $zipFilePath -PathType Leaf) ) { Remove-Item -Path $zipFilePath } } }
PowerShellCorpus/PowerShellGallery/Silk/0.2.0/Functions/New-NuGetPackage.ps1
New-NuGetPackage.ps1
# Copyright 2012 Aaron Jensen # # Licensed under the Apache License, Version 2.0 (the "License"); # you may not use this file except in compliance with the License. # You may obtain a copy of the License at # # http://www.apache.org/licenses/LICENSE-2.0 # # Unless required by applicable law or agreed to in writing, software # distributed under the License is distributed on an "AS IS" BASIS, # WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. # See the License for the specific language governing permissions and # limitations under the License. function New-NuGetPackage { <# .SYNOPSIS Creates a NuGet package. #> [CmdletBinding(SupportsShouldProcess=$true)] param( [Parameter(Mandatory=$true)] [string] # The path to the module manifest of the module you want to publish. $ManifestPath, [Parameter(Mandatory=$true)] [string] # The path to the nuspec file for the NuGet package to publish. $NuspecPath, [Parameter(Mandatory=$true)] [string] # The base directory for the files defined in the `NuspecPath` file. $NuspecBasePath, [string] # The name of the NuGet package, if it is different than the module name. $PackageName, [Parameter(Mandatory=$true)] [string] # The directory where the .nupkg file should be saved. $OutputDirectory ) Set-StrictMode -Version 'Latest' Use-CallerPreference -Cmdlet $PSCmdlet -Session $ExecutionContext.SessionState $nugetPath = Join-Path -Path $PSScriptRoot -ChildPath '..\bin\NuGet.exe' -Resolve if( -not $nugetPath ) { return } if( -not (Test-Path -Path $OutputDirectory -PathType Container) ) { New-Item -Path $OutputDirectory -ItemType 'directory' -Force } $manifest = Test-ModuleManifest -Path $ManifestPath if( -not $manifest ) { return } if( -not $PackageName ) { $PackageName = $manifest.Name } Push-Location -Path $NuSpecBasePath try { $nupkgPath = Join-Path -Path $OutputDirectory -ChildPath ('{0}.{1}.nupkg' -f $PackageName,$manifest.Version) if( (Test-Path -Path $nupkgPath -PathType Leaf) ) { Remove-Item -Path $nupkgPath } $verbosity = 'normal' if( $VerbosePreference -eq 'Continue' ) { $verbosity = 'detailed' } & $nugetPath pack $NuspecPath -BasePath '.' -NoPackageAnalysis -Verbosity $verbosity -OutputDirectory $OutputDirectory if( -not (Test-Path -Path $nupkgPath -PathType Leaf) ) { Write-Error ('NuGet package ''{0}'' not found.' -f $nupkgPath) return } } finally { Pop-Location } }
PowerShellCorpus/PowerShellGallery/Silk/0.2.0/Functions/Convert-RelatedLinkToHtml.ps1
Convert-RelatedLinkToHtml.ps1
function Convert-RelatedLinkToHtml { <# .SYNOPSIS Converts a command's related link to HTML. .DESCRIPTION `Convert-RelatedLinkToHtml` converts a command's related links to HTML. If the related link is not a URL, the command name is converted to a link that poitns to a `CommandName.html` file. #> [CmdletBinding()] param( [Parameter(Mandatory=$true,ValueFromPipeline=$true)] # The help object returned by `Get-Help`. $CommandHelp, [string] # The name of the module the command is in. $ModuleName, [string[]] # The names of any scripts in the module. $Script ) begin { Set-StrictMode -Version 'Latest' } process { if( -not $ModuleName -and ($CommandHelp | Get-Member -Name 'ModuleName') -and $CommandHelp.ModuleName ) { $ModuleName = $CommandHelp.ModuleName } $aboutTopics = @() if( $ModuleName ) { $moduleBase = Get-Module -Name $ModuleName | Select-Object -ExpandProperty 'ModuleBase' if( $moduleBase -and (Test-Path -Path (Join-Path -Path $moduleBase -ChildPath 'en-US') -PathType Container) ) { $aboutTopics = $moduleBase | Get-ChildItem -Filter 'en-US\about_*' | Select-Object -ExpandProperty 'BaseName' | ForEach-Object { $_ -replace '\.help$','' } } else { $aboutTopics = @() } } Invoke-Command -ScriptBlock { if( $CommandHelp | Get-Member -Name 'RelatedLinks' ) { return $CommandHelp.RelatedLinks | Out-String -Width ([Int32]::MaxValue) | ForEach-Object { $_ -split "`n" } | ForEach-Object { $_.Trim() } | Where-Object { $_ } } if( $CommandHelp -is [string] ) { return $CommandHelp } } | ForEach-Object { if( $_ -match '^https?\:\/\/' ) { return '<a href="{0}">{0}</a>' -f $_ } if( $ModuleName -and (Get-Command -Name $_ -Module $ModuleName -ErrorAction Ignore) ) { $cmdName = $_ $alias = Get-Alias -Name $_ -ErrorAction Ignore | Where-Object { $_.ModuleName -eq $ModuleName } if( $alias ) { $cmdName = $alias.ReferencedCommand } return '<a href="{0}.html">{1}</a>' -f $cmdName,$_ } $cmd = Get-Command -Name $_ -ErrorAction Ignore if( $cmd -and $cmd.HelpUri ) { return '<a href="{0}.html">{1}</a>' -f $cmd.HelpUri,$_ } if( $aboutTopics -contains $_ -or $Script -contains $_ ) { return '<a href="{0}.html">{0}</a>' -f $_ } return $_ } } end { } }
PowerShellCorpus/PowerShellGallery/Silk/0.2.0/Functions/Set-ModuleManifestMetadata.ps1
Set-ModuleManifestMetadata.ps1
function Set-ModuleManifestMetadata { [CmdletBinding()] param( [Parameter(Mandatory=$true)] # The path to the module. $ManifestPath, [string[]] # Tags for the module. $Tag, [string] # The path to the module's release notes. $ReleaseNotesPath ) Set-StrictMode -Version 'Latest' $releaseNotes = Get-ModuleReleaseNotes -ManifestPath $ManifestPath -ReleaseNotesPath $ReleaseNotesPath $manifest = Test-ModuleManifest -Path $ManifestPath if( -not $manifest ) { return } $module = Import-Module -Force -Name $manifestPath -PassThru $foundTags = $false $foundReleaseNotes = $false $inReleaseNotes = $false $releaseNotesWhitespacePrefix = '' $moduleManifestLines = Get-Content -Path $manifestPath | ForEach-Object { $line = $_ if( $inReleaseNotes ) { if( $line -match '^(''|")@$' ) { $inReleaseNotes = $false $foundReleaseNotes = $true return '{0}ReleaseNotes = @{1}{2}{3}{2}{1}@' -f $releaseNotesWhitespacePrefix,$Matches[1],[Environment]::NewLine,$releaseNotes.Trim() } return } if( $line -match '^(\s+)ReleaseNotes\ =\ @(''|")$' ) { $inReleaseNotes = $true $releaseNotesWhitespacePrefix = $Matches[1] return } if( $line -match '^(\s+)Tags\ =\ @\(' ) { $foundTags = $true return '{0}Tags = @(''{1}'')' -f $Matches[1],($Tag -join ''',''') } return $_ } if( -not $foundTags ) { Write-Error -Message ('PrivateData PSData hashtable missing Tags metadata. Please add `Tags = @()` to the PSData section of {0} and re-run.' -f $ManifestPath) return } if( -not $foundReleaseNotes ) { Write-Error -Message (@" PrivateData PSData hasthable missing ReleaseNotes metadata. Please add a `ReleaseNotes` key to the PSData hashtable whose value is an empty here string, e.g. PrivateData = @{ PSData = @{ ReleaseNotes = @' '@ } } "@) return } $moduleManifestLines | Set-Content -Path $ManifestPath }
PowerShellCorpus/PowerShellGallery/Silk/0.2.0/Functions/Get-ModuleReleaseNotes.ps1
Get-ModuleReleaseNotes.ps1
function Get-ModuleReleaseNotes { param( [Parameter(Mandatory=$true)] [string] # Path to the module's manifest. $ManifestPath, [Parameter(Mandatory=$true)] [string] # Path to the releaes notes file. $ReleaseNotesPath ) Set-StrictMode -Version 'Latest' $Version = Test-ModuleManifest -Path $ManifestPath | Select-Object -ExpandProperty 'Version' if( -not $Version ) { Write-Error -Message ('Version not found in module manifest ''{0}''.' -f $ManifestPath) return } $foundVersion = $false $versionReleaseNotes = Get-Content -Path $ReleaseNotesPath | Where-Object { $line = $_ if( -not $foundVersion ) { if( $line -match ('^#\s+{0}' -f [regex]::Escape($version)) ) { $foundVersion = $true return } } else { if( $line -match ('^#\s+(?!{0})' -f [regex]::Escape($version)) ) { $foundVersion = $false } } return( $foundVersion ) } if( -not $versionReleaseNotes ) { Write-Error -Message ('There are no release notes for version {0} in ''{1}''.' -f $Version,$ReleaseNotesPath) return } $versionReleaseNotes -join [Environment]::NewLine }
PowerShellCorpus/PowerShellGallery/Silk/0.2.0/Functions/Convert-MarkdownToHtml.ps1
Convert-MarkdownToHtml.ps1
filter Convert-MarkdownToHtml { if( $_ ) { $markdown.Transform( $_ ).Trim() } }
PowerShellCorpus/PowerShellGallery/MeasureScript/0.1.0.0/Measure-Script.ps1
Measure-Script.ps1
#region Profiler class Profiler { [System.Diagnostics.Stopwatch[]]$StopWatches Profiler([System.Management.Automation.Language.IScriptExtent]$extent) { $lines = $extent.EndLineNumber $this.StopWatches = [System.Diagnostics.Stopwatch[]]::new($lines) for ($i = 0; $i -lt $lines; $i++) { $this.StopWatches[$i] = [System.Diagnostics.Stopwatch]::new() } } [void] StartLine([int] $lineNo) { $this.StopWatches[$lineNo].Start() } [void] EndLine([int] $lineNo) { $this.StopWatches[$lineNo].Stop() } } #endregion #region AstVisitor class AstVisitor : System.Management.Automation.Language.ICustomAstVisitor { [Profiler]$Profiler = $null AstVisitor([Profiler]$profiler) { $this.Profiler = $profiler } [System.Object] VisitElement([object]$element) { if ($element -eq $null) { return $null } $res = $element.Visit($this) return $res } [System.Object] VisitElements([System.Object]$elements) { if ($elements -eq $null -or $elements.Count -eq 0) { return $null } $typeName = $elements.gettype().GenericTypeArguments.Fullname $newElements = New-Object -TypeName "System.Collections.Generic.List[$typeName]" foreach($element in $elements) { $visitedResult = $element.Visit($this) $newElements.add($visitedResult) } return $newElements } [System.Management.Automation.Language.StatementAst[]] VisitStatements([object]$Statements) { $newStatements = [System.Collections.Generic.List[System.Management.Automation.Language.StatementAst]]::new() foreach ($statement in $statements) { [bool]$instrument = $statement -is [System.Management.Automation.Language.PipelineBaseAst] $extent = $statement.Extent if ($instrument) { $expressionAstCollection = [System.Collections.Generic.List[System.Management.Automation.Language.ExpressionAst]]::new() $constantExpression = [System.Management.Automation.Language.ConstantExpressionAst]::new($extent, $extent.StartLineNumber - 1) $expressionAstCollection.Add($constantExpression) $constantProfiler = [System.Management.Automation.Language.ConstantExpressionAst]::new($extent, $this.Profiler) $constantStartline = [System.Management.Automation.Language.StringConstantExpressionAst]::new($extent, "StartLine", [System.Management.Automation.Language.StringConstantType]::BareWord) $invokeMember = [System.Management.Automation.Language.InvokeMemberExpressionAst]::new( $extent, $constantProfiler, $constantStartline, $expressionAstCollection, $false ) $startLine = [System.Management.Automation.Language.CommandExpressionAst]::new( $extent, $invokeMember, $null ) $pipe = [System.Management.Automation.Language.PipelineAst]::new($extent, $startLine); $newStatements.Add($pipe) } $newStatements.Add($this.VisitElement($statement)) if ($instrument) { $expressionAstCollection = [System.Collections.Generic.List[System.Management.Automation.Language.ExpressionAst]]::new() $expressionAstCollection.Add([System.Management.Automation.Language.ConstantExpressionAst]::new($extent, $extent.StartLineNumber - 1)) $endLine = [System.Management.Automation.Language.CommandExpressionAst]::new( $extent, [System.Management.Automation.Language.InvokeMemberExpressionAst]::new( $extent, [System.Management.Automation.Language.ConstantExpressionAst]::new($extent, $this.Profiler), [System.Management.Automation.Language.StringConstantExpressionAst]::new($extent, "EndLine", [System.Management.Automation.Language.StringConstantType]::BareWord), $expressionAstCollection, $false ), $null ) $pipe = [System.Management.Automation.Language.PipelineAst]::new($extent, $endLine) $newStatements.add($pipe) } } return $newStatements } [system.object] VisitScriptBlock([System.Management.Automation.Language.ScriptBlockAst] $scriptBlockAst) { $newParamBlock = $this.VisitElement($scriptBlockAst.ParamBlock) $newBeginBlock = $this.VisitElement($scriptBlockAst.BeginBlock) $newProcessBlock = $this.VisitElement($scriptBlockAst.ProcessBlock) $newEndBlock = $this.VisitElement($scriptBlockAst.EndBlock) $newDynamicParamBlock = $this.VisitElement($scriptBlockAst.DynamicParamBlock) return [System.Management.Automation.Language.ScriptBlockAst]::new($scriptBlockAst.Extent, $newParamBlock, $newBeginBlock, $newProcessBlock, $newEndBlock, $newDynamicParamBlock) } [system.object] VisitNamedBlock([System.Management.Automation.Language.NamedBlockAst] $namedBlockAst) { $newTraps = $this.VisitElements($namedBlockAst.Traps) $newStatements = $this.VisitStatements($namedBlockAst.Statements) $statementBlock = [System.Management.Automation.Language.StatementBlockAst]::new($namedBlockAst.Extent,$newStatements,$newTraps) return [System.Management.Automation.Language.NamedBlockAst]::new($namedBlockAst.Extent, $namedBlockAst.BlockKind, $statementBlock, $namedBlockAst.Unnamed) } [system.object] VisitFunctionDefinition([System.Management.Automation.Language.FunctionDefinitionAst] $functionDefinitionAst) { $newBody = $this.VisitElement($functionDefinitionAst.Body) return [System.Management.Automation.Language.FunctionDefinitionAst]::new($functionDefinitionAst.Extent, $functionDefinitionAst.IsFilter,$functionDefinitionAst.IsWorkflow, $functionDefinitionAst.Name, $this.VisitElements($functionDefinitionAst.Parameters), $newBody); } [system.object] VisitStatementBlock([System.Management.Automation.Language.StatementBlockAst] $statementBlockAst) { $newStatements = $this.VisitStatements($statementBlockAst.Statements) $newTraps = $this.VisitElements($statementBlockAst.Traps) return [System.Management.Automation.Language.StatementBlockAst]::new($statementBlockAst.Extent, $newStatements, $newTraps) } [system.object] VisitIfStatement([System.Management.Automation.Language.IfStatementAst] $ifStmtAst) { $newClauses = $ifStmtAst.Clauses | ForEach-Object { $newClauseTest = $this.VistitElement($_.Item1) $newStatementBlock = $this.VistitElement($_.Item2) [System.Tuple[System.Management.Automation.Language.PipelineBaseAst,System.Management.Automation.Language.StatementBlockAst]]::new($newClauseTest,$newStatementBlock) } $newElseClause = $this.VisitElement($ifStmtAst.ElseClause) return [System.Management.Automation.Language.IfStatementAst]::new($ifStmtAst.Extent, $newClauses, $newElseClause) } [system.object] VisitTrap([System.Management.Automation.Language.TrapStatementAst] $trapStatementAst) { return [System.Management.Automation.Language.TrapStatementAst]::new($trapStatementAst.Extent, $this.VisitElement($trapStatementAst.TrapType), $this.VisitElement($trapStatementAst.Body)) } [system.object] VisitSwitchStatement([System.Management.Automation.Language.SwitchStatementAst] $switchStatementAst) { $newCondition = $this.VisitElement($switchStatementAst.Condition) $newClauses = $switchStatementAst.Clauses | ForEach-Object { $newClauseTest = $this.VistitElement($_.Item1) $newStatementBlock = $this.VistitElement($_.Item2) [System.Tuple[System.Management.Automation.Language.ExpressionAst,System.Management.Automation.Language.StatementBlockAst]]::new($newClauseTest,$newStatementBlock) } $newDefault = $this.VisitElement($switchStatementAst.Default) return [System.Management.Automation.Language.SwitchStatementAst]::new($switchStatementAst.Extent, $switchStatementAst.Label,$newCondition,$switchStatementAst.Flags, $newClauses, $newDefault) } [system.object] VisitDataStatement([System.Management.Automation.Language.DataStatementAst] $dataStatementAst) { $newBody = $this.VisitElement($dataStatementAst.Body) $newCommandsAllowed = $this.VisitElements($dataStatementAst.CommandsAllowed) return [System.Management.Automation.Language.DataStatementAst]::new($dataStatementAst.Extent, $dataStatementAst.Variable, $newCommandsAllowed, $newBody) } [system.object] VisitForEachStatement([System.Management.Automation.Language.ForEachStatementAst] $forEachStatementAst) { $newVariable = $this.VisitElement($forEachStatementAst.Variable) $newCondition = $this.VisitElement($forEachStatementAst.Condition) $newBody = $this.VisitElement($forEachStatementAst.Body) return [System.Management.Automation.Language.ForEachStatementAst]::new($forEachStatementAst.Extent, $forEachStatementAst.Label, [System.Management.Automation.Language.ForEachFlags]::None, $newVariable, $newCondition, $newBody) } [system.object] VisitDoWhileStatement([System.Management.Automation.Language.DoWhileStatementAst] $doWhileStatementAst) { $newCondition = $this.VisitElement($doWhileStatementAst.Condition) $newBody = $this.VisitElement($doWhileStatementAst.Body) return [System.Management.Automation.Language.DoWhileStatementAst]::new($doWhileStatementAst.Extent, $doWhileStatementAst.Label, $newCondition, $newBody) } [system.object] VisitForStatement([System.Management.Automation.Language.ForStatementAst] $forStatementAst) { $newInitializer = $this.VisitElement($forStatementAst.Initializer) $newCondition = $this.VisitElement($forStatementAst.Condition) $newIterator = $this.VisitElement($forStatementAst.Iterator) $newBody = $this.VisitElement($forStatementAst.Body) return [System.Management.Automation.Language.ForStatementAst]::new($forStatementAst.Extent, $forStatementAst.Label, $newInitializer, $newCondition, $newIterator, $newBody) } [system.object] VisitWhileStatement([System.Management.Automation.Language.WhileStatementAst] $whileStatementAst) { $newCondition = $this.VisitElement($whileStatementAst.Condition) $newBody = $this.VisitElement($whileStatementAst.Body) return [System.Management.Automation.Language.WhileStatementAst]::new($whileStatementAst.Extent, $whileStatementAst.Label, $newCondition, $newBody) } [system.object] VisitCatchClause([System.Management.Automation.Language.CatchClauseAst] $catchClauseAst) { $newBody = $this.VisitElement($catchClauseAst.Body) return [System.Management.Automation.Language.CatchClauseAst]::new($catchClauseAst.Extent, $catchClauseAst.CatchTypes, $newBody) } [system.object] VisitTryStatement([System.Management.Automation.Language.TryStatementAst] $tryStatementAst) { $newBody = $this.VisitElement($tryStatementAst.Body) $newCatchClauses = $this.VisitElements($tryStatementAst.CatchClauses) $newFinally = $this.VisitElement($tryStatementAst.Finally) return [System.Management.Automation.Language.TryStatementAst]::new($tryStatementAst.Extent, $newBody, $newCatchClauses, $newFinally) } [system.object] VisitDoUntilStatement([System.Management.Automation.Language.DoUntilStatementAst] $doUntilStatementAst) { $newCondition = $this.VisitElement($doUntilStatementAst.Condition) $newBody = $this.VisitElement($doUntilStatementAst.Body) return [System.Management.Automation.Language.DoUntilStatementAst]::new($doUntilStatementAst.Extent, $doUntilStatementAst.Label, $newCondition, $newBody) } [system.object] VisitParamBlock([System.Management.Automation.Language.ParamBlockAst] $paramBlockAst) { $newAttributes = $this.VisitElements($paramBlockAst.Attributes) $newParameters = $this.VisitElements($paramBlockAst.Parameters) return [System.Management.Automation.Language.ParamBlockAst]::new($paramBlockAst.Extent, $newAttributes, $newParameters) } [system.object] VisitErrorStatement([System.Management.Automation.Language.ErrorStatementAst] $errorStatementAst) { return $errorStatementAst } [system.object] VisitErrorExpression([System.Management.Automation.Language.ErrorExpressionAst] $errorExpressionAst) { return $errorExpressionAst } [system.object] VisitTypeConstraint([System.Management.Automation.Language.TypeConstraintAst] $typeConstraintAst) { return [System.Management.Automation.Language.TypeConstraintAst]::new($typeConstraintAst.Extent, $typeConstraintAst.TypeName) } [system.object] VisitAttribute([System.Management.Automation.Language.AttributeAst] $attributeAst) { $newPositionalArguments = $this.VisitElements($attributeAst.PositionalArguments) $newNamedArguments = $this.VisitElements($attributeAst.NamedArguments) return [System.Management.Automation.Language.AttributeAst]::new($attributeAst.Extent, $attributeAst.TypeName, $newPositionalArguments, $newNamedArguments) } [system.object] VisitNamedAttributeArgument([System.Management.Automation.Language.NamedAttributeArgumentAst] $namedAttributeArgumentAst) { $newArgument = $this.VisitElement($namedAttributeArgumentAst.Argument) return [System.Management.Automation.Language.NamedAttributeArgumentAst]::new($namedAttributeArgumentAst.Extent, $namedAttributeArgumentAst.ArgumentName, $newArgument,$namedAttributeArgumentAst.ExpressionOmitted) } [system.object] VisitParameter([System.Management.Automation.Language.ParameterAst] $parameterAst) { $newName = $this.VisitElement($parameterAst.Name) $newAttributes = $this.VisitElements($parameterAst.Attributes) $newDefaultValue = $this.VisitElement($parameterAst.DefaultValue) return [System.Management.Automation.Language.ParameterAst]::new($parameterAst.Extent, $newName, $newAttributes, $newDefaultValue) } [system.object] VisitBreakStatement([System.Management.Automation.Language.BreakStatementAst] $breakStatementAst) { $newLabel = $this.VisitElement($breakStatementAst.Label) return [System.Management.Automation.Language.BreakStatementAst]::new($breakStatementAst.Extent, $newLabel) } [system.object] VisitContinueStatement([System.Management.Automation.Language.ContinueStatementAst] $continueStatementAst) { $newLabel = $this.VisitElement($continueStatementAst.Label) return [System.Management.Automation.Language.ContinueStatementAst]::new($continueStatementAst.Extent, $newLabel) } [system.object] VisitReturnStatement([System.Management.Automation.Language.ReturnStatementAst] $returnStatementAst) { $newPipeline = $this.VisitElement($returnStatementAst.Pipeline) return [System.Management.Automation.Language.ReturnStatementAst]::new($returnStatementAst.Extent, $newPipeline) } [system.object] VisitExitStatement([System.Management.Automation.Language.ExitStatementAst] $exitStatementAst) { $newPipeline = $this.VisitElement($exitStatementAst.Pipeline) return [System.Management.Automation.Language.ExitStatementAst]::new($exitStatementAst.Extent, $newPipeline) } [system.object] VisitThrowStatement([System.Management.Automation.Language.ThrowStatementAst] $throwStatementAst) { $newPipeline = $this.VisitElement($throwStatementAst.Pipeline) return [System.Management.Automation.Language.ThrowStatementAst]::new($throwStatementAst.Extent, $newPipeline) } [system.object] VisitAssignmentStatement([System.Management.Automation.Language.AssignmentStatementAst] $assignmentStatementAst) { $newLeft = $this.VisitElement($assignmentStatementAst.Left) $newRight = $this.VisitElement($assignmentStatementAst.Right) return [System.Management.Automation.Language.AssignmentStatementAst]::new($assignmentStatementAst.Extent, $newLeft, $assignmentStatementAst.Operator,$newRight, $assignmentStatementAst.ErrorPosition) } [system.object] VisitPipeline([System.Management.Automation.Language.PipelineAst] $pipelineAst) { $newPipeElements = $this.VisitElements($pipelineAst.PipelineElements) return [System.Management.Automation.Language.PipelineAst]::new($pipelineAst.Extent, $newPipeElements) } [system.object] VisitCommand([System.Management.Automation.Language.CommandAst] $commandAst) { $newCommandElements = $this.VisitElements($commandAst.CommandElements) $newRedirections = $this.VisitElements($commandAst.Redirections) return [System.Management.Automation.Language.CommandAst]::new($commandAst.Extent, $newCommandElements, $commandAst.InvocationOperator, $newRedirections) } [system.object] VisitCommandExpression([System.Management.Automation.Language.CommandExpressionAst] $commandExpressionAst) { $newExpression = $this.VisitElement($commandExpressionAst.Expression) $newRedirections = $this.VisitElements($commandExpressionAst.Redirections) return [System.Management.Automation.Language.CommandExpressionAst]::new($commandExpressionAst.Extent, $newExpression, $newRedirections) } [system.object] VisitCommandParameter([System.Management.Automation.Language.CommandParameterAst] $commandParameterAst) { $newArgument = $this.VisitElement($commandParameterAst.Argument) return [System.Management.Automation.Language.CommandParameterAst]::new($commandParameterAst.Extent, $commandParameterAst.ParameterName, $newArgument, $commandParameterAst.ErrorPosition) } [system.object] VisitFileRedirection([System.Management.Automation.Language.FileRedirectionAst] $fileRedirectionAst) { $newFile = $this.VisitElement($fileRedirectionAst.Location) return [System.Management.Automation.Language.FileRedirectionAst]::new($fileRedirectionAst.Extent, $fileRedirectionAst.FromStream, $newFile, $fileRedirectionAst.Append) } [system.object] VisitMergingRedirection([System.Management.Automation.Language.MergingRedirectionAst] $mergingRedirectionAst) { return [System.Management.Automation.Language.MergingRedirectionAst]::new($mergingRedirectionAst.Extent, $mergingRedirectionAst.FromStream, $mergingRedirectionAst.ToStream) } [system.object] VisitBinaryExpression([System.Management.Automation.Language.BinaryExpressionAst] $binaryExpressionAst) { $newLeft = $this.VisitElement($binaryExpressionAst.Left) $newRight = $this.VisitElement($binaryExpressionAst.Right) return [System.Management.Automation.Language.BinaryExpressionAst]::new($binaryExpressionAst.Extent, $newLeft, $binaryExpressionAst.Operator, $newRight, $binaryExpressionAst.ErrorPosition) } [system.object] VisitUnaryExpression([System.Management.Automation.Language.UnaryExpressionAst] $unaryExpressionAst) { $newChild = $this.VisitElement($unaryExpressionAst.Child) return [System.Management.Automation.Language.UnaryExpressionAst]::new($unaryExpressionAst.Extent, $unaryExpressionAst.TokenKind, $newChild) } [system.object] VisitConvertExpression([System.Management.Automation.Language.ConvertExpressionAst] $convertExpressionAst) { $newChild = $this.VisitElement($convertExpressionAst.Child) $newTypeConstraint = $this.VisitElement($convertExpressionAst.Type) return [System.Management.Automation.Language.ConvertExpressionAst]::new($convertExpressionAst.Extent, $newTypeConstraint, $newChild) } [system.object] VisitTypeExpression([System.Management.Automation.Language.TypeExpressionAst] $typeExpressionAst) { return [System.Management.Automation.Language.TypeExpressionAst]::new($typeExpressionAst.Extent, $typeExpressionAst.TypeName) } [system.object] VisitConstantExpression([System.Management.Automation.Language.ConstantExpressionAst] $constantExpressionAst) { return [System.Management.Automation.Language.ConstantExpressionAst]::new($constantExpressionAst.Extent, $constantExpressionAst.Value) } [system.object] VisitStringConstantExpression([System.Management.Automation.Language.StringConstantExpressionAst] $stringConstantExpressionAst) { return [System.Management.Automation.Language.StringConstantExpressionAst]::new($stringConstantExpressionAst.Extent, $stringConstantExpressionAst.Value, $stringConstantExpressionAst.StringConstantType) } [system.object] VisitSubExpression([System.Management.Automation.Language.SubExpressionAst] $subExpressionAst) { $newStatementBlock = $this.VisitElement($subExpressionAst.SubExpression) return [System.Management.Automation.Language.SubExpressionAst]::new($subExpressionAst.Extent, $newStatementBlock) } [system.object] VisitUsingExpression([System.Management.Automation.Language.UsingExpressionAst] $usingExpressionAst) { $newUsingExpr = $this.VisitElement($usingExpressionAst.SubExpression) return [System.Management.Automation.Language.UsingExpressionAst]::new($usingExpressionAst.Extent, $newUsingExpr) } [system.object] VisitVariableExpression([System.Management.Automation.Language.VariableExpressionAst] $variableExpressionAst) { return [System.Management.Automation.Language.VariableExpressionAst]::new($variableExpressionAst.Extent, $variableExpressionAst.VariablePath.UserPath, $variableExpressionAst.Splatted) } [system.object] VisitMemberExpression([System.Management.Automation.Language.MemberExpressionAst] $memberExpressionAst) { $newExpr = $this.VisitElement($memberExpressionAst.Expression) $newMember = $this.VisitElement($memberExpressionAst.Member) return [System.Management.Automation.Language.MemberExpressionAst]::new($memberExpressionAst.Extent, $newExpr, $newMember, $memberExpressionAst.Static) } [system.object] VisitInvokeMemberExpression([System.Management.Automation.Language.InvokeMemberExpressionAst] $invokeMemberExpressionAst) { $newExpression = $this.VisitElement($invokeMemberExpressionAst.Expression) $newMethod = $this.VisitElement($invokeMemberExpressionAst.Member) $newArguments = $this.VisitElements($invokeMemberExpressionAst.Arguments) return [System.Management.Automation.Language.InvokeMemberExpressionAst]::new($invokeMemberExpressionAst.Extent, $newExpression, $newMethod, $newArguments, $invokeMemberExpressionAst.Static) } [system.object] VisitArrayExpression([System.Management.Automation.Language.ArrayExpressionAst] $arrayExpressionAst) { $newStatementBlock = $this.VisitElement($arrayExpressionAst.SubExpression) return [System.Management.Automation.Language.ArrayExpressionAst]::new($arrayExpressionAst.Extent, $newStatementBlock) } [system.object] VisitArrayLiteral([System.Management.Automation.Language.ArrayLiteralAst] $arrayLiteralAst) { $newArrayElements = $this.VisitElements($arrayLiteralAst.Elements) return [System.Management.Automation.Language.ArrayLiteralAst]::new($arrayLiteralAst.Extent, $newArrayElements) } [system.object] VisitHashtable([System.Management.Automation.Language.HashtableAst] $hashtableAst) { $newKeyValuePairs = [System.Collections.Generic.List[System.Tuple[System.Management.Automation.Language.ExpressionAst,System.Management.Automation.Language.StatementAst]]]::new() foreach ($keyValuePair in $hashtableAst.KeyValuePairs) { $newKey = $this.VisitElement($keyValuePair.Item1); $newValue = $this.VisitElement($keyValuePair.Item2); $newKeyValuePairs.Add([System.Tuple[System.Management.Automation.Language.ExpressionAst,System.Management.Automation.Language.StatementAst]]::new($newKey, $newValue)) # TODO NOT SURE } return [System.Management.Automation.Language.HashtableAst]::new($hashtableAst.Extent, $newKeyValuePairs) } [system.object] VisitScriptBlockExpression([System.Management.Automation.Language.ScriptBlockExpressionAst] $scriptBlockExpressionAst) { $newScriptBlock = $this.VisitElement($scriptBlockExpressionAst.ScriptBlock) return [System.Management.Automation.Language.ScriptBlockExpressionAst]::new($scriptBlockExpressionAst.Extent, $newScriptBlock) } [system.object] VisitParenExpression([System.Management.Automation.Language.ParenExpressionAst] $parenExpressionAst) { $newPipeline = $this.VisitElement($parenExpressionAst.Pipeline) return [System.Management.Automation.Language.ParenExpressionAst]::new($parenExpressionAst.Extent, $newPipeline) } [system.object] VisitExpandableStringExpression([System.Management.Automation.Language.ExpandableStringExpressionAst] $expandableStringExpressionAst) { return [System.Management.Automation.Language.ExpandableStringExpressionAst]::new($expandableStringExpressionAst.Extent,$expandableStringExpressionAst.Value,$expandableStringExpressionAst.StringConstantType) } [system.object] VisitIndexExpression([System.Management.Automation.Language.IndexExpressionAst] $indexExpressionAst) { $newTargetExpression = $this.VisitElement($indexExpressionAst.Target) $newIndexExpression = $this.VisitElement($indexExpressionAst.Index) return [System.Management.Automation.Language.IndexExpressionAst]::new($indexExpressionAst.Extent, $newTargetExpression, $newIndexExpression) } [system.object] VisitAttributedExpression([System.Management.Automation.Language.AttributedExpressionAst] $attributedExpressionAst) { $newAttribute = $this.VisitElement($attributedExpressionAst.Attribute) $newChild = $this.VisitElement($attributedExpressionAst.Child) return [System.Management.Automation.Language.AttributedExpressionAst]::new($attributedExpressionAst.Extent, $newAttribute, $newChild) } [system.object] VisitBlockStatement([System.Management.Automation.Language.BlockStatementAst] $blockStatementAst) { $newBody = $this.VisitElement($blockStatementAst.Body) return [System.Management.Automation.Language.BlockStatementAst]::new($blockStatementAst.Extent, $blockStatementAst.Kind, $newBody) } } #endregion #region Measure-Script Function Measure-Script { <# .SYNOPSIS Measures the execution time of each of the statements of a script or scriptblock .DESCRIPTION This is an re-implementation in pure PowerShell of the good old Measure-Script cmddlet found in SDK samples. See: https://code.msdn.microsoft.com/Script-Line-Profiler-Sample-80380291 .PARAMETER ScriptBlock The ScriptBlock to be measured. .PARAMETER Path The Path to a script to be measured. .PARAMETER ExecutionResultVariable The name of a variable where the result of the execution will be stored. .PARAMETER VariableScope The variable scope for the ExecutionResultVariable. Default is 1, i.e. one level above the script execution inside this function. .PARAMETER Arguments Arguments passed to the ScriptBlock or Script. .EXAMPLE Measure-Script -ScriptBlock { Get-Service | ForEach-Object { $_.name + " is " + $_.Status } } This measures the script block and returns the times executed for each line in the script block. LineNo ExecutionTime Line ------ ------------- ---- 1 00:00:00 2 00:00:00.0411606 Get-Service | ForEach-Object { 3 00:00:00.0170710 $_.name + " is " + $_.Status 4 00:00:00 } 5 00:00:00 .EXAMPLE Measure-Scipt -Path c:\PS\GenerateUsername.ps1 -Arguments @{GivenName = "Joe";Surname = "Smith"} This will execute and measure the c:\PS\GenerateUsername.ps1 script with the -GivenName and -Surname parameters. #> [cmdletbinding(DefaultParameterSetName="ScriptBlock")] param( [parameter(Mandatory=$true,ParameterSetName="ScriptBlock")] [scriptblock]$ScriptBlock, [parameter(Mandatory=$true,ParameterSetName="Path")] [string]$Path, [parameter(Mandatory=$false,ParameterSetName="__AllParametersets")] [string]$ExecutionResultVariable, [parameter(Mandatory=$false,ParameterSetName="__AllParametersets")] [hashtable]$Arguments, [parameter(Mandatory=$false,ParameterSetName="__AllParametersets")] [string]$VariableScope="1" ) if($PSBoundParameters.Keys -icontains "Path") { if(-not (Test-Path $path)) { throw "No such file" } $ScriptText = Get-Content $path -Raw $ScriptBlock = [scriptblock]::Create($ScriptText) } $ScriptBlock = [scriptblock]::Create($ScriptBlock.ToString()) $profiler = [Profiler]::new($ScriptBlock.Ast.Extent) $visitor = [AstVisitor]::new($profiler) $newAst = $ScriptBlock.Ast.Visit($visitor) $executionResult = . $newAst.GetScriptBlock() @Arguments [string[]]$lines = $ScriptBlock.ToString().Split("`n").TrimEnd() for($i = 0; $i -lt $lines.Count;$i++){ [pscustomobject]@{ LineNo = $i+1 ExecutionTime = $profiler.StopWatches[$i].Elapsed Line = $lines[$i] } } if($ExecutionResultVariable) { Set-Variable -Name $ExecutionResultVariable -Value $executionResult -Scope $VariableScope } }
PowerShellCorpus/PowerShellGallery/SCOrchDev-PasswordVault/2.1.1/SCOrchDev-PasswordVault.tests.ps1
SCOrchDev-PasswordVault.tests.ps1
$here = Split-Path -Parent $MyInvocation.MyCommand.Path $manifestPath = "$here\SCOrchDev-PasswordVault.psd1" Import-Module SCOrchDev-PasswordVault -Force Describe -Tags 'VersionChecks' 'SCOrchDev-PasswordVault manifest' { $script:manifest = $null It 'has a valid manifest' { { $script:manifest = Test-ModuleManifest -Path $manifestPath -ErrorAction Stop -WarningAction SilentlyContinue } | Should Not Throw } It 'has a valid name in the manifest' { $script:manifest.Name | Should Be SCOrchDev-PasswordVault } It 'has a valid guid in the manifest' { $script:manifest.Guid | Should Be '1ef339ab-57b3-4ea9-bedb-af2780f0e995' } It 'has a valid version in the manifest' { $script:manifest.Version -as [Version] | Should Not BeNullOrEmpty } if (Get-Command git.exe -ErrorAction SilentlyContinue) { $script:tagVersion = $null It 'is tagged with a valid version' { $cwd = get-location Set-Location ($Path -as [System.IO.FileInfo]).Directory $thisCommit = git.exe log --decorate --oneline HEAD~1..HEAD Set-Location $cwd if ($thisCommit -match 'tag:\s*(\d+(?:\.\d+)*)') { $script:tagVersion = $matches[1] } $script:tagVersion | Should Not BeNullOrEmpty $script:tagVersion -as [Version] | Should Not BeNullOrEmpty } It 'all versions are the same' { $script:manifest.Version -as [Version] | Should be ( $script:tagVersion -as [Version] ) } } It 'should have all files listed in the FileList' { $ModuleFiles = (Get-ChildItem -Path $here -Recurse -Exclude .git).FullName $FileDifferences = Compare-Object -ReferenceObject $ModuleFiles -DifferenceObject $script:manifest.FileList if (($FileDifferences -as [array]).Count -gt 0) { Throw-Exception -Type 'MissingFiles' ` -Message 'Files missing or not tracked in FileList' ` -Property @{ 'Missing Files' = ($FileDifferences | Where-Object {$_.SideIndicator -eq '=>'}).InputObject ; 'Non Tracked Files' = ($FileDifferences | Where-Object {$_.SideIndicator -eq '<='}).InputObject ; } } } } if ($PSVersionTable.PSVersion.Major -ge 3) { $error.Clear() Describe 'Clean treatment of the $error variable' { It 'Performs a successful test' { $true | Should Be $true } It 'Did not add anything to the $error variable' { $error.Count | Should Be 0 } } } Describe 'Style rules' { $SCOrchDevUtilityRoot = (Get-Module SCOrchDev-PasswordVault).ModuleBase $files = @( Get-ChildItem $SCOrchDevUtilityRoot -Include *.ps1,*.psm1 ) It 'Module source files contain no trailing whitespace' { $badLines = @( foreach ($file in $files) { $lines = [System.IO.File]::ReadAllLines($file.FullName) $lineCount = $lines.Count for ($i = 0; $i -lt $lineCount; $i++) { if ($lines[$i] -match '\s+$') { 'File: {0}, Line: {1}' -f $file.FullName, ($i + 1) } } } ) if ($badLines.Count -gt 0) { throw "The following $($badLines.Count) lines contain trailing whitespace: `r`n`r`n$($badLines -join "`r`n")" } } It 'Module Source Files all end with a newline' { $badFiles = @( foreach ($file in $files) { $string = [System.IO.File]::ReadAllText($file.FullName) if ($string.Length -gt 0 -and $string[-1] -ne "`n") { $file.FullName } } ) if ($badFiles.Count -gt 0) { throw "The following files do not end with a newline: `r`n`r`n$($badFiles -join "`r`n")" } } } Describe 'Storing Credentials' { $Credential = New-Object -TypeName pscredential 'testcred\cred', ('qwerty' | ConvertTo-SecureString -AsPlainText -Force) Context 'Resource Specified' { $Resource = [guid]::NewGuid() -as [string] It 'Should store a pscredential object' { Set-PasswordVaultCredential -Credential $Credential -Resource $Resource } It 'Should be able to retrieve a credential' { $TestCredential = Get-PasswordVaultCredential -UserName $Credential.UserName -AsPSCredential -Resource $Resource $TestCredential.UserName | Should Be $Credential.UserName $TestCredential.GetNetworkCredential().Password | Should Be $Credential.GetNetworkCredential().Password } It 'Should be able to remove a credential' { Remove-PasswordVaultCredential -UserName $Credential.UserName -Resource $Resource { Get-PasswordVaultCredential -UserName $Credential.UserName -Resource $Resource } | Should Throw } } }
PowerShellCorpus/PowerShellGallery/AzureRM.Network/3.7.0/AzureRmProfileStartup.ps1
AzureRmProfileStartup.ps1
# ---------------------------------------------------------------------------------- # # Copyright Microsoft Corporation # Licensed under the Apache License, Version 2.0 (the "License"); # you may not use this file except in compliance with the License. # You may obtain a copy of the License at # http://www.apache.org/licenses/LICENSE-2.0 # Unless required by applicable law or agreed to in writing, software # distributed under the License is distributed on an "AS IS" BASIS, # WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. # See the License for the specific language governing permissions and # limitations under the License. # ---------------------------------------------------------------------------------- @{ "Login-AzureRmAccount" = "Add-AzureRmAccount"; "Select-AzureRmSubscription" = "Set-AzureRmContext"; "Save-AzureRmProfile" = "Save-AzureRmContext"; "Select-AzureRmProfile" = "Import-AzureRmContext"; }.GetEnumerator() | Select @{Name='Name'; Expression={$_.Key}}, @{Name='Value'; Expression={$_.Value}} | New-Alias -Description "AzureAlias" # SIG # Begin signature block # MIIkGwYJKoZIhvcNAQcCoIIkDDCCJAgCAQExDzANBglghkgBZQMEAgEFADB5Bgor # BgEEAYI3AgEEoGswaTA0BgorBgEEAYI3AgEeMCYCAwEAAAQQH8w7YFlLCE63JNLG # KX7zUQIBAAIBAAIBAAIBAAIBADAxMA0GCWCGSAFlAwQCAQUABCDApggZz05Qnk0e # yiuUwG/hQa3nA5NWg0bjPekKbmwN+aCCDZMwggYRMIID+aADAgECAhMzAAAAjoeR # pFcaX8o+AAAAAAC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AOBgNVBAcTB1JlZG1vbmQxHjAcBgNVBAoTFU1pY3Jvc29mdCBDb3Jw # b3JhdGlvbjEmMCQGA1UEAxMdTWljcm9zb2Z0IFRpbWUtU3RhbXAgUENBIDIwMTAC # EzMAAACwhumSIApd6vgAAAAAALAwFgQUD7U+b5faW5HStgG8yNl+b44Ea54wDQYJ # KoZIhvcNAQELBQAEggEARJ4m6ab6DZYaKMcMwYoa9f4pYbzs4ZvrnLm7ARHii84w # ndYJt75ZyCn6jpZqYUvbYByEfFWc8kaNVuAJnhYHyu7TWea3cDTcQZGoan1vZCyh # L/OCwFmdjcJmjbiMmrpFFqn66xSB0Q5pJaXzf1J/UrKjc+TP8DXmAC3aaaROTyZl # Bjr6LKzrCEgk22WsJjVD+agcJdbG0Do7CXdplhPyUmux6rDCYP7JRYpHbgrgMCak # DLUXy3vnvmlnAjDl93wzNN9FoUOW+3M6zhGi6PVLkAqyAmovGC5f6lFAqQ8zZ7PM # FOQucUgc19NQwW9i1IAvQGg4ojzK1EGHJe/bOukncQ== # SIG # End signature block
PowerShellCorpus/PowerShellGallery/AzureRM.Network/3.7.0/AzureRmNetworkStartup.ps1
AzureRmNetworkStartup.ps1
# ---------------------------------------------------------------------------------- # # Copyright Microsoft Corporation # Licensed under the Apache License, Version 2.0 (the "License"); # you may not use this file except in compliance with the License. # You may obtain a copy of the License at # http://www.apache.org/licenses/LICENSE-2.0 # Unless required by applicable law or agreed to in writing, software # distributed under the License is distributed on an "AS IS" BASIS, # WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. # See the License for the specific language governing permissions and # limitations under the License. # ---------------------------------------------------------------------------------- @{ "List-AzureRmApplicationGatewayAvailableWafRuleSets" = "Get-AzureRmApplicationGatewayAvailableWafRuleSets"; }.GetEnumerator() | Select @{Name='Name'; Expression={$_.Key}}, @{Name='Value'; Expression={$_.Value}} | New-Alias -Description "AzureAlias" # SIG # Begin signature block # MIIkGwYJKoZIhvcNAQcCoIIkDDCCJAgCAQExD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nzANBglghkgBZQMEAgEFAKCCATIwGgYJKoZIhvcNAQkDMQ0GCyqGSIb3 # DQEJEAEEMC8GCSqGSIb3DQEJBDEiBCAlS+pSrlmvDaOPulWALrUvCEJaumnNeYd3 # sHqpM0G3BjCB4gYLKoZIhvcNAQkQAgwxgdIwgc8wgcwwgbEEFGzTJwjy+dmoy/kZ # 3pJLSq3bGaPBMIGYMIGApH4wfDELMAkGA1UEBhMCVVMxEzARBgNVBAgTCldhc2hp # bmd0b24xEDAOBgNVBAcTB1JlZG1vbmQxHjAcBgNVBAoTFU1pY3Jvc29mdCBDb3Jw # b3JhdGlvbjEmMCQGA1UEAxMdTWljcm9zb2Z0IFRpbWUtU3RhbXAgUENBIDIwMTAC # EzMAAACfZ/K1qCMGW3sAAAAAAJ8wFgQU4M1Fd2JpzLcNV/kNn2hq8kEZOaQwDQYJ # KoZIhvcNAQELBQAEggEABzVAzt7+3eNUzry89L6XhpkyxRfHsC6aBXh3RlGZGweQ # o0YxfnA69Pu9iXV8lQOepMFPTrG8AcyJmOur9Pxv9iKbJORY08pCl/pebr9pCzDC # 4NNrvdjNOlF+Fn2+RoWLTnek6dfXHbUUm9QoKqaPkyfBg1tN7ez7eKOkJ4XnynX0 # OONLehI0+gEv2C4zOLeB3+ta6Hi72nKtdqX6QPuCvlnwt2+HEDTH9jgZx3RB2Tx0 # 8FpWoZdfqXwABrjnZCklk3aAQKnIlZC5dv0iv1fh18J6nxocL9ekXcTbW6KMMHft # v1mY+ZH3/bLNFQq1dQ3mWuSlFoVvsj1SgKQMLTgFpA== # SIG # End signature block
PowerShellCorpus/PowerShellGallery/AzureRM.Network/3.7.0/ResourceManagerStartup.ps1
ResourceManagerStartup.ps1
# ---------------------------------------------------------------------------------- # # Copyright Microsoft Corporation # Licensed under the Apache License, Version 2.0 (the "License"); # you may not use this file except in compliance with the License. # You may obtain a copy of the License at # http://www.apache.org/licenses/LICENSE-2.0 # Unless required by applicable law or agreed to in writing, software # distributed under the License is distributed on an "AS IS" BASIS, # WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. # See the License for the specific language governing permissions and # limitations under the License. # ---------------------------------------------------------------------------------- # Authorization script commandlet that builds on top of existing Insights comandlets. # This commandlet gets all events for the "Microsoft.Authorization" resource provider by calling the "Get-AzureRmResourceProviderLog" commandlet function Get-AzureRmAuthorizationChangeLog { <# .SYNOPSIS Gets access change history for the selected subscription for the specified time range i.e. role assignments that were added or removed, including classic administrators (co-administrators and service administrators). Maximum duration that can be queried is 15 days (going back up to past 90 days). .DESCRIPTION The Get-AzureRmAuthorizationChangeLog produces a report of who granted (or revoked) what role to whom at what scope within the subscription for the specified time range. The command queries all role assignment events from the Insights resource provider of Azure Resource Manager. Specifying the time range is optional. If both StartTime and EndTime parameters are not specified, the default query interval is the past 1 hour. Maximum duration that can be queried is 15 days (going back up to past 90 days). .PARAMETER StartTime Start time of the query. Optional. .PARAMETER EndTime End time of the query. Optional .EXAMPLE Get-AzureRmAuthorizationChangeLog Gets the access change logs for the past hour. .EXAMPLE Get-AzureRmAuthorizationChangeLog -StartTime "09/20/2015 15:00" -EndTime "09/24/2015 15:00" Gets all access change logs between the specified dates Timestamp : 2015-09-23 21:52:41Z Caller : admin@rbacCliTest.onmicrosoft.com Action : Revoked PrincipalId : 54401967-8c4e-474a-9fbb-a42073f1783c PrincipalName : testUser PrincipalType : User Scope : /subscriptions/9004a9fd-d58e-48dc-aeb2-4a4aec58606f/resourceGroups/TestRG/providers/Microsoft.Network/virtualNetworks/testresource ScopeName : testresource ScopeType : Resource RoleDefinitionId : /subscriptions/9004a9fd-d58e-48dc-aeb2-4a4aec58606f/providers/Microsoft.Authorization/roleDefinitions/b24988ac-6180-42a0-ab88-20f7382dd24c RoleName : Contributor .EXAMPLE Get-AzureRmAuthorizationChangeLog -StartTime ([DateTime]::Now - [TimeSpan]::FromDays(5)) -EndTime ([DateTime]::Now) | FT Caller, Action, RoleName, PrincipalName, ScopeType Gets access change logs for the past 5 days and format the output Caller Action RoleName PrincipalName ScopeType ------ ------ -------- ------------- --------- admin@contoso.com Revoked Contributor User1 Subscription admin@contoso.com Granted Reader User1 Resource Group admin@contoso.com Revoked Contributor Group1 Resource .LINK New-AzureRmRoleAssignment .LINK Get-AzureRmRoleAssignment .LINK Remove-AzureRmRoleAssignment #> [CmdletBinding()] param( [parameter(Mandatory=$false, ValueFromPipelineByPropertyName=$true, HelpMessage = "The start time. Optional If both StartTime and EndTime are not provided, defaults to querying for the past 1 hour. Maximum allowed difference in StartTime and EndTime is 15 days")] [DateTime] $StartTime, [parameter(Mandatory=$false, ValueFromPipelineByPropertyName=$true, HelpMessage = "The end time. Optional. If both StartTime and EndTime are not provided, defaults to querying for the past 1 hour. Maximum allowed difference in StartTime and EndTime is 15 days")] [DateTime] $EndTime ) PROCESS { # Get all events for the "Microsoft.Authorization" provider by calling the Insights commandlet $events = Get-AzureRmLog -ResourceProvider "Microsoft.Authorization" -DetailedOutput -StartTime $StartTime -EndTime $EndTime $startEvents = @{} $endEvents = @{} $offlineEvents = @() # StartEvents and EndEvents will contain matching pairs of logs for when role assignments (and definitions) were created or deleted. # i.e. A PUT on roleassignments will have a Start-End event combination and a DELETE on roleassignments will have another Start-End event combination $startEvents = $events | ? { $_.httpRequest -and $_.Status -ieq "Started" } $events | ? { $_.httpRequest -and $_.Status -ne "Started" } | % { $endEvents[$_.OperationId] = $_ } # This filters non-RBAC events like classic administrator write or delete $events | ? { $_.httpRequest -eq $null } | % { $offlineEvents += $_ } $output = @() # Get all role definitions once from the service and cache to use for all 'startevents' $azureRoleDefinitionCache = @{} Get-AzureRmRoleDefinition | % { $azureRoleDefinitionCache[$_.Id] = $_ } $principalDetailsCache = @{} # Process StartEvents # Find matching EndEvents that succeeded and relating to role assignments only $startEvents | ? { $endEvents.ContainsKey($_.OperationId) ` -and $endEvents[$_.OperationId] -ne $null ` -and $endevents[$_.OperationId].OperationName.StartsWith("Microsoft.Authorization/roleAssignments", [System.StringComparison]::OrdinalIgnoreCase) ` -and $endEvents[$_.OperationId].Status -ieq "Succeeded"} | % { $endEvent = $endEvents[$_.OperationId]; # Create the output structure $out = "" | select Timestamp, Caller, Action, PrincipalId, PrincipalName, PrincipalType, Scope, ScopeName, ScopeType, RoleDefinitionId, RoleName $out.Timestamp = Get-Date -Date $endEvent.EventTimestamp -Format u $out.Caller = $_.Caller if ($_.HttpRequest.Method -ieq "PUT") { $out.Action = "Granted" if ($_.Properties.Content.ContainsKey("requestbody")) { $messageBody = ConvertFrom-Json $_.Properties.Content["requestbody"] } $out.Scope = $_.Authorization.Scope } elseif ($_.HttpRequest.Method -ieq "DELETE") { $out.Action = "Revoked" if ($endEvent.Properties.Content.ContainsKey("responseBody")) { $messageBody = ConvertFrom-Json $endEvent.Properties.Content["responseBody"] } } if ($messageBody) { # Process principal details $out.PrincipalId = $messageBody.properties.principalId if ($out.PrincipalId -ne $null) { # Get principal details by querying Graph. Cache principal details and read from cache if present $principalId = $out.PrincipalId if($principalDetailsCache.ContainsKey($principalId)) { # Found in cache $principalDetails = $principalDetailsCache[$principalId] } else { # not in cache $principalDetails = "" | select Name, Type $user = Get-AzureRmADUser -ObjectId $principalId if ($user) { $principalDetails.Name = $user.DisplayName $principalDetails.Type = "User" } else { $group = Get-AzureRmADGroup -ObjectId $principalId if ($group) { $principalDetails.Name = $group.DisplayName $principalDetails.Type = "Group" } else { $servicePrincipal = Get-AzureRmADServicePrincipal -objectId $principalId if ($servicePrincipal) { $principalDetails.Name = $servicePrincipal.DisplayName $principalDetails.Type = "Service Principal" } } } # add principal details to cache $principalDetailsCache.Add($principalId, $principalDetails); } $out.PrincipalName = $principalDetails.Name $out.PrincipalType = $principalDetails.Type } # Process scope details if ([string]::IsNullOrEmpty($out.Scope)) { $out.Scope = $messageBody.properties.Scope } if ($out.Scope -ne $null) { # Remove the authorization provider details from the scope, if present if ($out.Scope.ToLower().Contains("/providers/microsoft.authorization")) { $index = $out.Scope.ToLower().IndexOf("/providers/microsoft.authorization") $out.Scope = $out.Scope.Substring(0, $index) } $scope = $out.Scope $resourceDetails = "" | select Name, Type $scopeParts = $scope.Split('/', [System.StringSplitOptions]::RemoveEmptyEntries) $len = $scopeParts.Length if ($len -gt 0 -and $len -le 2 -and $scope.ToLower().Contains("subscriptions")) { $resourceDetails.Type = "Subscription" $resourceDetails.Name = $scopeParts[1] } elseif ($len -gt 0 -and $len -le 4 -and $scope.ToLower().Contains("resourcegroups")) { $resourceDetails.Type = "Resource Group" $resourceDetails.Name = $scopeParts[3] } elseif ($len -ge 6 -and $scope.ToLower().Contains("providers")) { $resourceDetails.Type = "Resource" $resourceDetails.Name = $scopeParts[$len -1] } $out.ScopeName = $resourceDetails.Name $out.ScopeType = $resourceDetails.Type } # Process Role definition details $out.RoleDefinitionId = $messageBody.properties.roleDefinitionId if ($out.RoleDefinitionId -ne $null) { #Extract roleDefinitionId Guid value from the fully qualified id string. $roleDefinitionIdGuid= $out.RoleDefinitionId.Substring($out.RoleDefinitionId.LastIndexOf("/")+1) if ($azureRoleDefinitionCache[$roleDefinitionIdGuid]) { $out.RoleName = $azureRoleDefinitionCache[$roleDefinitionIdGuid].Name } else { $out.RoleName = "" } } } $output += $out } # start event processing complete # Filter classic admins events $offlineEvents | % { if($_.Status -ne $null -and $_.Status -ieq "Succeeded" -and $_.OperationName -ne $null -and $_.operationName.StartsWith("Microsoft.Authorization/ClassicAdministrators", [System.StringComparison]::OrdinalIgnoreCase)) { $out = "" | select Timestamp, Caller, Action, PrincipalId, PrincipalName, PrincipalType, Scope, ScopeName, ScopeType, RoleDefinitionId, RoleName $out.Timestamp = Get-Date -Date $_.EventTimestamp -Format u $out.Caller = "Subscription Admin" if($_.operationName -ieq "Microsoft.Authorization/ClassicAdministrators/write"){ $out.Action = "Granted" } elseif($_.operationName -ieq "Microsoft.Authorization/ClassicAdministrators/delete"){ $out.Action = "Revoked" } $out.RoleDefinitionId = $null $out.PrincipalId = $null $out.PrincipalType = "User" $out.Scope = "/subscriptions/" + $_.SubscriptionId $out.ScopeType = "Subscription" $out.ScopeName = $_.SubscriptionId if($_.Properties -ne $null){ $out.PrincipalName = $_.Properties.Content["adminEmail"] $out.RoleName = "Classic " + $_.Properties.Content["adminType"] } $output += $out } } # end offline events $output | Sort Timestamp } } # End commandlet # SIG # Begin signature block # MIIkGwYJKoZIhvcNAQcCoIIkDDCCJAgCAQExDzANBglghkgBZQMEAgEFADB5Bgor # BgEEAYI3AgEEoGswaTA0BgorBgEEAYI3AgEeMCYCAwEAAAQQH8w7YFlLCE63JNLG # KX7zUQIBAAIBAAIBAAIBAAIBADAxMA0GCWCGSAFlAwQCAQUABCD1aIG6oFrw5Hw0 # KihOeY9wUbQ9YuZoQAqgPB6b76kKyqCCDZMwggYRMIID+aADAgECAhMzAAAAjoeR # pFcaX8o+AAAAAACOMA0GCSqGSIb3DQEBCwUAMH4xCzAJBgNVBAYTAlVTMRMwEQYD # VQQIEwpXYXNoaW5ndG9uMRAwDgYDVQQHEwdSZWRtb25kMR4wHAYDVQQKExVNaWNy # b3NvZnQgQ29ycG9yYXRpb24xKDAmBgNVBAMTH01pY3Jvc29mdCBDb2RlIFNpZ25p # bmcgUENBIDIwMTEwHhcNMTYxMTE3MjIwOTIxWhcNMTgwMjE3MjIwOTIxWjCBgzEL # MAkGA1UEBhMCVVMxEzARBgNVBAgTCldhc2hpbmd0b24xEDAOBgNVBAcTB1JlZG1v # bmQxHjAcBgNVBAoTFU1pY3Jvc29mdCBDb3Jwb3JhdGlvbjENMAsGA1UECxMETU9Q # UjEeMBwGA1UEAxMVTWljcm9zb2Z0IENvcnBvcmF0aW9uMIIBIjANBgkqhkiG9w0B # AQEFAAOCAQ8AMIIBCgKCAQEA0IfUQit+ndnGetSiw+MVktJTnZUXyVI2+lS/qxCv # 6cnnzCZTw8Jzv23WAOUA3OlqZzQw9hYXtAGllXyLuaQs5os7efYjDHmP81LfQAEc # wsYDnetZz3Pp2HE5m/DOJVkt0slbCu9+1jIOXXQSBOyeBFOmawJn+E1Zi3fgKyHg # 78CkRRLPA3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Gallery/AzureRM.Network/4.1.0/AzureRmProfileStartup.ps1
AzureRmProfileStartup.ps1
# ---------------------------------------------------------------------------------- # # Copyright Microsoft Corporation # Licensed under the Apache License, Version 2.0 (the "License"); # you may not use this file except in compliance with the License. # You may obtain a copy of the License at # http://www.apache.org/licenses/LICENSE-2.0 # Unless required by applicable law or agreed to in writing, software # distributed under the License is distributed on an "AS IS" BASIS, # WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. # See the License for the specific language governing permissions and # limitations under the License. # ---------------------------------------------------------------------------------- @{ "Login-AzureRmAccount" = "Add-AzureRmAccount"; "Select-AzureRmSubscription" = "Set-AzureRmContext"; "Save-AzureRmProfile" = "Save-AzureRmContext"; "Select-AzureRmProfile" = "Import-AzureRmContext"; "Resolve-Error" = "Resolve-AzureRmError"; }.GetEnumerator() | Select @{Name='Name'; Expression={$_.Key}}, @{Name='Value'; Expression={$_.Value}} | New-Alias -Description "AzureAlias" # SIG # Begin signature block # MIIkHgYJKoZIhvcNAQcCoIIkDzCCJAsCAQExDzANBglghkgBZQMEAgEFADB5Bgor # BgEEAYI3AgEEoGswaTA0BgorBgEEAYI3AgEeMCYCAwEAAAQQH8w7YFlLCE63JNLG # KX7zUQIBAAIBAAIBAAIBAAIBADAxMA0GCWCGSAFlAwQCAQUABCALJXjrzh47rcfU # 4UfdAQzeL9cnx2R84p1DABBXUFZ2oKCCDZMwggYRMIID+aADAgECAhMzAAAAjoeR # pFcaX8o+AAAAAACOMA0GCSqGSIb3DQEBCwUAMH4xCzAJBgNVBAYTAlVTMRMwEQYD # VQQIEwpXYXNoaW5ndG9uMRAwDgYDVQQHEwdSZWRtb25kMR4wHAYDVQQKExVNaWNy # b3NvZnQgQ29ycG9yYXRpb24xKDAmBgNVBAMTH01pY3Jvc29mdCBDb2RlIFNpZ25p # bmcgUENBIDIwMTEwHhcNMTYxMTE3MjIwOTIxWhcNMTgwMjE3MjIwOTIxWjCBgzEL # MAkGA1UEBhMCVVMxEzARBgNV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sE3CeuQwpxZwoR8mwYCM9qkfTW8N25URbpreM8ldZ18/yZNNnyOh5A # /f00GRYiUW1S2N0YADFLKNhp9V6YJIIF2s3hQjljFmJtMK3w1/Ne2f6ufI7mfbhr # AF2sXgJtapilcuggKg10C6jQmXiWCDro1D5Jre+cqOHMo8gJ6FzVFgIernx4ONbw # 6++tIsFw1gUuOo8EKv6scAljqilimDV0wgaGyC4F9mAfXDQ/vfjtiMk4mXSdBF6m # mnSjVnUGXwGmu5PFgzVHTzOK/leoHQyotelFFSRLs/qZ7g== # SIG # End signature block
PowerShellCorpus/PowerShellGallery/AzureRM.Network/4.1.0/AzureRmNetworkStartup.ps1
AzureRmNetworkStartup.ps1
# ---------------------------------------------------------------------------------- # # Copyright Microsoft Corporation # Licensed under the Apache License, Version 2.0 (the "License"); # you may not use this file except in compliance with the License. # You may obtain a copy of the License at # http://www.apache.org/licenses/LICENSE-2.0 # Unless required by applicable law or agreed to in writing, software # distributed under the License is distributed on an "AS IS" BASIS, # WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. # See the License for the specific language governing permissions and # limitations under the License. # ---------------------------------------------------------------------------------- @{ "List-AzureRmApplicationGatewayAvailableWafRuleSets" = "Get-AzureRmApplicationGatewayAvailableWafRuleSets"; }.GetEnumerator() | Select @{Name='Name'; Expression={$_.Key}}, @{Name='Value'; Expression={$_.Value}} | New-Alias -Description "AzureAlias" # SIG # Begin signature block # MIIkHgYJKoZIhvcNAQcCoIIkDzCCJAsCAQExDzANBglghkgBZQMEAgEFADB5Bgor # BgEEAYI3AgEEoGswaTA0BgorBgEEAYI3AgEeMCYCAwEAAAQQH8w7YFlLCE63JNLG # KX7zUQIBAAIBAAIBAAIBAAIBADAxMA0GCWCGSAFlAwQCAQUABCAE8guz/TPbymvn # WAp8ElwkVmvcZEOLitNC15Ze5K1j9qCCDZMwggYRMIID+aADAgECAhMzAAAAjoeR # pFcaX8o+AAAAAACOMA0GCSqGSIb3DQEBCwUAMH4xCzAJBg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AoTFU1pY3Jvc29mdCBD # b3Jwb3JhdGlvbjEmMCQGA1UEAxMdTWljcm9zb2Z0IFRpbWUtU3RhbXAgUENBIDIw # MTACEzMAAACj7x8iIIFj3KUAAAAAAKMwFgQUgJEFJ8IJojCcjlFGA6WuaXiOtzcw # DQYJKoZIhvcNAQELBQAEggEAk038EaaEN9bMZ87hGshZoA8zrS+TW8Ra9qbrs8xR # bDj88OnLki+96+XbTVPf2wH5TtkCMg7BCdP/Hd8iJTJm/ipkJdhXXMRsb9gjhkwu # EkQks+CxQRJjTXN8hRZQKDmSTEFQs34C33bcTA6P1a3EAjMMxsYbtOgI0GUxSRlf # GUOqtID5gmxh0NKKFqWtMgYZsBKi1IB5oLqvQzJlwUODE1gNTJeZHy7oVfRO/wnA # 6b8dDabAOmceLJg1xiCcArL76ODR/DoCMykMgU02sRREkHVU4k7osEmhtMkSO00f # U1UMc3ugOpz/Nd8Rrn4uOSrnqvHkMk6kyjFz4NqZKfog+Q== # SIG # End signature block
PowerShellCorpus/PowerShellGallery/AzureRM.Network/4.1.0/ResourceManagerStartup.ps1
ResourceManagerStartup.ps1
# ---------------------------------------------------------------------------------- # # Copyright Microsoft Corporation # Licensed under the Apache License, Version 2.0 (the "License"); # you may not use this file except in compliance with the License. # You may obtain a copy of the License at # http://www.apache.org/licenses/LICENSE-2.0 # Unless required by applicable law or agreed to in writing, software # distributed under the License is distributed on an "AS IS" BASIS, # WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. # See the License for the specific language governing permissions and # limitations under the License. # ---------------------------------------------------------------------------------- # Authorization script commandlet that builds on top of existing Insights comandlets. # This commandlet gets all events for the "Microsoft.Authorization" resource provider by calling the "Get-AzureRmResourceProviderLog" commandlet function Get-AzureRmAuthorizationChangeLog { <# .SYNOPSIS Gets access change history for the selected subscription for the specified time range i.e. role assignments that were added or removed, including classic administrators (co-administrators and service administrators). Maximum duration that can be queried is 15 days (going back up to past 90 days). .DESCRIPTION The Get-AzureRmAuthorizationChangeLog produces a report of who granted (or revoked) what role to whom at what scope within the subscription for the specified time range. The command queries all role assignment events from the Insights resource provider of Azure Resource Manager. Specifying the time range is optional. If both StartTime and EndTime parameters are not specified, the default query interval is the past 1 hour. Maximum duration that can be queried is 15 days (going back up to past 90 days). .PARAMETER StartTime Start time of the query. Optional. .PARAMETER EndTime End time of the query. Optional .EXAMPLE Get-AzureRmAuthorizationChangeLog Gets the access change logs for the past hour. .EXAMPLE Get-AzureRmAuthorizationChangeLog -StartTime "09/20/2015 15:00" -EndTime "09/24/2015 15:00" Gets all access change logs between the specified dates Timestamp : 2015-09-23 21:52:41Z Caller : admin@rbacCliTest.onmicrosoft.com Action : Revoked PrincipalId : 54401967-8c4e-474a-9fbb-a42073f1783c PrincipalName : testUser PrincipalType : User Scope : /subscriptions/9004a9fd-d58e-48dc-aeb2-4a4aec58606f/resourceGroups/TestRG/providers/Microsoft.Network/virtualNetworks/testresource ScopeName : testresource ScopeType : Resource RoleDefinitionId : /subscriptions/9004a9fd-d58e-48dc-aeb2-4a4aec58606f/providers/Microsoft.Authorization/roleDefinitions/b24988ac-6180-42a0-ab88-20f7382dd24c RoleName : Contributor .EXAMPLE Get-AzureRmAuthorizationChangeLog -StartTime ([DateTime]::Now - [TimeSpan]::FromDays(5)) -EndTime ([DateTime]::Now) | FT Caller, Action, RoleName, PrincipalName, ScopeType Gets access change logs for the past 5 days and format the output Caller Action RoleName PrincipalName ScopeType ------ ------ -------- ------------- --------- admin@contoso.com Revoked Contributor User1 Subscription admin@contoso.com Granted Reader User1 Resource Group admin@contoso.com Revoked Contributor Group1 Resource .LINK New-AzureRmRoleAssignment .LINK Get-AzureRmRoleAssignment .LINK Remove-AzureRmRoleAssignment #> [CmdletBinding()] param( [parameter(Mandatory=$false, ValueFromPipelineByPropertyName=$true, HelpMessage = "The start time. Optional If both StartTime and EndTime are not provided, defaults to querying for the past 1 hour. Maximum allowed difference in StartTime and EndTime is 15 days")] [DateTime] $StartTime, [parameter(Mandatory=$false, ValueFromPipelineByPropertyName=$true, HelpMessage = "The end time. Optional. If both StartTime and EndTime are not provided, defaults to querying for the past 1 hour. Maximum allowed difference in StartTime and EndTime is 15 days")] [DateTime] $EndTime ) PROCESS { # Get all events for the "Microsoft.Authorization" provider by calling the Insights commandlet $events = Get-AzureRmLog -ResourceProvider "Microsoft.Authorization" -DetailedOutput -StartTime $StartTime -EndTime $EndTime $startEvents = @{} $endEvents = @{} $offlineEvents = @() # StartEvents and EndEvents will contain matching pairs of logs for when role assignments (and definitions) were created or deleted. # i.e. A PUT on roleassignments will have a Start-End event combination and a DELETE on roleassignments will have another Start-End event combination $startEvents = $events | ? { $_.httpRequest -and $_.Status -ieq "Started" } $events | ? { $_.httpRequest -and $_.Status -ne "Started" } | % { $endEvents[$_.OperationId] = $_ } # This filters non-RBAC events like classic administrator write or delete $events | ? { $_.httpRequest -eq $null } | % { $offlineEvents += $_ } $output = @() # Get all role definitions once from the service and cache to use for all 'startevents' $azureRoleDefinitionCache = @{} Get-AzureRmRoleDefinition | % { $azureRoleDefinitionCache[$_.Id] = $_ } $principalDetailsCache = @{} # Process StartEvents # Find matching EndEvents that succeeded and relating to role assignments only $startEvents | ? { $endEvents.ContainsKey($_.OperationId) ` -and $endEvents[$_.OperationId] -ne $null ` -and $endevents[$_.OperationId].OperationName.StartsWith("Microsoft.Authorization/roleAssignments", [System.StringComparison]::OrdinalIgnoreCase) ` -and $endEvents[$_.OperationId].Status -ieq "Succeeded"} | % { $endEvent = $endEvents[$_.OperationId]; # Create the output structure $out = "" | select Timestamp, Caller, Action, PrincipalId, PrincipalName, PrincipalType, Scope, ScopeName, ScopeType, RoleDefinitionId, RoleName $out.Timestamp = Get-Date -Date $endEvent.EventTimestamp -Format u $out.Caller = $_.Caller if ($_.HttpRequest.Method -ieq "PUT") { $out.Action = "Granted" if ($_.Properties.Content.ContainsKey("requestbody")) { $messageBody = ConvertFrom-Json $_.Properties.Content["requestbody"] } $out.Scope = $_.Authorization.Scope } elseif ($_.HttpRequest.Method -ieq "DELETE") { $out.Action = "Revoked" if ($endEvent.Properties.Content.ContainsKey("responseBody")) { $messageBody = ConvertFrom-Json $endEvent.Properties.Content["responseBody"] } } if ($messageBody) { # Process principal details $out.PrincipalId = $messageBody.properties.principalId if ($out.PrincipalId -ne $null) { # Get principal details by querying Graph. Cache principal details and read from cache if present $principalId = $out.PrincipalId if($principalDetailsCache.ContainsKey($principalId)) { # Found in cache $principalDetails = $principalDetailsCache[$principalId] } else { # not in cache $principalDetails = "" | select Name, Type $user = Get-AzureRmADUser -ObjectId $principalId if ($user) { $principalDetails.Name = $user.DisplayName $principalDetails.Type = "User" } else { $group = Get-AzureRmADGroup -ObjectId $principalId if ($group) { $principalDetails.Name = $group.DisplayName $principalDetails.Type = "Group" } else { $servicePrincipal = Get-AzureRmADServicePrincipal -objectId $principalId if ($servicePrincipal) { $principalDetails.Name = $servicePrincipal.DisplayName $principalDetails.Type = "Service Principal" } } } # add principal details to cache $principalDetailsCache.Add($principalId, $principalDetails); } $out.PrincipalName = $principalDetails.Name $out.PrincipalType = $principalDetails.Type } # Process scope details if ([string]::IsNullOrEmpty($out.Scope)) { $out.Scope = $messageBody.properties.Scope } if ($out.Scope -ne $null) { # Remove the authorization provider details from the scope, if present if ($out.Scope.ToLower().Contains("/providers/microsoft.authorization")) { $index = $out.Scope.ToLower().IndexOf("/providers/microsoft.authorization") $out.Scope = $out.Scope.Substring(0, $index) } $scope = $out.Scope $resourceDetails = "" | select Name, Type $scopeParts = $scope.Split('/', [System.StringSplitOptions]::RemoveEmptyEntries) $len = $scopeParts.Length if ($len -gt 0 -and $len -le 2 -and $scope.ToLower().Contains("subscriptions")) { $resourceDetails.Type = "Subscription" $resourceDetails.Name = $scopeParts[1] } elseif ($len -gt 0 -and $len -le 4 -and $scope.ToLower().Contains("resourcegroups")) { $resourceDetails.Type = "Resource Group" $resourceDetails.Name = $scopeParts[3] } elseif ($len -ge 6 -and $scope.ToLower().Contains("providers")) { $resourceDetails.Type = "Resource" $resourceDetails.Name = $scopeParts[$len -1] } $out.ScopeName = $resourceDetails.Name $out.ScopeType = $resourceDetails.Type } # Process Role definition details $out.RoleDefinitionId = $messageBody.properties.roleDefinitionId if ($out.RoleDefinitionId -ne $null) { #Extract roleDefinitionId Guid value from the fully qualified id string. $roleDefinitionIdGuid= $out.RoleDefinitionId.Substring($out.RoleDefinitionId.LastIndexOf("/")+1) if ($azureRoleDefinitionCache[$roleDefinitionIdGuid]) { $out.RoleName = $azureRoleDefinitionCache[$roleDefinitionIdGuid].Name } else { $out.RoleName = "" } } } $output += $out } # start event processing complete # Filter classic admins events $offlineEvents | % { if($_.Status -ne $null -and $_.Status -ieq "Succeeded" -and $_.OperationName -ne $null -and $_.operationName.StartsWith("Microsoft.Authorization/ClassicAdministrators", [System.StringComparison]::OrdinalIgnoreCase)) { $out = "" | select Timestamp, Caller, Action, PrincipalId, PrincipalName, PrincipalType, Scope, ScopeName, ScopeType, RoleDefinitionId, RoleName $out.Timestamp = Get-Date -Date $_.EventTimestamp -Format u $out.Caller = "Subscription Admin" if($_.operationName -ieq "Microsoft.Authorization/ClassicAdministrators/write"){ $out.Action = "Granted" } elseif($_.operationName -ieq "Microsoft.Authorization/ClassicAdministrators/delete"){ $out.Action = "Revoked" } $out.RoleDefinitionId = $null $out.PrincipalId = $null $out.PrincipalType = "User" $out.Scope = "/subscriptions/" + $_.SubscriptionId $out.ScopeType = "Subscription" $out.ScopeName = $_.SubscriptionId if($_.Properties -ne $null){ $out.PrincipalName = $_.Properties.Content["adminEmail"] $out.RoleName = "Classic " + $_.Properties.Content["adminType"] } $output += $out } } # end offline events $output | Sort Timestamp } } # End commandlet # SIG # Begin signature block # MIIkHgYJKoZIhvcNAQcCoIIkDzCCJAsCAQExDzANBglghkgBZQMEAgEFADB5Bgor # BgEEAYI3AgEEoGswaTA0BgorBgEEAYI3AgEeMCYCAwEAAAQQH8w7YFlLCE63JNLG # KX7zUQIBAAIBAAIBAAIBAAIBADAxMA0GCWCGSAFlAwQ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gYLKoZIhvcNAQkQAgwxgdIwgc8wgcwwgbEEFDXko/tOP/8m # DXH1bV4Se5GWOKaNMIGYMIGApH4wfDELMAkGA1UEBhMCVVMxEzARBgNVBAgTCldh # c2hpbmd0b24xEDAOBgNVBAcTB1JlZG1vbmQxHjAcBgNVBAoTFU1pY3Jvc29mdCBD # b3Jwb3JhdGlvbjEmMCQGA1UEAxMdTWljcm9zb2Z0IFRpbWUtU3RhbXAgUENBIDIw # MTACEzMAAACj7x8iIIFj3KUAAAAAAKMwFgQUgJEFJ8IJojCcjlFGA6WuaXiOtzcw # DQYJKoZIhvcNAQELBQAEggEAnneLXZg2gSGpMBYdGAQCEdsNdE69j0kdDl2HI9Y4 # jQf1OcCXwsAth09mVtGFqnNC4fw7EKWkquRQZ/b6XegdRPJtEH5V9EqLXFLANRLK # KYM7CuxeBnJ0EYFpL+XJbEXwjJTKGE2KWY50Qqj8nLNqAqHskgEegJ36eaewe6FJ # Bsm9pxdAIim7nMajpKwS546CZ+18N8q81sR9Zi0PXWW01WCkSDoAeRRUk+YtCV3a # jaT5VFtOj/6XgGvwfhjIuj/iy1o7ubkK9q5R5SvfymmBe1wu3zbCbgcDDcok4qno # RCwyhuX1bj21wFv1TdiOW5oGE2CGoEL+dkBNowNO/Fhf9Q== # SIG # End signature block
PowerShellCorpus/PowerShellGallery/AzureRM.Network/3.4.0/AzureRmProfileStartup.ps1
AzureRmProfileStartup.ps1
# ---------------------------------------------------------------------------------- # # Copyright Microsoft Corporation # Licensed under the Apache License, Version 2.0 (the "License"); # you may not use this file except in compliance with the License. # You may obtain a copy of the License at # http://www.apache.org/licenses/LICENSE-2.0 # Unless required by applicable law or agreed to in writing, software # distributed under the License is distributed on an "AS IS" BASIS, # WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. # See the License for the specific language governing permissions and # limitations under the License. # ---------------------------------------------------------------------------------- @{ "Login-AzureRmAccount" = "Add-AzureRmAccount"; "Select-AzureRmSubscription" = "Set-AzureRmContext"; }.GetEnumerator() | Select @{Name='Name'; Expression={$_.Key}}, @{Name='Value'; Expression={$_.Value}} | New-Alias -Description "AzureAlias" # SIG # Begin signature block # MIIdpwYJKoZIhvcNAQcCoIIdmDCCHZQCAQExCzAJBgUrDgMCGgUAMGkGCisGAQQB # gjcCAQSgWzBZMDQGCisGAQQBgjcCAR4wJgIDAQAABBAfzDtgWUsITrck0sYpfvNR # AgEAAgEAAgEAAgEAAgEAMCEwCQYFKw4DAhoFAAQUrt58EopeEVPXRxPxV4sss2J/ # fdWgghhlMIIEwzCCA6ugAwIBAgITMwAAAMp9MhZ8fv0FAwAAAAAAyjANBgkqhkiG # 9w0BAQUFADB3MQswCQYDVQQGEwJVUzETMBEGA1UECBMKV2FzaGluZ3RvbjEQMA4G # A1UEBxMHUmVkbW9uZDEeMBwGA1UEChMVTWljcm9zb2Z0IENvcnBvcmF0aW9uMSEw # HwYDVQQDExhNaWNyb3NvZnQgVGltZS1TdGFtcCBQQ0EwHhcNMTYwOTA3MTc1ODU1 # WhcNMTgwOTA3MTc1ODU1WjCBszELMAkGA1UEBhMCVVMxEzARBgNVBAgTCldhc2hp # bmd0b24xEDAOBgNVBAcTB1JlZG1vbmQxHjAcBgNVBAoTFU1pY3Jvc29mdCBDb3Jw # b3JhdGlvbjENMAsGA1UECxMETU9QUjEnMCUGA1UECxMebkNpcGhlciBEU0UgRVNO # OjcyOEQtQzQ1Ri1GOUVCMSUwIwYDVQQDExxNaWNyb3NvZnQgVGltZS1TdGFtcCBT # ZXJ2aWNlMIIBIjANBgkqhkiG9w0BAQEFAAOCAQ8AMIIBCgKCAQEAj3CeDl2ll7S4 # 96ityzOt4bkPI1FucwjpTvklJZLOYljFyIGs/LLi6HyH+Czg8Xd/oDQYFzmJTWac # A0flGdvk8Yj5OLMEH4yPFFgQsZA5Wfnz/Cg5WYR2gmsFRUFELCyCbO58DvzOQQt1 # k/tsTJ5Ns5DfgCb5e31m95yiI44v23FVpKnTY9CUJbIr8j28O3biAhrvrVx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G9MNbJvfAh1tesohRCnH0b9zxD2s8vJs6twqKGCAigwggIkBgkqhkiG9w0B # CQYxggIVMIICEQIBATCBjjB3MQswCQYDVQQGEwJVUzETMBEGA1UECBMKV2FzaGlu # Z3RvbjEQMA4GA1UEBxMHUmVkbW9uZDEeMBwGA1UEChMVTWljcm9zb2Z0IENvcnBv # cmF0aW9uMSEwHwYDVQQDExhNaWNyb3NvZnQgVGltZS1TdGFtcCBQQ0ECEzMAAADK # fTIWfH79BQMAAAAAAMowCQYFKw4DAhoFAKBdMBgGCSqGSIb3DQEJAzELBgkqhkiG # 9w0BBwEwHAYJKoZIhvcNAQkFMQ8XDTE3MDExODAxNDkwMFowIwYJKoZIhvcNAQkE # MRYEFEbcE0uc55tgvpRM+zYLuDHxfBN1MA0GCSqGSIb3DQEBBQUABIIBACmLT97b # UBfUO/0NO+Nn5ImMkCc18BJIFv0Cd+bLtkhStrRPqouTQJR2t4AJFtHR21lD0C1y # yaJGc2uVZroPtaoUn0M++Gv4ETMelLVxV/zaPtuV1JZbY5hSTW+F6TxMx6eVt3co # NgzwdLMHttpFF7+EV6OnblX8o1OLfV9329rVEvLz/Ijy68SOiumOydcadyA4L+P8 # ZPj5MsE1dIdIfmJV7NJcFZusOX2RpEt/O9jyMV1Zx7TyCEBArqOQKtiN0OR/Hoo4 # /Jn1dFYbg5Gb7i0CRc0orXKkeJj60OuK5kOIp4wSFLIV1ye+HIqsN0LZMaDg9b8/ # 0f/SiBcEQTO80MY= # SIG # End signature block
PowerShellCorpus/PowerShellGallery/AzureRM.Network/3.4.0/ResourceManagerStartup.ps1
ResourceManagerStartup.ps1
# ---------------------------------------------------------------------------------- # # Copyright Microsoft Corporation # Licensed under the Apache License, Version 2.0 (the "License"); # you may not use this file except in compliance with the License. # You may obtain a copy of the License at # http://www.apache.org/licenses/LICENSE-2.0 # Unless required by applicable law or agreed to in writing, software # distributed under the License is distributed on an "AS IS" BASIS, # WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. # See the License for the specific language governing permissions and # limitations under the License. # ---------------------------------------------------------------------------------- # Authorization script commandlet that builds on top of existing Insights comandlets. # This commandlet gets all events for the "Microsoft.Authorization" resource provider by calling the "Get-AzureRmResourceProviderLog" commandlet function Get-AzureRmAuthorizationChangeLog { <# .SYNOPSIS Gets access change history for the selected subscription for the specified time range i.e. role assignments that were added or removed, including classic administrators (co-administrators and service administrators). Maximum duration that can be queried is 15 days (going back up to past 90 days). .DESCRIPTION The Get-AzureRmAuthorizationChangeLog produces a report of who granted (or revoked) what role to whom at what scope within the subscription for the specified time range. The command queries all role assignment events from the Insights resource provider of Azure Resource Manager. Specifying the time range is optional. If both StartTime and EndTime parameters are not specified, the default query interval is the past 1 hour. Maximum duration that can be queried is 15 days (going back up to past 90 days). .PARAMETER StartTime Start time of the query. Optional. .PARAMETER EndTime End time of the query. Optional .EXAMPLE Get-AzureRmAuthorizationChangeLog Gets the access change logs for the past hour. .EXAMPLE Get-AzureRmAuthorizationChangeLog -StartTime "09/20/2015 15:00" -EndTime "09/24/2015 15:00" Gets all access change logs between the specified dates Timestamp : 2015-09-23 21:52:41Z Caller : admin@rbacCliTest.onmicrosoft.com Action : Revoked PrincipalId : 54401967-8c4e-474a-9fbb-a42073f1783c PrincipalName : testUser PrincipalType : User Scope : /subscriptions/9004a9fd-d58e-48dc-aeb2-4a4aec58606f/resourceGroups/TestRG/providers/Microsoft.Network/virtualNetworks/testresource ScopeName : testresource ScopeType : Resource RoleDefinitionId : /subscriptions/9004a9fd-d58e-48dc-aeb2-4a4aec58606f/providers/Microsoft.Authorization/roleDefinitions/b24988ac-6180-42a0-ab88-20f7382dd24c RoleName : Contributor .EXAMPLE Get-AzureRmAuthorizationChangeLog -StartTime ([DateTime]::Now - [TimeSpan]::FromDays(5)) -EndTime ([DateTime]::Now) | FT Caller, Action, RoleName, PrincipalName, ScopeType Gets access change logs for the past 5 days and format the output Caller Action RoleName PrincipalName ScopeType ------ ------ -------- ------------- --------- admin@contoso.com Revoked Contributor User1 Subscription admin@contoso.com Granted Reader User1 Resource Group admin@contoso.com Revoked Contributor Group1 Resource .LINK New-AzureRmRoleAssignment .LINK Get-AzureRmRoleAssignment .LINK Remove-AzureRmRoleAssignment #> [CmdletBinding()] param( [parameter(Mandatory=$false, ValueFromPipelineByPropertyName=$true, HelpMessage = "The start time. Optional If both StartTime and EndTime are not provided, defaults to querying for the past 1 hour. Maximum allowed difference in StartTime and EndTime is 15 days")] [DateTime] $StartTime, [parameter(Mandatory=$false, ValueFromPipelineByPropertyName=$true, HelpMessage = "The end time. Optional. If both StartTime and EndTime are not provided, defaults to querying for the past 1 hour. Maximum allowed difference in StartTime and EndTime is 15 days")] [DateTime] $EndTime ) PROCESS { # Get all events for the "Microsoft.Authorization" provider by calling the Insights commandlet $events = Get-AzureRmLog -ResourceProvider "Microsoft.Authorization" -DetailedOutput -StartTime $StartTime -EndTime $EndTime $startEvents = @{} $endEvents = @{} $offlineEvents = @() # StartEvents and EndEvents will contain matching pairs of logs for when role assignments (and definitions) were created or deleted. # i.e. A PUT on roleassignments will have a Start-End event combination and a DELETE on roleassignments will have another Start-End event combination $startEvents = $events | ? { $_.httpRequest -and $_.Status -ieq "Started" } $events | ? { $_.httpRequest -and $_.Status -ne "Started" } | % { $endEvents[$_.OperationId] = $_ } # This filters non-RBAC events like classic administrator write or delete $events | ? { $_.httpRequest -eq $null } | % { $offlineEvents += $_ } $output = @() # Get all role definitions once from the service and cache to use for all 'startevents' $azureRoleDefinitionCache = @{} Get-AzureRmRoleDefinition | % { $azureRoleDefinitionCache[$_.Id] = $_ } $principalDetailsCache = @{} # Process StartEvents # Find matching EndEvents that succeeded and relating to role assignments only $startEvents | ? { $endEvents.ContainsKey($_.OperationId) ` -and $endEvents[$_.OperationId] -ne $null ` -and $endevents[$_.OperationId].OperationName.StartsWith("Microsoft.Authorization/roleAssignments", [System.StringComparison]::OrdinalIgnoreCase) ` -and $endEvents[$_.OperationId].Status -ieq "Succeeded"} | % { $endEvent = $endEvents[$_.OperationId]; # Create the output structure $out = "" | select Timestamp, Caller, Action, PrincipalId, PrincipalName, PrincipalType, Scope, ScopeName, ScopeType, RoleDefinitionId, RoleName $out.Timestamp = Get-Date -Date $endEvent.EventTimestamp -Format u $out.Caller = $_.Caller if ($_.HttpRequest.Method -ieq "PUT") { $out.Action = "Granted" if ($_.Properties.Content.ContainsKey("requestbody")) { $messageBody = ConvertFrom-Json $_.Properties.Content["requestbody"] } $out.Scope = $_.Authorization.Scope } elseif ($_.HttpRequest.Method -ieq "DELETE") { $out.Action = "Revoked" if ($endEvent.Properties.Content.ContainsKey("responseBody")) { $messageBody = ConvertFrom-Json $endEvent.Properties.Content["responseBody"] } } if ($messageBody) { # Process principal details $out.PrincipalId = $messageBody.properties.principalId if ($out.PrincipalId -ne $null) { # Get principal details by querying Graph. Cache principal details and read from cache if present $principalId = $out.PrincipalId if($principalDetailsCache.ContainsKey($principalId)) { # Found in cache $principalDetails = $principalDetailsCache[$principalId] } else { # not in cache $principalDetails = "" | select Name, Type $user = Get-AzureRmADUser -ObjectId $principalId if ($user) { $principalDetails.Name = $user.DisplayName $principalDetails.Type = "User" } else { $group = Get-AzureRmADGroup -ObjectId $principalId if ($group) { $principalDetails.Name = $group.DisplayName $principalDetails.Type = "Group" } else { $servicePrincipal = Get-AzureRmADServicePrincipal -objectId $principalId if ($servicePrincipal) { $principalDetails.Name = $servicePrincipal.DisplayName $principalDetails.Type = "Service Principal" } } } # add principal details to cache $principalDetailsCache.Add($principalId, $principalDetails); } $out.PrincipalName = $principalDetails.Name $out.PrincipalType = $principalDetails.Type } # Process scope details if ([string]::IsNullOrEmpty($out.Scope)) { $out.Scope = $messageBody.properties.Scope } if ($out.Scope -ne $null) { # Remove the authorization provider details from the scope, if present if ($out.Scope.ToLower().Contains("/providers/microsoft.authorization")) { $index = $out.Scope.ToLower().IndexOf("/providers/microsoft.authorization") $out.Scope = $out.Scope.Substring(0, $index) } $scope = $out.Scope $resourceDetails = "" | select Name, Type $scopeParts = $scope.Split('/', [System.StringSplitOptions]::RemoveEmptyEntries) $len = $scopeParts.Length if ($len -gt 0 -and $len -le 2 -and $scope.ToLower().Contains("subscriptions")) { $resourceDetails.Type = "Subscription" $resourceDetails.Name = $scopeParts[1] } elseif ($len -gt 0 -and $len -le 4 -and $scope.ToLower().Contains("resourcegroups")) { $resourceDetails.Type = "Resource Group" $resourceDetails.Name = $scopeParts[3] } elseif ($len -ge 6 -and $scope.ToLower().Contains("providers")) { $resourceDetails.Type = "Resource" $resourceDetails.Name = $scopeParts[$len -1] } $out.ScopeName = $resourceDetails.Name $out.ScopeType = $resourceDetails.Type } # Process Role definition details $out.RoleDefinitionId = $messageBody.properties.roleDefinitionId if ($out.RoleDefinitionId -ne $null) { #Extract roleDefinitionId Guid value from the fully qualified id string. $roleDefinitionIdGuid= $out.RoleDefinitionId.Substring($out.RoleDefinitionId.LastIndexOf("/")+1) if ($azureRoleDefinitionCache[$roleDefinitionIdGuid]) { $out.RoleName = $azureRoleDefinitionCache[$roleDefinitionIdGuid].Name } else { $out.RoleName = "" } } } $output += $out } # start event processing complete # Filter classic admins events $offlineEvents | % { if($_.Status -ne $null -and $_.Status -ieq "Succeeded" -and $_.OperationName -ne $null -and $_.operationName.StartsWith("Microsoft.Authorization/ClassicAdministrators", [System.StringComparison]::OrdinalIgnoreCase)) { $out = "" | select Timestamp, Caller, Action, PrincipalId, PrincipalName, PrincipalType, Scope, ScopeName, ScopeType, RoleDefinitionId, RoleName $out.Timestamp = Get-Date -Date $_.EventTimestamp -Format u $out.Caller = "Subscription Admin" if($_.operationName -ieq "Microsoft.Authorization/ClassicAdministrators/write"){ $out.Action = "Granted" } elseif($_.operationName -ieq "Microsoft.Authorization/ClassicAdministrators/delete"){ $out.Action = "Revoked" } $out.RoleDefinitionId = $null $out.PrincipalId = $null $out.PrincipalType = "User" $out.Scope = "/subscriptions/" + $_.SubscriptionId $out.ScopeType = "Subscription" $out.ScopeName = $_.SubscriptionId if($_.Properties -ne $null){ $out.PrincipalName = $_.Properties.Content["adminEmail"] $out.RoleName = "Classic " + $_.Properties.Content["adminType"] } $output += $out } } # end offline events $output | Sort Timestamp } } # End commandlet # SIG # Begin signature block # MIIdpwYJKoZIhvcNAQcCoIIdmDCCHZQCAQExCzAJBgUrDgMCGgUAMGkGCisGAQQB # gjcCAQSgWzBZMDQGCisGAQQBgjcCAR4wJgIDAQAABBAfzDtgWUsITrck0sYpfvNR # AgEAAgEAAgEAAgEAAgEAMCEwCQYFKw4DAhoFAAQUxf3QflcJBGQFfPuf/JfGrjT4 # dQKgghhlMIIEwzCCA6ugAwIBAgITMwAAAMvZUgZTvz4qWQAAAAAAyzANBgkqhkiG # 9w0BAQUFADB3MQswCQYDVQQGEwJVUzETMBEGA1UECBMKV2FzaGluZ3RvbjEQMA4G # A1UEBxMHUmVkbW9uZDEeMBwGA1UEChMVTWljcm9zb2Z0IENvcnBvcmF0aW9uMSEw # HwYDVQQDExhNaWNyb3NvZnQgVGltZS1TdGFtcCBQQ0EwHhcNMTYwOTA3MTc1ODU1 # WhcNMTgwOTA3MTc1ODU1WjCBszELMAkGA1UEBhMCVVMxEzARBgNVBAgTCldhc2hp # bmd0b24xEDAOBgNVBAcTB1JlZG1vbmQxHjAcBgNVBAoTFU1pY3Jvc29mdCBDb3Jw # b3JhdGlvbjENMAsGA1UECxMETU9QUjEnMCUGA1UECxMebkNpcGhlciBEU0UgRVNO # OjU4NDctRjc2MS00RjcwMSUwIwYDVQQDExxNaWNyb3NvZnQgVGltZS1TdGFtcCBT # ZXJ2aWNlMIIBIjANBgkqhkiG9w0BAQEFAAOCAQ8AMIIBCgKCAQEAum1PI6z8Uk7O # jh+jHA7qkPtqGl+g9Ol0qKYBPtGxZ7SgIuZrXcfSVifUjgXwk+0q9TQFSiD+/b5L # akoaE7Onwvh5GKjFrZH4Ymu8lwmIQBFCa5liePRTnVQybA/c18S/8AhhXn7t3/QL # gh27vP7FnFy3lDYiVoEhxM40kv6vM0OuiBlFTxwWfBWzwHDem0cA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tq1cnTgxL5nbRY+SjYv # 8TN1ZI5MUKiUmPC1zkGnCYN4SN0/Uc90HgleqK5HpaGCAigwggIkBgkqhkiG9w0B # CQYxggIVMIICEQIBATCBjjB3MQswCQYDVQQGEwJVUzETMBEGA1UECBMKV2FzaGlu # Z3RvbjEQMA4GA1UEBxMHUmVkbW9uZDEeMBwGA1UEChMVTWljcm9zb2Z0IENvcnBv # cmF0aW9uMSEwHwYDVQQDExhNaWNyb3NvZnQgVGltZS1TdGFtcCBQQ0ECEzMAAADL # 2VIGU78+KlkAAAAAAMswCQYFKw4DAhoFAKBdMBgGCSqGSIb3DQEJAzELBgkqhkiG # 9w0BBwEwHAYJKoZIhvcNAQkFMQ8XDTE3MDExODAxNDkwNFowIwYJKoZIhvcNAQkE # MRYEFIesLttsFc1H1N2/cStMGt9SFoDCMA0GCSqGSIb3DQEBBQUABIIBAAh7DFXp # MxX1ySuweYOunL92qyunzPBf9YDIzKAnGPx3Jg7zz+RD7RQ0AO8t59TrVTkbHd5j # b94ZxEd1noIyZsyGrNVO443DwkYqaA7XpyOVxMj5tIufpq/dQvNjNFTKOKR12GDe # gkV2eDJ9viBJowk6oTXpC+AcLMvbIsvT4l4fM8kgmbT354dQYzluIeccsPIV/bik # 5S4+61Ft7PmVc4sDMDPiMYM2M3/l4NSX2SGsmFv03uRSdjiazLEIuxe1nLmtWg/v # nfmqSwj+BLQPLUIAlUK4gnYtH0/mX4mbBqYzZ+or6osC/yPF8HEGHGCTexxVed2/ # wTnz4Vuav6TbPP0= # SIG # End signature block
PowerShellCorpus/PowerShellGallery/AzSDKPreview/2.2.0/AlertMonitoring/OMS.ps1
OMS.ps1
Set-StrictMode -Version Latest function Set-AzSDKOMSSettings { <# .SYNOPSIS This command would help in updating the OMS configuration settings under the current powershell session. .DESCRIPTION This command will update the OMS Settings under the current powershell session. This also remembers the current settings and use them in the subsequent sessions. .PARAMETER OMSWorkspaceID Workspace ID of your OMS instance. AzSDK data would be pushed to this instance. .PARAMETER OMSSharedKey Shared key of your OMS instance. .PARAMETER Source Provide the source of OMS Events.(e.g. CC,CICD,SDL) .PARAMETER Disable Use -Disable option to clean the OMS setting under the current instance. .LINK https://aka.ms/azsdkdocs #> param( [Parameter(Mandatory = $true, HelpMessage="Workspace ID of your OMS instance. AzSDK data would be pushed to this instance.", ParameterSetName = "Setup")] [AllowEmptyString()] [string] $OMSWorkspaceID, [Parameter(Mandatory = $true, HelpMessage="Shared key of your OMS instance.", ParameterSetName = "Setup")] [AllowEmptyString()] [string] $OMSSharedKey, [Parameter(Mandatory = $false, HelpMessage="Provide the source of OMS Events.(e.g. CC,CICD,SDL)", ParameterSetName = "Setup")] [AllowEmptyString()] [string] $Source, [Parameter(Mandatory = $true, HelpMessage="Use -Disable option to clean the OMS setting under the current instance.", ParameterSetName = "Disable")] [switch] $Disable ) Begin { [ListenerHelper]::RegisterListeners(); } Process { try { $appSettings = [ConfigurationManager]::GetAzSdkSettings() if(-not $Disable) { $appSettings.OMSWorkspaceId = $OMSWorkspaceID $appSettings.OMSSharedKey = $OMSSharedKey } else { $appSettings.OMSWorkspaceId = "" $appSettings.OMSSharedKey = "" } if(-not [string]::IsNullOrWhiteSpace($Source)) { $AppSettings.OMSSource = $Source } else { $AppSettings.OMSSource = "SDL" } $appSettings.Update(); } catch { [EventBase]::PublishGenericException($_); } } End { [ListenerHelper]::UnregisterListeners(); } } function Install-AzSDKOMSSecurityPack { <# .SYNOPSIS This command would help in creating security dashboard for applications .DESCRIPTION This command would help in creating security dashboard for applications .PARAMETER ApplicationRGMappingJSON Provide the application and resource group mapping config as JSON input .PARAMETER ApplicationRGMappingJSONConfigPath Provide the application and resource group mapping config as JSON config file .EXAMPLE .NOTES This command helps the application team to check compliance of Azure Subscriptions with the AzSDK security guidance. .LINK https://aka.ms/azsdkdocs #> param( [Parameter(ParameterSetName= "PackageJsonObjectParameterSet", Mandatory = $true)] [string] [ValidateNotNullOrEmpty()] $SubscriptionId, [Parameter(ParameterSetName= "PackageJsonObjectParameterSet", Mandatory = $true)] [string] $OMSResourceGroupName, [Parameter(ParameterSetName= "PackageJsonObjectParameterSet", Mandatory = $false)] [string] $OMSSubCCParamFilePath, [Parameter(ParameterSetName= "PackageJsonObjectParameterSet", Mandatory = $false)] [string] $OMSAppCCParamFilePath, [switch] [Parameter(Mandatory = $False)] $ValidateOnly ) Begin { [ListenerHelper]::RegisterListeners(); } Process { try { $OMSMonitoringInstance = [OMSMonitoring]::new($SubscriptionId); $OMSMonitoringInstance.CreateOMSPolicies($OMSResourceGroupName, $OMSSubCCParamFilePath, $OMSAppCCParamFilePath , $ValidateOnly) } catch { [EventBase]::PublishGenericException($_); } } End { [ListenerHelper]::UnregisterListeners(); } }
PowerShellCorpus/PowerShellGallery/AzSDKPreview/2.2.0/SVT/SVT.ps1
SVT.ps1
Set-StrictMode -Version Latest function Get-AzSDKAzureServicesSecurityStatus { <# .SYNOPSIS This command would help in validating the security controls for the Azure resources meeting the specified input criteria. .DESCRIPTION This command will execute the security controls and will validate their status as 'Success' or 'Failure' based on the security guidance. Refer https://aka.ms/azsdkdocs for more information .PARAMETER SubscriptionId Subscription id for which the security evaluation has to be performed. .PARAMETER ResourceGroupNames ResourceGroups for which the security evaluation has to be performed. Comma seperated values are supported. Wildcards are not permitted. By default, the command gets all resources in the subscription. .PARAMETER ResourceType Gets only resources of the specified resource type. Wildcards are not permitted. e.g.: Microsoft.KeyVault/vaults. Run command 'Get-AzSDKSupportedResourceTypes' to get the list of supported types. .PARAMETER ResourceTypeName Friendly name of resource type. e.g.: KeyVault. Run command 'Get-AzSDKSupportedResourceTypes' to get the list of supported values. .PARAMETER ResourceName Gets a resource with the specified name. Wildcards are not permitted. By default, the command gets all resources in the subscription. .PARAMETER Tag The tag filter for Azure resource. The expected format is @{tagName1=$null} or @{tagName = 'tagValue'; tagName2='value1'}. .PARAMETER TagName The name of the tag to query for Azure resource. .PARAMETER TagValue The value of the tag to query for Azure resource. .PARAMETER FilterTags Comma seperated tags to filter the security controls. e.g.: RBAC, SOX, AuthN etc. .PARAMETER ExcludeTags Comma seperated tags to exclude the security controls. e.g.: RBAC, SOX, AuthN etc. .PARAMETER AttestControls Enables users to attest controls with proper justification .PARAMETER DoNotOpenOutputFolder Switch to specify whether to open output folder containing all security evaluation report or not. .NOTES This command helps the application team to verify whether their Azure resources are compliant with the security guidance or not .LINK https://aka.ms/azsdkdocs #> [OutputType([String])] Param ( [string] [Parameter(Mandatory = $true, HelpMessage = "Subscription id for which the security evaluation has to be performed.")] [ValidateNotNullOrEmpty()] $SubscriptionId, [string] [Parameter(Mandatory = $false, ParameterSetName = "ResourceFilter", HelpMessage = "ResourceGroups for which the security evaluation has to be performed. Comma seperated values are supported. Wildcards are not permitted. By default, the command gets all resources in the subscription.")] $ResourceGroupNames, [string] [Parameter(Mandatory = $false, ParameterSetName = "ResourceFilter", HelpMessage = "Gets only resources of the specified resource type. Wildcards are not permitted. e.g.: Microsoft.KeyVault/vaults. Run command 'Get-AzSDKSupportedResourceTypes' to get the list of supported types.")] $ResourceType, [Parameter(Mandatory = $false, ParameterSetName = "ResourceFilter", HelpMessage = "Friendly name of resource type. e.g.: KeyVault. Run command 'Get-AzSDKSupportedResourceTypes' to get the list of supported values.")] [ResourceTypeName] $ResourceTypeName = [ResourceTypeName]::All, [string] [Parameter(Mandatory = $false, ParameterSetName = "ResourceFilter", HelpMessage = "Gets a resource with the specified name. Wildcards are not permitted. By default, the command gets all resources in the subscription.")] $ResourceName, [Hashtable] [Parameter(Mandatory = $true, ParameterSetName = "TagHashset", HelpMessage = "The tag filter for Azure resource. The expected format is @{tagName1=`$null} or @{tagName = 'tagValue'; tagName2='value1'}.")] $Tag, [string] [Parameter(Mandatory = $true, ParameterSetName = "TagName", HelpMessage = "The name of the tag to query for Azure resource.")] $TagName, [string] [Parameter(Mandatory = $true, ParameterSetName = "TagName", HelpMessage = "The value of the tag to query for Azure resource.")] $TagValue, [string] [Parameter(Mandatory = $false, HelpMessage = "Comma seperated control ids to filter the security controls. e.g.: Azure_Subscription_AuthZ_Limit_Admin_Owner_Count, Azure_Storage_DP_Encrypt_At_Rest_Blob etc.")] $ControlIds, [string] [Parameter(Mandatory = $false, HelpMessage = "Comma seperated tags to filter the security controls. e.g.: RBAC, SOX, AuthN etc.")] $FilterTags, [string] [Parameter(Mandatory = $false, HelpMessage = "Comma seperated tags to exclude the security controls. e.g.: RBAC, SOX, AuthN etc.")] $ExcludeTags, [AttestControls] [Parameter(Mandatory = $false, HelpMessage = "Enables users to attest controls with proper justification.")] $AttestControls = [AttestControls]::None, [switch] [Parameter(Mandatory = $false, HelpMessage = "Switch to specify whether to open output folder containing all security evaluation report or not.")] $DoNotOpenOutputFolder ) Begin { [ListenerHelper]::RegisterListeners(); } Process {      try { $resolver = [SVTResourceResolver]::new($SubscriptionId, $ResourceGroupNames); $resolver.ResourceName = $ResourceName; $resolver.ResourceType = $ResourceType; $resolver.ResourceTypeName = $ResourceTypeName; $resolver.Tag = $Tag; $resolver.TagName = $TagName; $resolver.TagValue = $TagValue; $secStatus = [ServicesSecurityStatus]::new($SubscriptionId, $PSCmdlet.MyInvocation, $resolver); if ($secStatus) { # Just copy all the tags without validation. Validation will be done internally $secStatus.FilterTags = $FilterTags; $secStatus.ExcludeTags = $ExcludeTags; $secStatus.ControlIds = $ControlIds; $secStatus.AttestControls = $AttestControls; return $secStatus.EvaluateControlStatus(); } } catch { [EventBase]::PublishGenericException($_); } } End { [ListenerHelper]::UnregisterListeners(); } } function Get-AzSDKSubscriptionSecurityStatus { <# .SYNOPSIS This command would help in validating the security controls for the Azure Subscription meeting the specified input criteria. .DESCRIPTION This command will execute the security controls and will validate their status as 'Success' or 'Failure' based on the security guidance. Refer https://aka.ms/azsdkdocs for more information .PARAMETER SubscriptionId Subscription id for which the security evaluation has to be performed. .PARAMETER FilterTags Comma seperated tags to filter the security controls. e.g.: RBAC, SOX, AuthN etc. .PARAMETER ExcludeTags Comma seperated tags to exclude the security controls. e.g.: RBAC, SOX, AuthN etc. .PARAMETER AttestControls Enables users to attest controls with proper justification .PARAMETER DoNotOpenOutputFolder Switch to specify whether to open output folder containing all security evaluation report or not. .NOTES This command helps the application team to verify whether their Azure subscription are compliant with the security guidance or not .LINK https://aka.ms/azsdkdocs #> [OutputType([String])] Param ( [Parameter(Mandatory = $True, HelpMessage = "Subscription id for which the security evaluation has to be performed.")] [string] [ValidateNotNullOrEmpty()] $SubscriptionId, [string] [Parameter(Mandatory = $false, HelpMessage = "Comma seperated control ids to filter the security controls. e.g.: Azure_Subscription_AuthZ_Limit_Admin_Owner_Count, Azure_Storage_DP_Encrypt_At_Rest_Blob etc.")] $ControlIds, [string] [Parameter(Mandatory = $false, HelpMessage = "Comma seperated tags to filter the security controls. e.g.: RBAC, SOX, AuthN etc.")] $FilterTags, [string] [Parameter(Mandatory = $false, HelpMessage = "Comma seperated tags to exclude the security controls. e.g.: RBAC, SOX, AuthN etc.")] $ExcludeTags, [AttestControls] [Parameter(Mandatory = $false, HelpMessage = "Enables users to attest controls with proper justification.")] $AttestControls = [AttestControls]::None, [switch] [Parameter(Mandatory = $false, HelpMessage = "Switch to specify whether to open output folder containing all security evaluation report or not.")] $DoNotOpenOutputFolder ) Begin { [ListenerHelper]::RegisterListeners(); } Process {      try { $sscore = [SubscriptionSecurityStatus]::new($SubscriptionId, $PSCmdlet.MyInvocation); if ($sscore) { # Just copy all the tags without validation. Validation will be done internally $sscore.FilterTags = $FilterTags; $sscore.ExcludeTags = $ExcludeTags; $sscore.ControlIds = $ControlIds; $sscore.AttestControls = $AttestControls; return $sscore.EvaluateControlStatus(); } } catch { [EventBase]::PublishGenericException($_); } } End { [ListenerHelper]::UnregisterListeners(); } } function Get-AzSDKExpressRouteNetworkSecurityStatus { <# .SYNOPSIS This command would help in validating the security controls for the ExpressRoute enabled VNet resources meeting the specified input criteria. .DESCRIPTION This command will execute the security controls and will validate their status as 'Success' or 'Failure' based on the security guidance. Refer https://aka.ms/azsdkdocs for more information .PARAMETER SubscriptionId Subscription id for which the security evaluation has to be performed. .PARAMETER ResourceGroupNames ResourceGroups which host ExpressRoute VNets. Comma seperated values are supported. Wildcards are not permitted. By default, the command gets all resources in the subscription. .PARAMETER ResourceName ExpressRoute VNet resource name. Wildcards are not permitted. By default, the command gets all resources in the subscription. .PARAMETER FilterTags Comma seperated tags to filter the security controls. e.g.: RBAC, SOX, AuthN etc. .PARAMETER ExcludeTags Comma seperated tags to exclude the security controls. e.g.: RBAC, SOX, AuthN etc. .PARAMETER AttestControls Enables users to attest controls with proper justification .PARAMETER DoNotOpenOutputFolder Switch to specify whether to open output folder containing all security evaluation report or not. .NOTES This command helps the application team to verify whether their ExpressRoute enabled VNets are compliant with the security guidance or not .LINK https://aka.ms/azsdkdocs #> [OutputType([String])] Param( [string] [Parameter(Mandatory = $true, HelpMessage = "Provide the subscription id for which the security report has to be generated")] [ValidateNotNullOrEmpty()] $SubscriptionId, [string] [Parameter(Mandatory = $false, HelpMessage = "ResourceGroups which host ExpressRoute VNets. Comma seperated values are supported. Wildcards are not permitted. By default, the command gets all resources in the subscription.")] $ResourceGroupNames, [string] [Parameter(Mandatory = $false, ParameterSetName = "ResourceFilter", HelpMessage = "ExpressRoute VNet resource name. Wildcards are not permitted. By default, the command gets all resources in the subscription.")] $ResourceName, [string] [Parameter(Mandatory = $false, HelpMessage = "Comma seperated control ids to filter the security controls. e.g.: Azure_Subscription_AuthZ_Limit_Admin_Owner_Count, Azure_Storage_DP_Encrypt_At_Rest_Blob etc.")] $ControlIds, [string] [Parameter(Mandatory = $false, HelpMessage = "Comma seperated tags to filter the security controls. e.g.: RBAC, SOX, AuthN etc.")] $FilterTags, [string] [Parameter(Mandatory = $false, HelpMessage = "Comma seperated tags to exclude the security controls. e.g.: RBAC, SOX, AuthN etc.")] $ExcludeTags, [AttestControls] [Parameter(Mandatory = $false, HelpMessage = "Enables users to attest controls with proper justification.")] $AttestControls = [AttestControls]::None, [switch] [Parameter(Mandatory = $false, HelpMessage = "Switch to specify whether to open output folder containing all security evaluation report or not.")] $DoNotOpenOutputFolder ) $erResourceGroups = $ResourceGroupNames; if([string]::IsNullOrEmpty($erResourceGroups)) { $erResourceGroups = [ConfigurationManager]::GetAzSdkConfigData().ERvNetResourceGroupNames } Get-AzSDKAzureServicesSecurityStatus -SubscriptionId $SubscriptionId -ResourceGroupNames $erResourceGroups -ResourceName $ResourceName ` -ResourceTypeName "ERvNet" -ControlIds $ControlIds -FilterTags $FilterTags -ExcludeTags $ExcludeTags -DoNotOpenOutputFolder:$DoNotOpenOutputFolder -AttestControls:$AttestControls } function Get-AzSDKControlsStatus { <# .SYNOPSIS This command would help in validating the security controls for the Azure resources meeting the specified input criteria. .DESCRIPTION This command will execute the security controls and will validate their status as 'Success' or 'Failure' based on the security guidance. Refer https://aka.ms/azsdkdocs for more information .PARAMETER SubscriptionId Subscription id for which the security evaluation has to be performed. .PARAMETER ResourceGroupNames ResourceGroups for which the security evaluation has to be performed. Comma seperated values are supported. Wildcards are not permitted. By default, the command gets all resources in the subscription. .PARAMETER ResourceType Gets only resources of the specified resource type. Wildcards are not permitted. e.g.: Microsoft.KeyVault/vaults. Run command 'Get-AzSDKSupportedResourceTypes' to get the list of supported types. .PARAMETER ResourceTypeName Friendly name of resource type. e.g.: KeyVault. Run command 'Get-AzSDKSupportedResourceTypes' to get the list of supported values. .PARAMETER ResourceName Gets a resource with the specified name. Wildcards are not permitted. By default, the command gets all resources in the subscription. .PARAMETER Tag The tag filter for Azure resource. The expected format is @{tagName1=$null} or @{tagName = 'tagValue'; tagName2='value1'}. .PARAMETER TagName The name of the tag to query for Azure resource. .PARAMETER TagValue The value of the tag to query for Azure resource. .PARAMETER FilterTags Comma seperated tags to filter the security controls. e.g.: RBAC, SOX, AuthN etc. .PARAMETER ExcludeTags Comma seperated tags to exclude the security controls. e.g.: RBAC, SOX, AuthN etc. .PARAMETER AttestControls Enables users to attest controls with proper justification .PARAMETER DoNotOpenOutputFolder Switch to specify whether to open output folder containing all security evaluation report or not. .NOTES This command helps the application team to verify whether their Azure resources are compliant with the security guidance or not .LINK https://aka.ms/azsdkdocs #> [OutputType([String])] Param ( [string] [Parameter(Mandatory = $true, HelpMessage = "Subscription id for which the security evaluation has to be performed.")] [ValidateNotNullOrEmpty()] $SubscriptionId, [string] [Parameter(Mandatory = $false, ParameterSetName = "ResourceFilter", HelpMessage = "ResourceGroups for which the security evaluation has to be performed. Comma seperated values are supported. Wildcards are not permitted. By default, the command gets all resources in the subscription.")] $ResourceGroupNames, [string] [Parameter(Mandatory = $false, ParameterSetName = "ResourceFilter", HelpMessage = "Gets only resources of the specified resource type. Wildcards are not permitted. e.g.: Microsoft.KeyVault/vaults. Run command 'Get-AzSDKSupportedResourceTypes' to get the list of supported types.")] $ResourceType, [Parameter(Mandatory = $false, ParameterSetName = "ResourceFilter", HelpMessage = "Friendly name of resource type. e.g.: KeyVault. Run command 'Get-AzSDKSupportedResourceTypes' to get the list of supported values.")] [ResourceTypeName] $ResourceTypeName = [ResourceTypeName]::All, [string] [Parameter(Mandatory = $false, ParameterSetName = "ResourceFilter", HelpMessage = "Gets a resource with the specified name. Wildcards are not permitted. By default, the command gets all resources in the subscription.")] $ResourceName, [Hashtable] [Parameter(Mandatory = $true, ParameterSetName = "TagHashset", HelpMessage = "The tag filter for Azure resource. The expected format is @{tagName1=`$null} or @{tagName = 'tagValue'; tagName2='value1'}.")] $Tag, [string] [Parameter(Mandatory = $true, ParameterSetName = "TagName", HelpMessage = "The name of the tag to query for Azure resource.")] $TagName, [string] [Parameter(Mandatory = $true, ParameterSetName = "TagName", HelpMessage = "The value of the tag to query for Azure resource.")] $TagValue, [string] [Parameter(Mandatory = $false, HelpMessage = "Comma seperated control ids to filter the security controls. e.g.: Azure_Subscription_AuthZ_Limit_Admin_Owner_Count, Azure_Storage_DP_Encrypt_At_Rest_Blob etc.")] $ControlIds, [string] [Parameter(Mandatory = $false, HelpMessage = "Comma seperated tags to filter the security controls. e.g.: RBAC, SOX, AuthN etc.")] $FilterTags, [string] [Parameter(Mandatory = $false, HelpMessage = "Comma seperated tags to exclude the security controls. e.g.: RBAC, SOX, AuthN etc.")] $ExcludeTags, [AttestControls] [Parameter(Mandatory = $false, HelpMessage = "Enables users to attest controls with proper justification.")] $AttestControls = [AttestControls]::None, [switch] [Parameter(Mandatory = $false, HelpMessage = "Switch to specify whether to open output folder containing all security evaluation report or not.")] $DoNotOpenOutputFolder ) Begin { [ListenerHelper]::RegisterListeners(); } Process {      try { $resolver = [SVTResourceResolver]::new($SubscriptionId, $ResourceGroupNames); $resolver.ResourceName = $ResourceName; $resolver.ResourceType = $ResourceType; $resolver.ResourceTypeName = $ResourceTypeName; $resolver.Tag = $Tag; $resolver.TagName = $TagName; $resolver.TagValue = $TagValue; $controlReport = [SVTStatusReport]::new($SubscriptionId, $PSCmdlet.MyInvocation, $resolver); if ($controlReport) { # Just copy all the tags without validation. Validation will be done internally $controlReport.FilterTags = $FilterTags; $controlReport.ExcludeTags = $ExcludeTags; $controlReport.ControlIds = $ControlIds; $controlReport.AttestControls = $AttestControls; return $controlReport.EvaluateControlStatus(); } } catch { [EventBase]::PublishGenericException($_); } } End { [ListenerHelper]::UnregisterListeners(); } }
PowerShellCorpus/PowerShellGallery/AzSDKPreview/2.2.0/Framework/Framework.ps1
Framework.ps1
Set-StrictMode -Version Latest # Hack to load AI dlls try {Get-AzureRmContext -ErrorAction SilentlyContinue | Out-Null}catch {} #Constants . $PSScriptRoot\Helpers\Constants.ps1 #Models . $PSScriptRoot\Models\Enums.ps1 . $PSScriptRoot\Models\AzSdkGenericEvent.ps1 . $PSScriptRoot\Abstracts\EventBase.ps1 . $PSScriptRoot\Helpers\Helpers.ps1 #Helpers (independent of models) . $PSScriptRoot\Helpers\ConfigurationHelper.ps1 . $PSScriptRoot\Models\AzSdkConfig.ps1 . $PSScriptRoot\Models\AzSdkEvent.ps1 . $PSScriptRoot\Models\AzSdkSettings.ps1 . $PSScriptRoot\Models\SVT\SVTConfig.ps1 . $PSScriptRoot\Models\SVT\SVTEvent.ps1 . $PSScriptRoot\Models\SVT\SVTResource.ps1 . $PSScriptRoot\Models\SVT\PSCloudService.ps1 . $PSScriptRoot\Models\SubscriptionCore\AzureSecurityCenter.ps1 . $PSScriptRoot\Models\SubscriptionCore\ManagementCertificate.ps1 . $PSScriptRoot\Models\SubscriptionSecurity\SubscriptionRBAC.ps1 . $PSScriptRoot\Models\ContinuousCompliance\AutomationAccount.ps1 . $PSScriptRoot\Models\ControlState.ps1 . $PSScriptRoot\Models\RemoteReports\ScanResultModels.ps1 #Helpers . $PSScriptRoot\Helpers\Helpers.ps1 . $PSScriptRoot\Helpers\WebRequestHelper.ps1 . $PSScriptRoot\Helpers\ActiveDirectoryHelper.ps1 . $PSScriptRoot\Helpers\RoleAssignmentHelper.ps1 . $PSScriptRoot\Helpers\SecurityCenterHelper.ps1 . $PSScriptRoot\Helpers\SVTMapping.ps1 . $PSScriptRoot\Helpers\IdentityHelpers.ps1 #Managers . $PSScriptRoot\Managers\ConfigurationManager.ps1 . $PSScriptRoot\Managers\ControlStateExtension.ps1 . $PSScriptRoot\Helpers\RemoteApiHelper.ps1 #Abstracts . $PSScriptRoot\Abstracts\AzSdkRoot.ps1 . $PSScriptRoot\Abstracts\SVTBase.ps1 . $PSScriptRoot\Abstracts\ListenerBase.ps1 . $PSScriptRoot\Abstracts\FileOutputBase.ps1 #Listeners . $PSScriptRoot\Listeners\UserReports\WriteFolderPath.ps1 (Get-ChildItem -Path "$PSScriptRoot\Listeners\UserReports" -Recurse -File -Include "*.ps1" -Exclude "WriteFolderPath.ps1") | ForEach-Object { . $_.FullName } . $PSScriptRoot\Listeners\RemoteReports\TelemetryStrings.ps1 . $PSScriptRoot\Listeners\RemoteReports\RemoteReportHelper.ps1 . $PSScriptRoot\Listeners\RemoteReports\VulnDataPublisher.ps1 . $PSScriptRoot\Listeners\RemoteReports\ControlTelemetry.ps1 . $PSScriptRoot\Listeners\RemoteReports\UsageTelemetry.ps1 <# . $PSScriptRoot\Listeners\Telemetry\ControlTelemetryHelper.ps1 . $PSScriptRoot\Listeners\Telemetry\UsageTelemetryHelper.ps1 . $PSScriptRoot\Listeners\Telemetry\ControlTelemetry.ps1 . $PSScriptRoot\Listeners\Telemetry\UsageTelemetry.ps1 #> . $PSScriptRoot\Listeners\OMS\OMSOutput.ps1 . $PSScriptRoot\Listeners\ListenerHelper.ps1 #Remaining Abstracts . $PSScriptRoot\Core\SVT\SVTControlAttestation.ps1 . $PSScriptRoot\Abstracts\CommandBase.ps1 . $PSScriptRoot\Abstracts\SVTCommandBase.ps1 #Core . $PSScriptRoot\Core\SVT\SVTIaasBase.ps1 (Get-ChildItem -Path "$PSScriptRoot\Core\SVT\Services\" -Recurse -File) | ForEach-Object { . $_.FullName } (Get-ChildItem -Path "$PSScriptRoot\Core\SubscriptionSecurity\" -Recurse -File) | ForEach-Object { . $_.FullName } . $PSScriptRoot\Core\AzureMonitoring\OMSMonitoring.ps1 . $PSScriptRoot\Core\SVT\SubscriptionCore\SubscriptionCore.ps1 . $PSScriptRoot\Core\SVT\SVTResourceResolver.ps1 . $PSScriptRoot\Core\SVT\ServicesSecurityStatus.ps1 . $PSScriptRoot\Core\SVT\SubscriptionSecurityStatus.ps1 . $PSScriptRoot\Core\SVT\SVTStatusReport.ps1 . $PSScriptRoot\Core\ContinuousCompliance\CCAutomation.ps1
PowerShellCorpus/PowerShellGallery/AzSDKPreview/2.2.0/Framework/Core/SVT/ServicesSecurityStatus.ps1
ServicesSecurityStatus.ps1
Set-StrictMode -Version Latest class ServicesSecurityStatus: SVTCommandBase { [SVTResourceResolver] $Resolver = $null; ServicesSecurityStatus([string] $subscriptionId, [InvocationInfo] $invocationContext, [SVTResourceResolver] $resolver): Base($subscriptionId, $invocationContext) { if(-not $resolver) { throw [System.ArgumentException] ("The argument 'resolver' is null"); } $this.Resolver = $resolver; $this.Resolver.LoadAzureResources(); } hidden [SVTEventContext[]] RunAllControls() { [SVTEventContext[]] $result = @(); $this.PublishCustomMessage("Number of resources found: $($this.Resolver.SVTResources.Count)"); $nonAutomatedResources = [array] ($this.Resolver.SVTResources | Where-Object { $null -eq $_.ResourceTypeMapping }); $automatedResources = [array] ($this.Resolver.SVTResources | Where-Object { $_.ResourceTypeMapping }); $this.PublishCustomMessage("Number of resources for which security controls will be evaluated: $(($automatedResources | Measure-Object).Count)"); if(($nonAutomatedResources | Measure-Object).Count -gt 0) { $this.PublishCustomMessage("Number of resources for which security controls will NOT be evaluated: $($nonAutomatedResources.Count)", [MessageType]::Warning); $nonAutomatedResTypes = [array] ($nonAutomatedResources | Select-Object -Property ResourceType -Unique); $this.PublishCustomMessage([MessageData]::new("Security controls are yet to be automated for the following service types: ", $nonAutomatedResTypes)); $this.PublishAzSdkRootEvent([AzSdkRootEvent]::UnsupportedResources, $nonAutomatedResources); } $totalResources = ($automatedResources | Measure-Object).Count; [int] $currentCount = 0; $automatedResources | ForEach-Object { try { $currentCount += 1; if($totalResources -gt 1) { $this.PublishCustomMessage("Checking resource [$currentCount/$totalResources]"); } $svtClassName = $_.ResourceTypeMapping.ClassName; $svtObject = New-Object -TypeName $svtClassName -ArgumentList $this.SubscriptionContext.SubscriptionId, $_ $this.SetSVTBaseProperties($svtObject); $result += $svtObject.EvaluateAllControls(); # Register/Deregister all listeners to cleanup the memory [ListenerHelper]::RegisterListeners(); } catch { $this.CommandError($_); } } return $result; } }
PowerShellCorpus/PowerShellGallery/AzSDKPreview/2.2.0/Framework/Core/SVT/SVTIaasBase.ps1
SVTIaasBase.ps1
Set-StrictMode -Version Latest class SVTIaasBase: SVTBase { hidden [PSObject] $ResourceObject; hidden [PSObject[]] $vNetNics; hidden [PSObject[]] $vNetNicsOutput; SVTIaasBase([string] $subscriptionId, [string] $resourceGroupName, [string] $resourceName): Base($subscriptionId, $resourceGroupName, $resourceName) { $this.GetResourceObject(); $this.GetvNetNics($this.ResourceObject.Subnets); $this.GetvnetNicsProperties($this.vNetNics); } SVTIaasBase([string] $subscriptionId, [SVTResource] $svtResource): Base($subscriptionId, $svtResource) { $this.GetResourceObject(); $this.GetvNetNics($this.ResourceObject.Subnets); $this.GetvnetNicsProperties($this.vNetNics); } hidden [PSObject] GetResourceObject() { if (-not $this.ResourceObject) { $this.ResourceObject = Get-AzureRmVirtualNetwork -ResourceGroupName $this.ResourceContext.ResourceGroupName ` -Name $this.ResourceContext.ResourceName if(-not $this.ResourceObject) { throw ("Resource '{0}' not found under Resource Group '{1}'" -f ($this.ResourceContext.ResourceName), ($this.ResourceContext.ResourceGroupName)) } } return $this.ResourceObject; } hidden [PSObject[]] GetvNetNics($VNetSubnets) { if (-not $this.vNetNics) { $VNetSubnets | ForEach-Object{ Set-Variable -Name currentsubnet -Scope Local -Value $_ if($null -ne $currentsubnet.IpConfigurations ) { $currentsubnet.IpConfigurations | ForEach-Object{ Set-Variable -Name currentipconfig -Scope Local -Value $_ if($currentipconfig.Id.Contains("Microsoft.Network/networkInterfaces")) { $currentipconfig = $currentipconfig.Id.ToLower() $nicresourceid = $currentipconfig.Substring(0,$currentipconfig.LastIndexOf("ipconfigurations")-1) $nic = Get-AzureRmResource -ResourceId $nicresourceid $this.vNetNics += $nic } } } } } return $this.vNetNics; } hidden [PSObject[]] GetvnetNicsProperties($vNetNics) { if(-not $this.vNetNicsOutput) { if($null -ne $vNetNics ) { $tempVNetNICS = [array]($vNetNics) $tempVNetNICS | ForEach-Object{ Set-Variable -Name nic -Scope Local -Value $_ Set-Variable -Name nicproperties -Scope Local -Value $_.Properties $out = ""| Select-Object NICName, VMName, VMId, PrimaryStatus, NetworkSecurityGroupName,NetworkSecurityGroupId, PublicIpAddress, PrivateIpAddress, EnableIPForwarding, IpConfigurations $out.NICName = $nic.Name $out.IpConfigurations = $nicproperties.IpConfigurations $out.EnableIPForwarding = $nicproperties.EnableIPForwarding $PublicIpAddresses = @() $PrivateIpAddresses = @() $nicproperties.IpConfigurations | ForEach-Object{ Set-Variable -Name ipconfiguration -Scope Local -Value $_ if(($ipconfiguration | Get-Member -Name "Properties") -and ($ipconfiguration.Properties | Get-Member -Name "PublicIpAddress") -and $ipconfiguration.Properties.PublicIpAddress) { $IPResource = Get-AzureRmResource -ResourceId $ipconfiguration.Properties.PublicIpAddress.Id $pubResourceName = Get-AzureRmPublicIpAddress -Name $IPResource.Name -ResourceGroupName $IPResource.ResourceGroupName $PublicIpAddresses += $pubResourceName.IpAddress } $PrivateIpAddresses += $ipconfiguration.Properties.PrivateIpAddress } $out.PublicIpAddress = ([System.String]::Join(";",$PublicIpAddresses)) $out.PrivateIpAddress = ([System.String]::Join(";",$PrivateIpAddresses)) if(($nicproperties | Get-Member -Name "VirtualMachine") -and $nicproperties.VirtualMachine ) { $vmresource = Get-AzureRmResource -ResourceId $nicproperties.VirtualMachine.Id $out.VMName = $vmresource.Name } else { $out.VMName = "" } if($null -ne ($nicproperties | Get-Member primary)) { $out.PrimaryStatus = $nicproperties.primary } if(($nicproperties | Get-Member -Name "NetworkSecurityGroup") -and $nicproperties.NetworkSecurityGroup) { $nsgresource = Get-AzureRmResource -ResourceId $nicproperties.NetworkSecurityGroup.Id $out.NetworkSecurityGroupName = $nsgresource.Name } $this.vNetNicsOutput += $out } $this.vNetNicsOutput = [array]($this.vNetNicsOutput) } } return $this.vNetNicsOutput; } }
PowerShellCorpus/PowerShellGallery/AzSDKPreview/2.2.0/Framework/Core/SVT/SubscriptionSecurityStatus.ps1
SubscriptionSecurityStatus.ps1
Set-StrictMode -Version Latest class SubscriptionSecurityStatus: SVTCommandBase { SubscriptionSecurityStatus([string] $subscriptionId, [InvocationInfo] $invocationContext): Base($subscriptionId, $invocationContext) { } hidden [SVTEventContext[]] RunAllControls() { [SVTEventContext[]] $result = @(); $svtClassName = [SVTMapping]::SubscriptionMapping.ClassName $svtObject = New-Object -TypeName $svtClassName -ArgumentList $this.SubscriptionContext.SubscriptionId $this.SetSVTBaseProperties($svtObject); $result += $svtObject.EvaluateAllControls(); [ListenerHelper]::RegisterListeners(); return $result; } }
PowerShellCorpus/PowerShellGallery/AzSDKPreview/2.2.0/Framework/Core/SVT/SVTStatusReport.ps1
SVTStatusReport.ps1
Set-StrictMode -Version Latest class SVTStatusReport : SVTCommandBase { [SVTResourceResolver] $ServicesResolver = $null; SVTStatusReport([string] $subscriptionId, [InvocationInfo] $invocationContext, [SVTResourceResolver] $resolver): Base($subscriptionId, $invocationContext) { if(-not $resolver) { throw [System.ArgumentException] ("The argument 'resolver' is null"); } $this.ServicesResolver = $resolver; $this.ServicesResolver.LoadAzureResources(); } hidden [SVTEventContext[]] RunAllControls() { [SVTEventContext[]] $result = @(); # Run all Subscription security controls try { $this.PublishCustomMessage([Constants]::DoubleDashLine + "`r`nStarted Subscription security controls`r`n" + [Constants]::DoubleDashLine); $sscore = [SubscriptionSecurityStatus]::new($this.SubscriptionContext.SubscriptionId, $this.InvocationContext); if ($sscore) { # Just copy all the tags without validation. Validation will be done internally $sscore.FilterTags = $this.FilterTags; $sscore.ExcludeTags = $this.ExcludeTags; $sscore.ControlIds = $this.ControlIds; $result += $sscore.RunAllControls(); $this.PublishCustomMessage([Constants]::DoubleDashLine + "`r`nCompleted Subscription security controls`r`n" + [Constants]::DoubleDashLine, [MessageType]::Update); } } catch { $this.CommandError($_); } # Run all Azure services security controls try { $this.PublishCustomMessage([Constants]::DoubleDashLine + "`r`nStarted Azure services security controls`r`n" + [Constants]::DoubleDashLine); $secStatus = [ServicesSecurityStatus]::new($this.SubscriptionContext.SubscriptionId, $this.InvocationContext, $this.ServicesResolver); if ($secStatus) { # Just copy all the tags without validation. Validation will be done internally $secStatus.FilterTags = $this.FilterTags; $secStatus.ExcludeTags = $this.ExcludeTags; $secStatus.ControlIds = $this.ControlIds; $result += $secStatus.RunAllControls(); $this.PublishCustomMessage([Constants]::DoubleDashLine + "`r`nCompleted Azure services security controls`r`n" + [Constants]::DoubleDashLine, [MessageType]::Update); } } catch { $this.CommandError($_); } return $result; } }
PowerShellCorpus/PowerShellGallery/AzSDKPreview/2.2.0/Framework/Core/SVT/SVTControlAttestation.ps1
SVTControlAttestation.ps1
Set-StrictMode -Version Latest class SVTControlAttestation { [SVTEventContext[]] $ControlResults = $null hidden [bool] $dirtyCommitState = $false; hidden [bool] $abortProcess = $false; hidden [ControlStateExtension] $controlStateExtension = $null; hidden [AttestControls] $AttestControlsChoice; SVTControlAttestation([SVTEventContext[]] $ctrlResults, [AttestControls] $tempAttestControlsChoice ) { $this.ControlResults = $ctrlResults; $this.AttestControlsChoice = $tempAttestControlsChoice; $this.controlStateExtension = [ControlStateExtension]::new() $this.controlStateExtension.Initialize() } [AttestationStatus] GetAtteststationValue([string] $AttestationCode) { switch($AttestationCode.ToUpper()) { "1" { return [AttestationStatus]::NotAnIssue;} "2" { return [AttestationStatus]::NotFixed;} "9" { $this.abortProcess = $true; return [AttestationStatus]::None; } Default { return [AttestationStatus]::None;} } return [AttestationStatus]::None } [ControlState] ComputeEffectiveControlState([ControlState] $controlState, [ControlSeverity] $ControlSeverity, [bool] $isSubscriptionControl, [SVTEventContext] $controlItem, [ControlResult] $controlResult) { Write-Host "`tControlId : $($controlState.ControlId)`n`tControlSeverity : $ControlSeverity`n`tDescription : $($controlItem.ControlItem.Description)`n`tCurrentControlStatus : $($controlState.ActualVerificationResult)`n" $userChoice = "" $isPrevAttested = $false; if($controlResult.AttestationStatus -ne [AttestationStatus]::None) { $isPrevAttested = $true; } if($isPrevAttested -and ($this.AttestControlsChoice -eq [AttestControls]::All -or $this.AttestControlsChoice -eq [AttestControls]::AlreadyAttested)) { while($userChoice -ne '0' -and $userChoice -ne '1' -and $userChoice -ne '2' -and $userChoice -ne '9' ) { Write-Host "`tPrevious attestation details are as below:`n`tAttestation Status: $($controlState.AttestationStatus)`n`tVerificationResult: $($controlState.EffectiveVerificationResult)`n`tAttested By : $($controlState.State.AttestedBy)`n`tJustification : $($controlState.State.Justification)`n" Write-Host "`tPlease select an action from below: `n`t[0]: None`n`t[1]: Attest`n`t[2]: Clear Attestation" $userChoice = Read-Host "`tUser Choice" $userChoice = $userChoice.Trim(); } } else { while($userChoice -ne '0' -and $userChoice -ne '1' -and $userChoice -ne '9' ) { Write-Host "`tPlease select an action from below: `n`t[0]: None`n`t[1]: Attest" $userChoice = Read-Host "`tUser Choice" $userChoice = $userChoice.Trim(); } } $Justification="" $Attestationstate="" switch ($userChoice.ToUpper()){ "0" #None { } "1" #Attest { $attestationState = "" while($attestationState -ne '0' -and $attestationState -ne '1' -and $attestationState -ne '2' -and $attestationState -ne '9' ) { Write-Host "`n`t`tPlease select an attestation status from below: `n`t`t[0]: None`n`t`t[1]: NotAnIssue`n`t`t[2]: NotFixed" $attestationState = Read-Host "`t`tUser Choice" $attestationState = $attestationState.Trim(); } $attestValue = $this.GetAtteststationValue($attestationState); if($attestValue -ne [AttestationStatus]::None) { $controlState.AttestationStatus = $attestValue; } elseif($this.abortProcess) { return $null; } if($controlState.AttestationStatus -ne [AttestationStatus]::None) { $Justification = Read-Host "`t`tJustification" $this.dirtyCommitState = $true } $controlState.EffectiveVerificationResult = [Helpers]::EvaluateVerificationResult($controlState.ActualVerificationResult,$controlState.AttestationStatus); if($null -eq $controlState.State) { $controlState.State = [StateData]::new() $controlState.State.AttestedBy = [Helpers]::GetCurrentSessionUser(); $controlState.State.AttestedDate = [DateTime]::UtcNow; } $controlState.State.Justification = $Justification break; } "2" #Clear Attestation { $this.dirtyCommitState = $true #Clears the control state. This overrides the previous attested controlstate. $controlState.State = $null; $controlState.EffectiveVerificationResult = $controlState.ActualVerificationResult $controlState.AttestationStatus = [AttestationStatus]::None } "9" #Abort { $this.abortProcess = $true; return $null; } Default { } } return $controlState; } [void] StartControlAttestation() { try { Write-Host $([Constants]::HashLine) -ForegroundColor Green Write-Host "Starting Control Attestation workflow...`n" -ForegroundColor Cyan Write-Host "Note: Enter 9 during the attestation workflow to abort." if($null -eq $this.ControlResults) { Write-Host "No control results found." -ForegroundColor Yellow } $this.abortProcess = $false; #filtering the controls - Removing all the passed controls #Step1 Group By IDs $filteredControlResults = @() $filteredControlResults += $this.ControlResults | Group-Object { $_.GetUniqueId() } #show warning if the keys count is greater than certain number. #start iterating resource after resource $filteredControlResults | ForEach-Object { $resource = $_; $resourceValueKey = $_.Name $this.dirtyCommitState = $false; $resourceValue = $resource.Group; $isSubscriptionScan = $false; if(($resourceValue | Measure-Object).Count -gt 0) { $SubscriptionId = $resourceValue[0].SubscriptionContext.SubscriptionId if($null -ne $resourceValue[0].ResourceContext) { $ResourceId = $resourceValue[0].ResourceContext.ResourceId Write-Host $([String]::Format([Constants]::ModuleAttestStartHeading, $resourceValue[0].FeatureName, $resourceValue[0].ResourceContext.ResourceGroupName, $resourceValue[0].ResourceContext.ResourceName)) -ForegroundColor Cyan } else { $isSubscriptionScan = $true; Write-Host $([String]::Format([Constants]::ModuleAttestStartHeadingSub, $resourceValue[0].FeatureName, $resourceValue[0].SubscriptionContext.SubscriptionName, $resourceValue[0].SubscriptionContext.SubscriptionId)) -ForegroundColor Cyan } [ControlState[]] $resourceControlStates = @() $count = 0; [SVTEventContext[]] $filteredControlItems = @() $resourceValue | ForEach-Object { $controlItem = $_; $matchedControlItem = $false; if(($controlItem.ControlResults | Measure-Object).Count -gt 0) { [ControlResult[]] $matchedControlResults = @(); $controlItem.ControlResults | ForEach-Object { $controlResult = $_ if($controlResult.ActualVerificationResult -ne [VerificationResult]::Passed) { if($this.AttestControlsChoice -eq [AttestControls]::All) { $matchedControlItem = $true; $matchedControlResults += $controlResult; $count++; } elseif($this.AttestControlsChoice -eq [AttestControls]::AlreadyAttested -and $controlResult.AttestationStatus -ne [AttestationStatus]::None) { $matchedControlItem = $true; $matchedControlResults += $controlResult; $count++; } elseif($this.AttestControlsChoice -eq [AttestControls]::NotAttested -and $controlResult.AttestationStatus -eq [AttestationStatus]::None) { $matchedControlItem = $true; $matchedControlResults += $controlResult; $count++; } } } } if($matchedControlItem) { $controlItem.ControlResults = $matchedControlResults; $filteredControlItems += $controlItem; } } if($count -gt 0) { Write-Host "`tNo. of controls that need to be attested: $count`n$([Constants]::SingleDashLine)" foreach( $controlItem in $filteredControlItems) { $controlId = $controlItem.ControlItem.ControlID $controlSeverity = $controlItem.ControlItem.ControlSeverity $controlResult = $null; $controlStatus = ""; $isPrevAttested = $false; if(($controlItem.ControlResults | Measure-Object).Count -gt 0) { #Assuming that there would be only one control result for each control id. Multi control results scenario need to revisited foreach( $controlResult in $controlItem.ControlResults) { $controlStatus = $controlResult.ActualVerificationResult; [ControlState] $controlState = [ControlState]::new($controlId,$controlItem.ControlItem.Id,$controlResult.ChildResourceName,$controlStatus,"1.0"); if($null -ne $controlResult.StateManagement -and $null -ne $controlResult.StateManagement.AttestedStateData) { $controlState.State = $controlResult.StateManagement.AttestedStateData } $controlState.AttestationStatus = $controlResult.AttestationStatus $controlState.EffectiveVerificationResult = $controlResult.VerificationResult $controlState = $this.ComputeEffectiveControlState($controlState, $controlSeverity, $isSubscriptionScan, $controlItem, $controlResult) $resourceControlStates +=$controlState; if($this.abortProcess) { Write-Host "`tAborted the attestation workflow." return $null; } } } Write-Host $([Constants]::SingleDashLine) -ForegroundColor Cyan } } else { Write-Host "`tNo attestable controls found.`n$([Constants]::SingleDashLine)" } #remove the entries which doesnt have any state #$resourceControlStates = $resourceControlStates | Where-Object {$_.State} #persist the value back to state if($this.dirtyCommitState) { if(($resourceControlStates | Measure-Object).Count -gt 0) { Write-Host "`tSummary:" $output = @() $resourceControlStates | ForEach-Object { $out = "" | Select-Object ControlId, ActualVerificationResult, EffectiveVerificationResult, AttestationStatus $out.ControlId = $_.ControlId $out.ActualVerificationResult = $_.ActualVerificationResult $out.EffectiveVerificationResult = $_.EffectiveVerificationResult $out.AttestationStatus = $_.AttestationStatus.ToString() $output += $out } Write-Host ($output | FT ControlId, ActualVerificationResult, EffectiveVerificationResult, AttestationStatus | Out-String) } $this.controlStateExtension.SetControlState($resourceValueKey, $resourceControlStates, $false) Write-Host "`tSuccessfully persisted the attestation." } if($null -ne $resourceValue[0].ResourceContext) { $ResourceId = $resourceValue[0].ResourceContext.ResourceId Write-Host $([String]::Format([Constants]::CompletedAttestAnalysis, $resourceValue[0].FeatureName, $resourceValue[0].ResourceContext.ResourceGroupName, $resourceValue[0].ResourceContext.ResourceName)) -ForegroundColor Cyan } else { $isSubscriptionScan = $true; Write-Host $([String]::Format([Constants]::CompletedAttestAnalysisSub, $resourceValue[0].FeatureName, $resourceValue[0].SubscriptionContext.SubscriptionName, $resourceValue[0].SubscriptionContext.SubscriptionId)) -ForegroundColor Cyan } } } } finally { $this.controlStateExtension.CleanTempFolder(); } } }
PowerShellCorpus/PowerShellGallery/AzSDKPreview/2.2.0/Framework/Core/SVT/SVTResourceResolver.ps1
SVTResourceResolver.ps1
Set-StrictMode -Version Latest class SVTResourceResolver: AzSdkRoot { [string] $ResourceName = ""; [string] $ResourceType = ""; [ResourceTypeName] $ResourceTypeName = [ResourceTypeName]::All; [Hashtable] $Tag = $null; [string] $TagName = ""; [string] $TagValue = ""; hidden [string[]] $ResourceGroups = @(); [SVTResource[]] $SVTResources = @(); # Indicates to fetch all resource groups SVTResourceResolver([string] $subscriptionId): Base($subscriptionId) { } SVTResourceResolver([string] $subscriptionId, [string] $resourceGroupNames): Base($subscriptionId) { if(-not [string]::IsNullOrEmpty($resourceGroupNames)) { $this.ResourceGroups += $this.ConvertToStringArray($resourceGroupNames); if ($this.ResourceGroups.Count -eq 0) { throw [System.ArgumentException] "The parameter 'resourceGroupNames' does not contain any string." } } } [void] LoadAzureResources() { #Lazy load the SVT resource array if($this.SVTResources.Count -eq 0) { $resources = @(); #Fetch Resources from Azure if($this.ResourceGroups.Count -eq 0) { #Target resource group param is not passed. Pass appropriate input params $resources += $this.FindAzureRmResource(""); } else { #Fetch resorces for all resource groups $this.ResourceGroups | ForEach-Object { $resouresFound = $this.FindAzureRmResource($_ ); if(($resouresFound | Measure-Object).Count -eq 0) { $this.PublishCustomMessage("Could not find any resources under Resource Group [$_]", [MessageType]::Warning); } else { $resources += $resouresFound; } } } if($resources.Count -eq 0) { throw "Could not find any resources that match the specified criteria." } $allResourceTypes = [string[]] [ConfigurationManager]::LoadServerConfigFile("AllResourceTypes.json"); $resources | ForEach-Object { $resType = $_.ResourceType; $svtResource = [SVTResource]::new(); $svtResource.ResourceId = $_.ResourceId; $svtResource.ResourceGroupName = $_.ResourceGroupName; $svtResource.ResourceName = $_.ResourceName; $svtResource.ResourceType = $resType; $svtResource.Location = $_.Location; if($this.ResourceTypeName -ne [ResourceTypeName]::All) { $svtResource.ResourceTypeMapping = ([SVTMapping]::Mapping | Where-Object { $_.ResourceTypeName -eq $this.ResourceTypeName } | Select-Object -First 1); } else { $svtResource.ResourceTypeMapping = ([SVTMapping]::Mapping | Where-Object { $_.ResourceType -eq $resType } | Select-Object -First 1); } $ignoredType = $false; if(-not $svtResource.ResourceTypeMapping) { $ignoredType = [string]::IsNullOrEmpty(($allResourceTypes | Where-Object { $_ -eq $resType } | Select-Object -First 1)); } if(-not $ignoredType) { $this.SVTResources += $svtResource; } } } } hidden [System.Object[]] FindAzureRmResource([string] $resourceGroupName) { $expression = "Find-AzureRmResource"; if(-not [string]::IsNullOrEmpty($resourceGroupName)) { $expression += " -ResourceGroupNameEquals '$resourceGroupName' " ; } if([string]::IsNullOrEmpty($this.ResourceType) -and ($this.ResourceTypeName -ne [ResourceTypeName]::All)) { $mapping = ([SVTMapping]::Mapping | Where-Object { $_.ResourceTypeName -eq $this.ResourceTypeName.ToString() } | Select-Object -First 1); if($mapping) { $this.ResourceType = $mapping.ResourceType; } } if(-not [string]::IsNullOrEmpty($this.ResourceType)) { $expression += " -ResourceType '$($this.ResourceType)' " ; } if(-not [string]::IsNullOrEmpty($this.ResourceName)) { $expression += " -ResourceNameEquals '$($this.ResourceName)' " ; } if($this.Tag -and $this.Tag.Count -ne 0) { $tagValues = ""; $this.Tag.GetEnumerator() | ForEach-Object { $tagValues += "'$($_.Name)'='$($_.Value)'; " }; $expression += " -Tag @{ $tagValues }" ; } elseif((-not [string]::IsNullOrEmpty($this.TagName)) -and (-not [string]::IsNullOrEmpty($this.TagValue))) { $expression += " -TagName '$($this.TagName)' -TagValue '$($this.TagValue)'" ; } $result = @(); $expressionResult = Invoke-Expression $expression if($expressionResult) { $result += $expressionResult } return $result; } }
PowerShellCorpus/PowerShellGallery/AzSDKPreview/2.2.0/Framework/Core/SVT/SubscriptionCore/SubscriptionCore.ps1
SubscriptionCore.ps1
#using namespace Microsoft.Azure.Commands.Search.Models Set-StrictMode -Version Latest class SubscriptionCore: SVTBase { hidden [AzureSecurityCenter] $ASCSettings hidden [ManagementCertificate[]] $ManagementCertificates hidden [PSObject] $RoleAssignments hidden [PSObject] $ApprovedAdmins; hidden [PSObject] $MandatoryAccounts; hidden [PSObject] $DeprecatedAccounts; hidden [PSObject] $CurrentContext; hidden [bool] $HasGraphAPIAccess; SubscriptionCore([string] $subscriptionId): Base($subscriptionId) { $this.GetResourceObject(); } hidden [void] GetResourceObject() { $this.ASCSettings = [AzureSecurityCenter]::new() $this.CurrentContext = Get-AzureRmContext -ErrorAction Ignore $this.MandatoryAccounts = $null $this.RoleAssignments = $null $this.ApprovedAdmins = $null $this.DeprecatedAccounts = $null $this.HasGraphAPIAccess = [RoleAssignmentHelper]::HasGraphAccess() } hidden [ControlResult] CheckSubscriptionAdminCount([ControlResult] $controlResult) { $this.GetRoleAssignments() $this.LoadRBACConfig() #Excessive number of admins (> 5) $scope = $this.SubscriptionContext.Scope; $SubAdmins = @(); $SubAdmins += $this.RoleAssignments | Where-Object { $_.RoleDefinitionName -eq 'CoAdministrator' ` -or $_.RoleDefinitionName -like '*ServiceAdministrator*' ` -or ($_.RoleDefinitionName -eq 'Owner' -and $_.Scope -eq $scope)} if($this.HasGraphAPIAccess -eq $false) { $this.PublishCustomMessage("Current Azure login context doesn't have graph api access"); } $ClientSubAdmins = @() $ApprovedSubAdmins = @() $SubAdmins | ForEach-Object{ $tempAdmin = $_ $objId = $_.ObjectId $isApprovedAdmin = $false foreach($admin in $this.ApprovedAdmins) { $tempObjId = $admin.ObjectId if($admin.ObjectType -eq "ServicePrincipal") { $out = $null #do we need to check for scope try { $out = $this.RoleAssignments | Where-Object { $_.ObjectId -eq $admin.ObjectId} } catch {} if($null -ne $out) { $tempObjId = $out[0].ObjectId } } if($objId -eq $tempObjId) { $ApprovedSubAdmins += $tempAdmin $isApprovedAdmin = $true } } if(-not $isApprovedAdmin) { $ClientSubAdmins += $tempAdmin } } #$controlResult.AddMessage("There are a total of $($SubAdmins.Count) admin/owner accounts in your subscription`r`nOf these, the following $($ClientSubAdmins.Count) admin/owner accounts are not from a central team.", ($ClientSubAdmins | Select-Object DisplayName,SignInName,ObjectType, ObjectId), $true, "ClientSubAdmins"); $controlResult.AddMessage("There are a total of $($SubAdmins.Count) admin/owner accounts in your subscription`r`nOf these, the following $($ClientSubAdmins.Count) admin/owner accounts are not from a central team.", ($ClientSubAdmins | Select-Object DisplayName,SignInName,ObjectType, ObjectId)); if(($ApprovedSubAdmins | Measure-Object).Count -gt 0) { #$controlResult.AddMessage("The following $($ApprovedSubAdmins.Count) admin/owner (approved) accounts are from a central team:`r`n", ($ApprovedSubAdmins | Select-Object DisplayName, SignInName, ObjectType, ObjectId), $true, "ApprovedSubAdmins"); $controlResult.AddMessage("The following $($ApprovedSubAdmins.Count) admin/owner (approved) accounts are from a central team:`r`n", ($ApprovedSubAdmins | Select-Object DisplayName, SignInName, ObjectType, ObjectId)); } $controlResult.AddMessage("Note: Approved central team accounts don't count against your limit"); #$ClientSubAdminsState = $this.GetControlState("ClientSubAdmins", $this.CurrentControlItem.ControlID) #[bool] $IsStateCheckEnabled = $true #[bool] $isMatch = $true; #if($ClientSubAdminsState -ne $null -and ($ClientSubAdminsState | Get-Member DataObject) -ne $null -and $ClientSubAdminsState.DataObject -ne $null -and ($ClientSubAdminsState.DataObject | Measure-Object).Count -gt 0) #{ # if($ClientSubAdminsState.DataObject.Count -eq ($ClientSubAdmins | Measure-Object).Count) # { # $ClientSubAdmins | ForEach-Object { # $clientSubAdmin = $_ # if(($ClientSubAdminsState.DataObject.value | Where-Object { $_.ObjectId -eq $clientSubAdmin.ObjectId} | Measure-Object).Count -le 0) # { # $isMatch = $false # } # } # } # else # { # $isMatch = $false # } #} #if($isMatch) #{ # $ApprovedSubAdminsState = $this.GetControlState("ApprovedSubAdmins", $this.CurrentControlItem.ControlID) # if($ApprovedSubAdminsState -ne $null -and ($ApprovedSubAdminsState | Get-Member DataObject) -ne $null -and $ApprovedSubAdminsState.DataObject -ne $null -and ($ApprovedSubAdminsState.DataObject | Measure-Object).Count -gt 0) # { # if($ApprovedSubAdminsState.DataObject.Count -eq ($ApprovedSubAdmins | Measure-Object).Count) # { # $ApprovedSubAdmins | ForEach-Object { # $approvedSubAdmin = $_ # if(($ApprovedSubAdminsState.DataObject.value | Where-Object { $_.ObjectId -eq $approvedSubAdmin.ObjectId} | Measure-Object).Count -le 0) # { # $isMatch = $false # } # } # } # else # { # $isMatch = $false # } # } #} if($ClientSubAdmins.Count -gt $this.ControlSettings.NoOfApprovedAdmins) { $controlResult.VerificationResult = [VerificationResult]::Failed $controlResult.AddMessage("Number of admins/owners configured at subscription scope are more than the approved limit: $($this.ControlSettings.NoOfApprovedAdmins). Total: " + $ClientSubAdmins.Count); } else { $controlResult.AddMessage([VerificationResult]::Passed, "Number of admins/owners configured at subscription scope are with in approved limit: $($this.ControlSettings.NoOfApprovedAdmins). Total: " + $ClientSubAdmins.Count); } return $controlResult; } hidden [ControlResult] CheckApprovedCentralAccountsRBAC([ControlResult] $controlResult) { $this.GetRoleAssignments() $this.LoadRBACConfig() $state = $true $scope = $this.SubscriptionContext.Scope $out = $null $missingMandatoryAccount = @() $foundMandatoryAccount = @() if($null -ne $this.MandatoryAccounts) { foreach($admin in $this.MandatoryAccounts) { try{ $out = $this.RoleAssignments | Where-Object { $_.ObjectId -eq $admin.ObjectId -and $_.Scope -eq $scope -and $_.RoleDefinitionName -eq $admin.RoleDefinitionName }} catch { } if($null -eq $out) { $missingMandatoryAccount+= $admin $state = $false } else { $foundMandatoryAccount += $admin } } if(($foundMandatoryAccount | Measure-Object).Count -gt 0) { #$controlResult.AddMessage("Found mandatory accounts:",$foundMandatoryAccount, $true, "FoundMandatoryAccounts") $controlResult.AddMessage("Found mandatory accounts:",$foundMandatoryAccount) } if(($missingMandatoryAccount | Measure-Object).Count -gt 0) { #$controlResult.AddMessage("Missing mandatory accounts:",$missingMandatoryAccount, $true, "MissingMandatoryAccounts") $controlResult.AddMessage("Missing mandatory accounts:",$missingMandatoryAccount) } } if(-not $state) { $controlResult.VerificationResult = [VerificationResult]::Failed; } else { $controlResult.VerificationResult = [VerificationResult]::Passed } return $controlResult } hidden [ControlResult] CheckDeprecatedAccountsRBAC([ControlResult] $controlResult) { $this.GetRoleAssignments() $this.LoadRBACConfig() $state = $true $scope = $this.SubscriptionContext.Scope $depCounter = 0 $out = $null $foundDeprecatedAccounts = @() if($null -ne $this.DeprecatedAccounts) { foreach($depAcct in $this.DeprecatedAccounts) { try{ $out = $this.RoleAssignments | Where-Object { $_.ObjectId -eq $depAcct.ObjectId} } catch { } if($null -ne $out) { #$controlResult.AddMessage("`r`nFound deprecated account: [User] [$($depAcct.Name )] Type:[$($depAcct.ObjectType)]",$out) $foundDeprecatedAccounts += $depAcct $depCounter++ $state = $false } } } if(-not $state) { #$controlResult.AddMessage([VerificationResult]::Failed, "Found deprecated accounts on the subscription:", $foundDeprecatedAccounts, $true, "DeprecatedAccounts") $controlResult.AddMessage([VerificationResult]::Failed, "Found deprecated accounts on the subscription:", $foundDeprecatedAccounts) } else { $controlResult.VerificationResult = [VerificationResult]::Passed } return $controlResult } hidden [ControlResult] CheckNonAADAccountsRBAC([ControlResult] $controlResult) { if($this.HasGraphAPIAccess) { $this.GetRoleAssignments() Set-Variable -Name liveAccounts -Scope Local $liveAccounts = [array]($this.RoleAssignments | Where-Object {$_.SignInName -like '*#EXT#@*.onmicrosoft.com'} ) if(($liveAccounts | Measure-Object).Count -gt 0) { $controlResult.AddMessage([VerificationResult]::Failed, "Found non-AAD account access present on the subscription:",($liveAccounts | Select-Object SignInName,DisplayName, Scope, RoleDefinitionName)) #$controlResult.AddMessage([VerificationResult]::Failed, "Found non-AAD account access present on the subscription:",($liveAccounts | Select-Object SignInName,DisplayName, Scope, RoleDefinitionName), $true, "NonAADAccounts") $controlResult.VerificationResult =[VerificationResult]::Failed } else { $controlResult.VerificationResult =[VerificationResult]::Passed } } else { $controlResult.AddMessage([VerificationResult]::Manual, "Not able to query Graph API. This has to be manually verified."); } return $controlResult } hidden [ControlResult] CheckSVCAccountsRBAC([ControlResult] $controlResult) { if($this.HasGraphAPIAccess) { $this.GetRoleAssignments() $serviceAccounts = @() if($null -ne $this.CurrentContext) { $GraphAccessToken = [Helpers]::GetAccessToken([WebRequestHelper]::GraphAPIUri) } $uniqueUsers = @(); $uniqueUsers += $this.RoleAssignments | Sort-Object SignInName -Unique | Select-Object DisplayName, SignInName,ObjectId, ObjectType $uniqueUsers | ForEach-Object{ Set-Variable -Name user -Scope Local -Value $_ Set-Variable -Name ObjectId -Scope Local -Value $_.ObjectId Set-Variable -Name SignInName -Scope Local -Value $_.SignInName Set-Variable -Name ObjectType -Scope Local -Value $_.ObjectType $isServiceAccount = [IdentityHelpers]::IsServiceAccount($_.ObjectId, $_.SignInName, $_.ObjectType, $GraphAccessToken) if($isServiceAccount) { $userScopes = $this.RoleAssignments | Where-Object {$_.SignInName -eq $SignInName} $userScopes | ForEach-Object{ Set-Variable -Name userScope -Scope Local -Value $_ $serviceAccounts += $userScope } } } if(($serviceAccounts | Measure-Object).Count -gt 0) { $serviceAccounts = $serviceAccounts | Where-Object {-not ($_.SignInName -like 'Sc-*')} } if(($serviceAccounts | Measure-Object).Count -gt 0) { #$controlResult.AddMessage([VerificationResult]::Failed, "Found non-MFA enabled accounts present on the subscription",($serviceAccounts | Select-Object Scope, DisplayName, SignInName, RoleDefinitionName, ObjectId, ObjectType), $true, "NonMFAAccounts") $controlResult.AddMessage([VerificationResult]::Failed, "Found non-MFA enabled accounts present on the subscription",($serviceAccounts | Select-Object Scope, DisplayName, SignInName, RoleDefinitionName, ObjectId, ObjectType)); } else { $controlResult.VerificationResult =[VerificationResult]::Passed } } else { $controlResult.AddMessage([VerificationResult]::Manual, "Not able to query Graph API. This has to be manually verified."); } return $controlResult } hidden [ControlResult] CheckCoAdminCount([ControlResult] $controlResult) { $this.GetRoleAssignments() Set-Variable -Name classicCoAdmins -Scope Local $classicCoAdmins = $this.RoleAssignments | Where-Object { $_.RoleDefinitionName -eq 'CoAdministrator' ` -or $_.RoleDefinitionName -like '*ServiceAdministrator*' } $count = ($classicCoAdmins | Measure-Object).Count #$controlResult.AddMessage("No. of CoAdministrators found: $count", ($classicCoAdmins | Select-Object DisplayName, Scope, ObjectType, ObjectId), $true, "CoAdminsList") $controlResult.AddMessage("No. of CoAdministrators found: $count", ($classicCoAdmins | Select-Object DisplayName, Scope, ObjectType, ObjectId)) if($count -gt $this.ControlSettings.NoOfClassicAdminsLimit) { $controlResult.VerificationResult = [VerificationResult]::Failed } else { $controlResult.VerificationResult =[VerificationResult]::Passed } return $controlResult } hidden [ControlResult] CheckManagementCertsPresence([ControlResult] $controlResult) { try { $this.GetManagementCertificates() if($this.ControlSettings.WhitelistedMgmtCerts | Get-Member -Name "Thumbprints") { $this.ManagementCertificates | ForEach-Object { Set-Variable -Name certObject -Value $_ -Scope Local if(($this.ControlSettings.WhitelistedMgmtCerts.Thumbprints | Where-Object {$_ -eq $certObject.CertThumbprint} | Measure-Object).Count -gt 0 -and $certObject.Difference.Days -le $this.ControlSettings.WhitelistedMgmtCerts.ApprovedValidityRangeInDays) { $certObject.Whitelisted = $true } } } $FilteredMgmtCerts = @(); $FilteredMgmtCerts += $this.ManagementCertificates | Where {-not $_.Whitelisted} Set-Variable -Name isCompliant -Scope Local if($null -ne $FilteredMgmtCerts -and $FilteredMgmtCerts.Count -gt 0) { #$controlResult.AddMessage([VerificationResult]::Failed,"Found Management certificates on the subscription.",($this.ManagementCertificates | Select-Object CertThumbprint, SubjectName, Issuer, Created , ExpiryDate , IsExpired, Whitelisted), $true, "MgmtCerts") $controlResult.AddMessage([VerificationResult]::Failed,"Found Management certificates on the subscription.",($this.ManagementCertificates | Select-Object CertThumbprint, SubjectName, Issuer, Created , ExpiryDate , IsExpired, Whitelisted)) } else { $controlResult.VerificationResult = [VerificationResult]::Passed } } catch { $controlResult.AddMessage([VerificationResult]::Manual,"Doesn't have required permissions to check management certificates on this subscription.") } return $controlResult } hidden [ControlResult] CheckAzureSecurityCenterSettings([ControlResult] $controlResult) { $secCenter = [SecurityCenter]::new($this.SubscriptionContext.SubscriptionId); if ($secCenter) { $controlResult.AddMessage([MessageData]::new("Security center policies must be configured with settings mentioned below:", $secCenter.Policy.properties)); $misConfiguredPolicies = $secCenter.GetMisconfiguredPolicies(); if($misConfiguredPolicies.Count -ne 0) { $controlResult.AddMessage([VerificationResult]::Failed, [MessageData]::new("Following security center policies are not correctly configured. Please update the policies in order to comply.", $misConfiguredPolicies)); } else { $controlResult.AddMessage([VerificationResult]::Passed, [MessageData]::new("All security center policies are correctly configured.")); } } return $controlResult } hidden [ControlResult] CheckAzureSecurityCenterAlerts([ControlResult] $controlResult) { $this.GetASCAlerts() $activeAlerts = ($this.ASCSettings.Alerts | Where-Object {$_.State -eq "Active"}) if(($activeAlerts | Measure-Object).Count -gt 0) { $controlResult.AddMessage([VerificationResult]::Failed,"Azure Security Center have active alerts that need to resolved.") } else { $controlResult.VerificationResult =[VerificationResult]::Passed } $controlResult.AddMessage(($activeAlerts | Select-Object State, AlertDisplayName, AlertName, Description, ReportedTimeUTC, RemediationSteps)) return $controlResult } hidden [ControlResult] CheckAzureSecurityCenterRecommendations([ControlResult] $controlResult) { $this.GetASCTasks() $activeRecommendations = ($this.ASCSettings.Tasks | Where-Object {$_.State -eq "Active"}) if(($activeRecommendations | Measure-Object).Count -gt 0) { $controlResult.AddMessage([VerificationResult]::Failed,"Azure Security Center have actives recommendations that need to resolved.") } else { $controlResult.VerificationResult =[VerificationResult]::Passed } $controlResult.AddMessage(($activeRecommendations | Select-Object Name, State, ResourceId)); return $controlResult } hidden [ControlResult] CheckSPNsRBAC([ControlResult] $controlResult) { if($this.HasGraphAPIAccess) { $this.GetRoleAssignments() $scope = $this.SubscriptionContext.Scope $servicePrincipalNames = $this.RoleAssignments | Where-Object {$_.ObjectType -eq "ServicePrincipal" -and ($_.RoleDefinitionName -eq "Owner" -or $_.RoleDefinitionName -eq "Contributor") -and $_.Scope -eq $scope} if(($servicePrincipalNames | Measure-Object).Count -gt 0) { $controlResult.VerificationResult = [VerificationResult]::Failed #$controlResult.AddMessage("Below is the list SPNs which have either owner or contributor access on subscription:", ($servicePrincipalNames | Select-Object DisplayName, SignInName,ObjectType), $true, "CriticalSPNs") $controlResult.AddMessage("Below is the list SPNs which have either owner or contributor access on subscription:", ($servicePrincipalNames | Select-Object DisplayName, SignInName,ObjectType)) } else { $controlResult.VerificationResult =[VerificationResult]::Passed } } else { $controlResult.AddMessage([VerificationResult]::Manual, "Not able to query Graph API. This has to be manually verified."); } return $controlResult } hidden [ControlResult] CheckResourceLocksUsage([ControlResult] $controlResult) { $foundLocks = $true $lockDtls = $null #Command will throw exception if no locks found try { $lockDtls = Get-AzureRmResourceLock -ErrorAction Stop # -Scope "/subscriptions/$SubscriptionId" } catch { $foundLocks = $false } if($null -eq $lockDtls) { $foundLocks = $false } if($foundLocks) { #$controlResult.AddMessage([VerificationResult]::Verify, "Subscription lock details :", ($lockDtls | Select-Object Name, @{Name="Lock Level";Expression={$_.Properties.level}}, LockId, @{Name="Notes";Expression={$_.Properties.notes}} ), $true, "SubscriptionLocks") $controlResult.AddMessage([VerificationResult]::Verify, "Subscription lock details :", ($lockDtls | Select-Object Name, @{Name="Lock Level";Expression={$_.Properties.level}}, LockId, @{Name="Notes";Expression={$_.Properties.notes}} )) } else { $controlResult.AddMessage([VerificationResult]::Failed, "There are no resource locks present on the subscription."); } return $controlResult } hidden [ControlResult] CheckARMPoliciesCompliance([ControlResult] $controlResult) { $UserTags = @() $UserTags += "mandatory" $subARMPolConfig = $this.LoadServerConfigFile("Subscription.ARMPolicies.json") $output = @() $foundMandatoryPolicies = $true if($null -ne $subARMPolConfig) { $subARMPolConfig = [array]($subARMPolConfig) $subARMPolConfig | ForEach-Object{ Set-Variable -Name pol -Scope Local -Value $_ Set-Variable -Name polEnabled -Scope Local -Value $_.enabled Set-Variable -Name policyDefinitionName -Scope Local -Value $_.policyDefinitionName Set-Variable -Name tags -Scope Local -Value $_.tags $haveMatchedTags = ((($tags | Where-Object { $UserTags.Contains($_.Trim().ToLower()) }) | Measure-Object).Count -gt 0) if($polEnabled -and $haveMatchedTags) { $mandatoryPolicies = [array](Get-AzureRMPolicyAssignment | Where-Object {$_.Name -eq $policyDefinitionName}) if($null -eq $mandatoryPolicies -or ($mandatoryPolicies | Measure-Object).Count -le 0) { $foundMandatoryPolicies = $false $output += $pol } } } } if($foundMandatoryPolicies) { $controlResult.AddMessage([VerificationResult]::Passed, "Found all the mandatory policies on the Subscription."); } else { $controlResult.AddMessage([VerificationResult]::Failed, "Some of the mandatory policies are missing which are demanded by the control tags [$UserTags]", $output); } return $controlResult } hidden [ControlResult] CheckCriticalAlertsPresence([ControlResult] $controlResult) { $UserTags = @() $UserTags += "mandatory" $output = @() $subInsightsAlertsConfig = $this.LoadServerConfigFile("Subscription.InsAlerts.json") $foundRequiredAlerts = $true if($null -ne $subInsightsAlertsConfig) { $subInsightsAlertsConfig =[array]($subInsightsAlertsConfig) $AlertsPkgRG = "AzSDKAlertsRG" $alertsRG = [array] (Get-AzureRmResourceGroup | Where-Object {$_.ResourceGroupName -match "^$AlertsPkgRG"}) $configuredAlerts = $null if (($alertsRG | Measure-Object).Count -eq 1) { $configuredAlerts = Get-AzureRmAlertRule -ResourceGroup $AlertsPkgRG } if((($alertsRG | Measure-Object).Count -eq 1) -and ($null -ne $configuredAlerts)){ $subInsightsAlertsConfig | ForEach-Object{ Set-Variable -Name alert -Scope Local -Value $_ Set-Variable -Name alertEnabled -Scope Local -Value $_.Enabled Set-Variable -Name alertName -Scope Local -Value $_.Name Set-Variable -Name tags -Scope Local -Value $_.Tags $haveMatchedTags = ((($tags | Where-Object { $UserTags.Contains($_.Trim().ToLower()) }) | Measure-Object).Count -gt 0) if($alertEnabled -and $haveMatchedTags) { $foundAlert = [array]($configuredAlerts | Where-Object {$_.Name -eq $alertName}) if($null -eq $foundAlert -or ($foundAlert | Measure-Object).Count -le 0) { $foundRequiredAlerts = $false $output += $alert } } } } else { $foundRequiredAlerts = $false } } if($foundRequiredAlerts) { $controlResult.AddMessage([VerificationResult]::Passed, "Insights alerts has been configured on the subscription."); } else { $controlResult.AddMessage([VerificationResult]::Failed, "Missing mandatory critical alerts on the subcription.", $output); } return $controlResult } hidden [ControlResult] CheckCustomRBACRolesPresence([ControlResult] $controlResult) { $this.GetRoleAssignments() $out = @() $output = @() Get-AzureRmRoleDefinition -Custom | ForEach-Object{ Set-Variable -Name RoleDefn -Value $_ $out = "" | Select-Object RoleDefinitionName, RoleAssignmentScope $RoleAssignments = [array]($this.RoleAssignments | Where-Object { $_.RoleDefinitionId -eq $RoleDefn.Id}) if($null -ne $RoleAssignments -and $RoleAssignments.Length -gt 0) { $RoleAssignments | ForEach-Object{ Set-Variable -Name RoleAssignment -Value $_ $out.RoleDefinitionName = $RoleDefn.Name $out.RoleAssignmentScope = $RoleAssignment.Scope $output+= $out } } else { $out.RoleDefinitionName = $RoleDefn.Name $out.RoleAssignmentScope = "UnAssigned" $output+= $out } } $output = [array]($output) if($null -ne $output -and $output.Length -gt 0) { #$controlResult.AddMessage([VerificationResult]::Verify, "Found custom RBAC definitions`r`nNo. of custom RBAC roles: $($output.Length)", $output, $true, "CustomRBAC") $controlResult.AddMessage([VerificationResult]::Verify, "Found custom RBAC definitions`r`nNo. of custom RBAC roles: $($output.Length)", $output) } else { $controlResult.VerificationResult = [VerificationResult]::Passed } return $controlResult } hidden [ControlResult] CheckPresenceOfClassicResources([ControlResult] $controlResult) { $classicResources = [array] (Get-AzureRMResource | Where-Object {$_.ResourceType -like "*classic*"} ) if(($classicResources | Measure-Object).Count -gt 0) { #$controlResult.AddMessage([VerificationResult]::Failed, "Found classic resources on the susbcription.", $classicResources, $true, "ClassicResources") $controlResult.AddMessage([VerificationResult]::Failed, "Found classic resources on the susbcription.", $classicResources) } else { $controlResult.VerificationResult = [VerificationResult]::Passed } return $controlResult } hidden [void] LoadRBACConfig() { if($null -eq $this.MandatoryAccounts` -or $null -eq $this.ApprovedAdmins` -or $null -eq $this.DeprecatedAccounts` ) { $this.MandatoryAccounts = @() $this.ApprovedAdmins = @() $subRBACConfig = $this.LoadServerConfigFile("Subscription.RBAC.json") if($null -ne $subRBACConfig) { $subRBACConfig.ValidActiveAccounts | Where-Object {$_.Enabled} | ForEach-Object{ if($_.RoleDefinitionName -eq "Owner") { $this.ApprovedAdmins += $_ } if(($_.Tags | Where-Object {$_ -eq "Mandatory"} | Measure-Object).Count -gt 0) { $this.MandatoryAccounts += $_ } } } $this.DeprecatedAccounts = $subRBACConfig.DeprecatedAccounts | Where-Object {$_.Enabled} } } hidden [void] GetRoleAssignments() { if($null -eq $this.RoleAssignments) { $this.RoleAssignments = [RoleAssignmentHelper]::GetAzSDKRoleAssignment($true,$true) } } hidden [void] GetManagementCertificates() { $ResourceAppIdURI = [WebRequestHelper]::ClassicManagementUri; $ClassicAccessToken = [Helpers]::GetAccessToken($ResourceAppIdURI) if($null -ne $ClassicAccessToken) { $header = "Bearer " + $ClassicAccessToken $headers = @{"Authorization"=$header;"Content-Type"="application/json"; "x-ms-version" ="2013-08-01"} $uri = [string]::Format("{0}/{1}/certificates","https://management.core.windows.net",$this.SubscriptionContext.SubscriptionId) $mgmtCertsResponse = Invoke-WebRequest -Method GET -Uri $uri -Headers $headers -UseBasicParsing if($mgmtCertsResponse.StatusCode -ge 200 -and $mgmtCertsResponse.StatusCode -le 399) { if($null -ne $mgmtCertsResponse.Content) { [xml] $mgmtCerts = $mgmtCertsResponse.Content; $this.ManagementCertificates = @(); if($null -ne $mgmtCerts -and [Helpers]::CheckMember($mgmtCerts, "SubscriptionCertificates.SubscriptionCertificate")) { $this.ManagementCertificates = [ManagementCertificate]::ListManagementCertificates($mgmtCerts.SubscriptionCertificates.SubscriptionCertificate) } } } } } hidden [void] GetASCAlerts() { $ResourceAppIdURI = [WebRequestHelper]::AzureManagementUri; $AccessToken = [Helpers]::GetAccessToken($ResourceAppIdURI) if($null -ne $AccessToken) { $header = "Bearer " + $AccessToken $headers = @{"Authorization"=$header;"Content-Type"="application/json";} $uri=[system.string]::Format("https://management.azure.com/subscriptions/{0}/providers/microsoft.Security/alerts?api-version=2015-06-01-preview",$this.SubscriptionContext.SubscriptionId) $result = "" $err = $null $output = $null try { $result = Invoke-WebRequest -Method GET -Uri $uri -Headers $headers -UseBasicParsing if($result.StatusCode -ge 200 -and $result.StatusCode -le 399){ if($null -ne $result.Content){ $json = (ConvertFrom-Json $result.Content) if($null -ne $json){ if(($json | Get-Member -Name "value")) { $output += $json.value; } else { $output += $json; } } } } } catch{ $err = $_ if($null -ne $err) { if($null -ne $err.ErrorDetails.Message){ $json = (ConvertFrom-Json $err.ErrorDetails.Message) if($null -ne $json){ $return = $json if($json.'odata.error'.code -eq "Request_ResourceNotFound") { $return = $json.'odata.error'.message } } } } } $this.ASCSettings.Alerts = [AzureSecurityCenter]::GetASCAlerts($output) } } hidden [void] GetASCTasks() { $ResourceAppIdURI = [WebRequestHelper]::AzureManagementUri; $AccessToken = [Helpers]::GetAccessToken($ResourceAppIdURI) if($null -ne $AccessToken) { $header = "Bearer " + $AccessToken $headers = @{"Authorization"=$header;"Content-Type"="application/json";} $uri=[system.string]::Format("https://management.azure.com/subscriptions/{0}/providers/microsoft.Security/tasks?api-version=2015-06-01-preview", $this.SubscriptionContext.SubscriptionId) $result = "" $err = $null $output = $null try { $result = Invoke-WebRequest -Method GET -Uri $uri -Headers $headers -UseBasicParsing if($result.StatusCode -ge 200 -and $result.StatusCode -le 399){ if($null -ne $result.Content){ $json = (ConvertFrom-Json $result.Content) if($null -ne $json){ if($json | Get-Member -Name "value") { $output += $json.value; } else { $output += $json; } } } } } catch{ $err = $_ if($null -ne $err) { if($null -ne $err.ErrorDetails.Message){ $json = (ConvertFrom-Json $err.ErrorDetails.Message) if($null -ne $json){ $return = $json if($json.'odata.error'.code -eq "Request_ResourceNotFound") { $return = $json.'odata.error'.message } } } } } $this.ASCSettings.Tasks = [AzureSecurityCenter]::GetASCTasks($output) } } }
PowerShellCorpus/PowerShellGallery/AzSDKPreview/2.2.0/Framework/Core/SVT/Services/ServiceFabric.ps1
ServiceFabric.ps1
Set-StrictMode -Version Latest class ServiceFabric : SVTBase { hidden [PSObject] $ResourceObject; hidden [string] $ClusterTagValue; hidden [PSObject] $ApplicationList; hidden [string] $DefaultTagName = "clusterName" hidden [string] $CertStoreLocation = "CurrentUser" hidden [string] $CertStoreName = "My" ServiceFabric([string] $subscriptionId, [SVTResource] $svtResource): Base($subscriptionId, $svtResource) { $this.GetResourceObject(); } hidden [PSObject] GetResourceObject() { if (-not $this.ResourceObject) { $this.ResourceObject = Get-AzureRmResource -ResourceGroupName $this.ResourceContext.ResourceGroupName -ResourceType $this.ResourceContext.ResourceType -ResourceName $this.ResourceContext.ResourceName -ApiVersion 2016-03-01 $this.ResourceObject.Tags.GetEnumerator() | Where-Object { $_.Name -eq $this.DefaultTagName } | ForEach-Object {$this.ClusterTagValue = $_.Value } ## Commented below two lines of code. This will be covered once we Service Fabric module gets available as part of AzureRM modules set. #$this.CheckClusterAccess(); #$this.ApplicationList = Get-ServiceFabricApplication if(-not $this.ResourceObject) { throw ("Resource '{0}' not found under Resource Group '{1}'" -f ($this.ResourceContext.ResourceName), ($this.ResourceContext.ResourceGroupName)) } } return $this.ResourceObject; } hidden [ControlResult] CheckSecurityMode([ControlResult] $controlResult) { $isCertificateEnabled = [Helpers]::CheckMember($this.ResourceObject.Properties,"certificate" ) #Validate if primary certificate is enabled on cluster. Presense of certificate property value indicates, security mode is truned on. if($isCertificateEnabled) { $controlResult.AddMessage([VerificationResult]::Passed,"Service Fabric cluster is secured with certificate", $this.ResourceObject.Properties.certificate); } else { $controlResult.AddMessage([VerificationResult]::Failed,"Service Fabric cluster is not secured with certificate"); } return $controlResult; } hidden [ControlResult] CheckClusterCertificateSSL([ControlResult] $controlResult) { $managementEndpointUri = $this.ResourceObject.Properties.managementEndpoint $managementEndpointUriScheme = ([System.Uri]$managementEndpointUri).Scheme #Validate if cluster management endpoint url is SSL enabled if($managementEndpointUriScheme -eq "https") { #Hit web request to management endpoint uri and validate certificate trust level $request = [System.Net.HttpWebRequest]::Create($managementEndpointUri) try { $request.GetResponse().Dispose() $controlResult.AddMessage([VerificationResult]::Passed,"Service Fabric cluster is protected with CA signed certificate"); } catch [System.Net.WebException] { #Trust failure indicates self signed certificate or domain mismatch certificate present on endpoint if ($_.Exception.Status -eq [System.Net.WebExceptionStatus]::TrustFailure) { $controlResult.AddMessage([VerificationResult]::Verify,"Validate if self signed certificate is not used for cluster management endpoint protection",$this.ResourceObject.Properties.managementEndpoint); } else { throw } } } else { $controlResult.AddMessage([VerificationResult]::Failed,"Service Fabric cluster is not proetcted by SSL") } return $controlResult; } hidden [ControlResult] CheckAADClientAuthentication([ControlResult] $controlResult) { $isAADEnabled = [Helpers]::CheckMember($this.ResourceObject.Properties,"azureActiveDirectory") #Presense of 'AzureActiveDirectory' indicates, AAD authentication is enabled for client authentication if($isAADEnabled) { $controlResult.AddMessage([VerificationResult]::Passed,"AAD is enabled for client authentication",$this.ResourceObject.Properties.azureActiveDirectory ) } else { $controlResult.AddMessage([VerificationResult]::Failed,"AAD is not enabled for client authentication") } return $controlResult } hidden [ControlResult] CheckClusterProtectionLevel([ControlResult] $controlResult) { $fabricSecuritySettings = $this.ResourceObject.Properties.fabricSettings | where {$_.Name -eq "Security"} #Absense of security settings indicates, secure mode is not enabled on cluster. if($null -ne $fabricSecuritySettings) { $clusterProtectionLevel = $fabricSecuritySettings.parameters | Where-Object { $_.name -eq "ClusterProtectionLevel"} if($clusterProtectionLevel.value -eq "EncryptAndSign") { $controlResult.AddMessage([VerificationResult]::Passed,"Cluster security is ON with 'EncryptAndSign' protection level",$clusterProtectionLevel); } else { $controlResult.AddMessage([VerificationResult]::Failed,"Cluster security is not set with 'EncryptAndSign' protection level. Current protection level is :", $clusterProtectionLevel); } } else { $controlResult.AddMessage([VerificationResult]::Failed,"Cluster security is OFF"); } return $controlResult } hidden [ControlResult[]] CheckNSGConfigurations([ControlResult] $controlResult) { [ControlResult[]] $controlResultList = @() $virtualNetworkResources = $this.GetLinkedResources("Microsoft.Network/virtualNetworks") #Iterate through all cluster linked VNet resources $virtualNetworkResources |ForEach-Object{ $virtualNetwork=Get-AzureRmVirtualNetwork -ResourceGroupName $_.ResourceGroupName -Name $_.Name $subnetConfig = Get-AzureRmVirtualNetworkSubnetConfig -VirtualNetwork $virtualNetwork #Iterate throught Subnet and validate if NSG is configured or not $subnetConfig | ForEach-Object{ $subnetName =$_.Name [ControlResult] $childControlResult = $this.CreateControlResult($subnetName); $isCompliant = ($_.NetworkSecurityGroup -ne $null) #If NSG is enabled on Subnet display all security rules applied if($isCompliant) { $nsgResource = Get-AzureRmResource -ResourceId $_.NetworkSecurityGroup.Id $nsgResourceDetails = Get-AzureRmNetworkSecurityGroup -ResourceGroupName $nsgResource.ResourceGroupName -Name $nsgResource.Name $childControlResult.AddMessage([VerificationResult]::Verify, "Validate NSG security rules applied on subnet '$subnetName' ", $nsgResourceDetails) } #If NSG is not enabled on Subnet fail the TCP with Subnet details else { $childControlResult.AddMessage([VerificationResult]::Failed, "NSG is not configured on subnet '$subnetName'",$_) } $controlResultList += $childControlResult } } return $controlResultList } hidden [ControlResult[]] CheckStorageEncryption([ControlResult] $controlResult) { [ControlResult[]] $controlResultList = @() $vmssResources = $this.GetLinkedResources("Microsoft.Compute/virtualMachineScaleSets") #Iterate throught cluster linked vmss resources $vmssResources | ForEach-Object{ $vmssResourceId = Get-AzureRmResource -ResourceId $_.ResourceId #Get all storage account details where vmss disk is stored $vmssResourceId.Properties.virtualMachineProfile.storageProfile.osDisk.vhdContainers | ForEach-Object{ $storageName = Convert-String -InputObject $_ -Example "https://accountname.blob.core.windows.net/vhds=accountname" $storageAccount = Get-AzureRmStorageAccount -Name $storageName -ResourceGroupName $this.ResourceContext.ResourceGroupName [ControlResult] $childControlResult = $this.CreateControlResult($storageName); #Validate if storage account storing vmss os disk/Cluster data is encrypted or not if($null -ne $storageAccount.Encryption) { $childControlResult.AddMessage([VerificationResult]::Passed, "Storage encryption is enabled for '$storageName'"); } else { $childControlResult.AddMessage([VerificationResult]::Failed, "Storage encryption is not enabled for '$storageName'"); } $controlResultList += $childControlResult } } return $controlResultList; } hidden [ControlResult[]] CheckVmssDiagnostics([ControlResult] $controlResult) { [ControlResult[]] $controlResultList = @() $vmssResources = $this.GetLinkedResources("Microsoft.Compute/virtualMachineScaleSets") #Iterate throught cluster linked vmss resources $vmssResources | ForEach-Object{ $VMScaleSetName = $_.Name [ControlResult] $childControlResult = $this.CreateControlResult($VMScaleSetName); $nodeTypeResource = Get-AzureRmVmss -ResourceGroupName $_.ResourceGroupName -VMScaleSetName $VMScaleSetName $diagnosticsSettings = $nodeTypeResource.VirtualMachineProfile.ExtensionProfile.Extensions | ? { $_.Type -eq "IaaSDiagnostics" -and $_.Publisher -eq "Microsoft.Azure.Diagnostics" } #Validate if diagnostics is enabled on vmss if($null -ne $diagnosticsSettings ) { $childControlResult.AddMessage([VerificationResult]::Passed, "Diagnostics is enabled on Vmss '$VMScaleSetName'",$diagnosticsSettings); } else { $childControlResult.AddMessage([VerificationResult]::Failed, "Diagnostics is disabled on Vmss '$VMScaleSetName'"); } $controlResultList += $childControlResult } return $controlResultList } hidden [ControlResult[]] CheckStatefulServiceReplicaSetSize([ControlResult] $controlResult) { [ControlResult[]] $controlResultList = @() #Iterate throught the applications present in cluster if($this.ApplicationList) { $this.ApplicationList | ForEach-Object{ $serviceFabricApplication = $_ Get-ServiceFabricService -ApplicationName $serviceFabricApplication.ApplicationName | ForEach-Object{ $serviceName = $_.ServiceName [ControlResult] $childControlResult = $this.CreateControlResult($serviceName); $serviceDescription = Get-ServiceFabricServiceDescription -ServiceName $_.ServiceName #Filter application with Stateful service type if($serviceDescription.ServiceKind -eq "Stateful") { [ControlResult] $childControlResult = $this.CreateControlResult($serviceName) #Validate minimum replica and target replica size for each service $isCompliant = !($serviceDescription.MinReplicaSetSize -lt 3 -or $serviceDescription.TargetReplicaSetSize -lt 3) if($isCompliant){ $controlStatus = [VerificationResult]::Passed } else{ $controlStatus = [VerificationResult]::Failed } $childControlResult.AddMessage([VerificationResult]::Failed, "Replica set size details for service '$serviceName'",$serviceDescription) $controlResultList += $childControlResult } } } } else { $controlResult.AddMessage([VerificationResult]::Passed,"No stateful service found.") $controlResultList += $controlResult } return $controlResultList } hidden [ControlResult[]] CheckStatelessServiceInstanceCount([ControlResult] $controlResult) { [ControlResult[]] $controlResultList = @() #Iterate throught the applications present in cluster if($this.ApplicationList) { $this.ApplicationList | ForEach-Object{ $serviceFabricApplication = $_ Get-ServiceFabricService -ApplicationName $serviceFabricApplication.ApplicationName | ForEach-Object{ $serviceName = $_.ServiceName [ControlResult] $childControlResult = $this.CreateControlResult($serviceName); $serviceDescription = Get-ServiceFabricServiceDescription -ServiceName $serviceName #Filter application with Stateless service type if($serviceDescription.ServiceKind -eq "Stateless") { $instantCount = $serviceDescription.InstanceCount Add-OutputLogEvent -OutputLogFilePath $outputLogFilePath -EventData "Service Fabric service [$serviceName] has instance count : [$instantCount]" #Validate instancecount it -1 (auto) or greater than equal to 3 if($serviceDescription.InstanceCount -eq -1 -and $serviceDescription.InstanceCount -ge 3){$controlStatus = [VerificationResult]::Passed } else{ $controlStatus = [VerificationResult]::Failed } $childControlResult.AddMessage([VerificationResult]::Failed, "Instance count for service '$serviceName'",$serviceDescription) $controlResultList += $childControlResult } } } } else { $controlResult.AddMessage([VerificationResult]::Passed,"No stateless service found.") $controlResultList += $controlResult } return $controlResultList } hidden [ControlResult[]] CheckPublicEndpointSSL([ControlResult] $controlResult) { [ControlResult[]] $controlResultList = @() $loadBalancerBackendPorts = @() $loadBalancerResources = $this.GetLinkedResources("Microsoft.Network/loadBalancers") #Collect all open ports on load balancer $loadBalancerResources | ForEach-Object{ $loadBalancerResource = Get-AzureRmLoadBalancer -Name $_.ResourceName -ResourceGroupName $_.ResourceGroupName $loadBalancingRules = @($loadBalancerResource.FrontendIpConfigurations | ? { $_.PublicIpAddress -ne $null } | % { $_.LoadBalancingRules }) $loadBalancingRules | % { $loadBalancingRuleId = $_.Id; $loadBalancingRule = $loadBalancerResource.LoadBalancingRules | ? { $_.Id -eq $loadBalancingRuleId } | select -First 1 $loadBalancerBackendPorts += $loadBalancingRule.BackendPort; }; } #If no ports open, Pass the TCP if($loadBalancerBackendPorts.Count -eq 0) { $controlResult.AddMessage([VerificationResult]::Passed,"No ports enabled.") $controlResultList += $controlResult } #If Ports are open for public in load balancer, map load balancer ports with application endpoint ports and validate if SSL is enabled. else { $controlResult.AddMessage("List of publicly exposed port",$loadBalancerBackendPorts) if($this.ApplicationList) { $this.ApplicationList | ForEach-Object{ $serviceFabricApplication = $_ Get-ServiceFabricServiceType -ApplicationTypeName $serviceFabricApplication.ApplicationTypeName -ApplicationTypeVersion $serviceFabricApplication.ApplicationTypeVersion | ForEach-Object{ $currentService = $_ $serviceManifest = [xml](Get-ServiceFabricServiceManifest -ApplicationTypeName $serviceFabricApplication.ApplicationTypeName -ApplicationTypeVersion $serviceFabricApplication.ApplicationTypeVersion -ServiceManifestName $_.ServiceManifestName) $serviceManifest.ServiceManifest.Resources.Endpoints.ChildNodes | ForEach-Object{ $endpoint = $_ $serviceTypeName = $currentService.ServiceTypeName [ControlResult] $childControlResult = $this.CreateControlResult($serviceTypeName +"_" + $endpoint.Name); if($endpoint.Port -eq $null) { #Add message $childControlResult.AddMessage([VerificationResult]::Passed) } else { if($loadBalancerBackendPorts.Contains($endpoint.Port) ) { if($endpoint.Protocol -eq "https"){ $controlResult.AddMessage([VerificationResult]::Passed,"Endpoint is protected with SSL") } elseif($endpoint.Protocol -eq "http"){ $controlResult.AddMessage([VerificationResult]::Failed,"Endpoint is not protected with SSL") } else { $controlResult.AddMessage([VerificationResult]::Verify,"Verify if endpoint is protected with SSL",$endpoint) } } else { $controlResult.AddMessage([VerificationResult]::Passed,"Endpoint is not publicly opened") } } $controlResultList += $childControlResult } } } } else { $controlResult.AddMessage([VerificationResult]::Passed,"No service found.") $controlResultList += $controlResult } } return $controlResultList } [void] CheckClusterAccess() { #Function to validate authentication and connect with Service Fabric cluster $sfCluster = $null $uri = ([System.Uri]$this.ResourceObject.Properties.managementEndpoint).Host $primaryNodeType = $this.ResourceObject.Properties.nodeTypes | where { $_.isPrimary -eq $true } $ClusterConnectionUri = $uri +":"+ $primaryNodeType.clientConnectionEndpointPort $this.PublishCustomMessage("Connecting with Service Fabric cluster...") $this.PublishCustomMessage("Valiating if Service Fabric is secure...") $isClusterSecure = [Helpers]::CheckMember($this.ResourceObject.Properties,"certificate" ) if($isClusterSecure) { $serviceFabricCertificate = $this.ResourceObject.Properties.certificate $this.PublishCustomMessage("Service Fabric is secure") $CertThumbprint= $this.ResourceObject.Properties.certificate.thumbprint $serviceFabricAAD =$this.ResourceObject.Properties.azureActiveDirectory if($serviceFabricAAD -ne $null) { try { $this.PublishCustomMessage("Connecting Service Fabric using AAD...") $sfCluster = Connect-ServiceFabricCluster -ConnectionEndpoint $ClusterConnectionUri -AzureActiveDirectory -ServerCertThumbprint $CertThumbprint #-SecurityToken " $this.PublishCustomMessage("Connection using AAD is successful.") } catch { throw "You may not have permission to connect with cluster" } } else { $this.PublishCustomMessage("Validating if cluster certificate present on machine...") $IsCertPresent = (Get-ChildItem -Path Cert:\$this.CertStoreLocation\$this.CertStoreName | Where-Object {$_.Thumbprint -eq $CertThumbprint }).Count if($IsCertPresent) { $this.PublishCustomMessage("Connecting Service Fabric using certificate") $sfCluster = Connect-serviceFabricCluster -ConnectionEndpoint $ClusterConnectionUri -KeepAliveIntervalInSec 10 -X509Credential -ServerCertThumbprint $CertThumbprint -FindType FindByThumbprint -FindValue $CertThumbprint -StoreLocation $this.CertStoreLocation -StoreName $this.CertStoreName } else { throw "Can not connect with Service Fabric due to unavailability of cluster certificate in local machine. Validate cluster certificate is present in 'CurrentUser' location." } } } else { "Service Fabric is unsecure" $sfCluster = Connect-serviceFabricCluster -ConnectionEndpoint $ClusterConnectionUri "Service Fabric connection is successful" } } [PSObject] GetLinkedResources([string] $resourceType) { return Find-AzureRmResource -TagName $this.DefaultTagName -TagValue $this.ClusterTagValue | Where-Object { ($_.ResourceType -EQ $resourceType) -and ($_.ResourceGroupName -eq $this.ResourceContext.ResourceGroupName) } } }
PowerShellCorpus/PowerShellGallery/AzSDKPreview/2.2.0/Framework/Core/SVT/Services/AnalysisServices.ps1
AnalysisServices.ps1
Set-StrictMode -Version Latest class AnalysisServices: SVTBase { hidden [PSObject] $ResourceObject; AnalysisServices([string] $subscriptionId, [string] $resourceGroupName, [string] $resourceName): Base($subscriptionId, $resourceGroupName, $resourceName) { $this.GetResourceObject(); } AnalysisServices([string] $subscriptionId, [SVTResource] $svtResource): Base($subscriptionId, $svtResource) { $this.GetResourceObject(); } hidden [PSObject] GetResourceObject() { if (-not $this.ResourceObject) { #Using command Get-AzureRmResource to get resource details (Admin and Backups details). #Get-AzureRmAnalysisServicesServer command not provides Backups details $this.ResourceObject = Get-AzureRmResource -ResourceName $this.ResourceContext.ResourceName ` -ResourceGroupName $this.ResourceContext.ResourceGroupName ` -ResourceType $this.ResourceContext.ResourceType if(-not $this.ResourceObject) { throw ("Resource '{0}' not found under Resource Group '{1}'" -f ($this.ResourceContext.ResourceName), ($this.ResourceContext.ResourceGroupName)) } } return $this.ResourceObject; } hidden [ControlResult] CheckAnalysisServicesAdmin([ControlResult] $controlResult) { if($this.ResourceObject.Properties -and $this.ResourceObject.Properties.State) { if($this.ResourceObject.Properties.State -eq "Paused") { #Can not retrive Analysis Services Admins details if analysis services state is 'Paused' $controlResult.AddMessage([MessageData]::new("Unable to fetch Analysis Services Admins as status is - [$($this.ResourceObject.Properties.State)]")) return $controlResult } #Get Admin count $adminCount = ($this.ResourceObject.Properties.AsAdministrators.members | Measure-Object).Count; #No admins if($adminCount -eq 0) { $controlResult.AddMessage([VerificationResult]::Verify, "Analysis Services admins are not configured"); } #Threshold case elseif($adminCount -gt 0 -and $adminCount -le $this.ControlSettings.AnalysisService.Max_Admin_Count) { $controlResult.AddMessage([VerificationResult]::Verify, "Validate that the following users require admin access on Analysis Services", $this.ResourceObject.Properties.AsAdministrators.members); } #Number of admins are more than permissible limit else { $controlResult.AddMessage([VerificationResult]::Failed, "Number of admins exceeds the maximum recommended value of $($this.ControlSettings.AnalysisService.Max_Admin_Count). Validate that the following users require admin access on Analysis Services", $this.ResourceObject.Properties.AsAdministrators.members); } } else { $controlResult.AddMessage([MessageData]::new("Not able to fetch the required data for the resource", [MessageType]::Error)); } return $controlResult; } hidden [ControlResult] CheckAnalysisServicesBCDRStatus([ControlResult] $controlResult) { if($this.ResourceObject.Properties){ #If Backup is enabled then Resource Properties object will have property with name 'backupBlobContainerUri' if(Get-Member -InputObject $this.ResourceObject.Properties -Name 'backupBlobContainerUri' -MemberType Properties) { $controlResult.AddMessage([VerificationResult]::Passed, [MessageData]::new("Backup is enabled")); } else { $controlResult.AddMessage([VerificationResult]::Failed, [MessageData]::new("Backup is not enabled")); } } else{ $controlResult.AddMessage([MessageData]::new("Not able to fetch the required data for the resource", [MessageType]::Error)); } return $controlResult; } }
PowerShellCorpus/PowerShellGallery/AzSDKPreview/2.2.0/Framework/Core/SVT/Services/NotificationHub.ps1
NotificationHub.ps1
#using namespace Microsoft.Azure.Commands.KeyVault.Models Set-StrictMode -Version Latest class NotificationHub: SVTBase { hidden [PSObject] $ResourceObject; hidden [PSObject] $NamespaceObject; NotificationHub([string] $subscriptionId, [string] $resourceGroupName, [string] $resourceName): Base($subscriptionId, $resourceGroupName, $resourceName) { $this.GetResourceObject(); } NotificationHub([string] $subscriptionId, [SVTResource] $svtResource): Base($subscriptionId, $svtResource) { $this.GetResourceObject(); } hidden [PSObject] GetResourceObject() { if (-not $this.ResourceObject) { $this.ResourceObject = Find-AzureRmResource -ResourceNameContains $this.ResourceContext.ResourceName -ResourceType "Microsoft.NotificationHubs/namespaces/notificationHubs" $Namespace = $this.ResourceObject.ResourceName.split("/")[0] $this.NamespaceObject = Get-AzureRmNotificationHubsNamespace -ResourceGroup $this.ResourceContext.ResourceGroupName -Namespace $Namespace if(-not $this.ResourceObject) { throw ("Resource '{0}' not found under Resource Group '{1}'" -f ($this.ResourceContext.ResourceName), ($this.ResourceContext.ResourceGroupName)) } } return $this.ResourceObject; } hidden [ControlResult] CheckAuthorizationRule([ControlResult] $controlResult) { $resourceName = ($this.ResourceContext.ResourceName.Split("/")[1]); $accessPolicieswithManageRights = (Get-AzureRmNotificationHubAuthorizationRules ` -ResourceGroup $this.ResourceContext.ResourceGroupName ` -Namespace $this.NamespaceObject.Name ` -NotificationHub $resourceName) ` | Where-Object Rights -Contains “Manage” ` | Select-Object -Property Name, Rights if($null -ne $accessPolicieswithManageRights){ $controlResult.AddMessage([VerificationResult]::Failed, [MessageData]::new("Authorization rules having 'Manage' security claim access rights for resource - ["+ $this.ResourceContext.ResourceName +"]" , $accessPolicieswithManageRights)); } else{ $controlResult.AddMessage([VerificationResult]::Passed, [MessageData]::new("No authorization rules found with 'Manage' security claim access rights for resource - ["+ $this.ResourceContext.ResourceName +"]" , $accessPolicieswithManageRights)); } return $controlResult; } }
PowerShellCorpus/PowerShellGallery/AzSDKPreview/2.2.0/Framework/Core/SVT/Services/Search.ps1
Search.ps1
#using namespace Microsoft.Azure.Commands.Search.Models Set-StrictMode -Version Latest class Search: SVTBase { hidden [PSObject] $ResourceObject; Search([string] $subscriptionId, [string] $resourceGroupName, [string] $resourceName): Base($subscriptionId, $resourceGroupName, $resourceName) { $this.GetResourceObject(); } Search([string] $subscriptionId, [SVTResource] $svtResource): Base($subscriptionId, $svtResource) { $this.GetResourceObject(); } hidden [PSObject] GetResourceObject() { if (-not $this.ResourceObject) { $this.ResourceObject = Get-AzureRmResource -ResourceName $this.ResourceContext.ResourceName ` -ResourceType "Microsoft.Search/searchServices" ` -ResourceGroupName $this.ResourceContext.ResourceGroupName ` -ErrorAction Stop if(-not $this.ResourceObject) { throw ("Resource '{0}' not found under Resource Group '{1}'" -f ($this.ResourceContext.ResourceName), ($this.ResourceContext.ResourceGroupName)) } } return $this.ResourceObject; } hidden [ControlResult] CheckSearchReplicaCount([ControlResult] $controlResult) { $replicaCount = $this.ResourceObject.Properties.replicaCount $isCompliant = $replicaCount -ge 3 if($isCompliant) { $controlResult.AddMessage([VerificationResult]::Passed, [MessageData]::new("Replica count for resource " + $this.ResourceContext.ResourceName + " is " + $replicaCount)); } else { $controlResult.AddMessage([VerificationResult]::Failed, [MessageData]::new("Replica count for resource " + $this.ResourceContext.ResourceName + " is " + $replicaCount)); } return $controlResult; } }
PowerShellCorpus/PowerShellGallery/AzSDKPreview/2.2.0/Framework/Core/SVT/Services/EventHub.ps1
EventHub.ps1
#using namespace Microsoft.Azure.Commands.EventHub.Models Set-StrictMode -Version Latest class EventHub: SVTBase { hidden [PSObject[]] $NameSpacePolicies; hidden [PSObject[]] $EventHubs; EventHub([string] $subscriptionId, [string] $resourceGroupName, [string] $resourceName): Base($subscriptionId, $resourceGroupName, $resourceName) { $this.GetEventHubDetails(); } EventHub([string] $subscriptionId, [SVTResource] $svtResource): Base($subscriptionId, $svtResource) { $this.GetEventHubDetails(); } hidden [void] GetEventHubDetails() { if (-not $this.NameSpacePolicies) { $this.NameSpacePolicies = Get-AzureRmEventHubNamespaceAuthorizationRule -ResourceGroupName $this.ResourceContext.ResourceGroupName ` -NamespaceName $this.ResourceContext.ResourceName } if (-not $this.EventHubs) { $this.EventHubs = Get-AzureRmEventHub -ResourceGroupName $this.ResourceContext.ResourceGroupName -NamespaceName $this.ResourceContext.ResourceName } } hidden [ControlResult[]] CheckEventHubRootPolicy([ControlResult] $controlResult) { [ControlResult[]] $resultControlResultList = @() #region "NameSpace" [ControlResult] $childControlResult = [ControlResult]@{ #ChildResourceName = $this.ResourceContext.ResourceName; }; $childControlResult.AddMessage([VerificationResult]::Verify, [MessageData]::new("Authorization rules for Namespace - ["+ $this.ResourceContext.ResourceName +"]. Validate that these rules must not be used at Event Hub level to send and receive messages.", $this.NameSpacePolicies)); $resultControlResultList += $childControlResult #endregion #region "Event Hub" if(($this.EventHubs|Measure-Object).count -gt 0) { foreach ($eventHub in $this.EventHubs) { [ControlResult] $childControlResult = [ControlResult]@{ ChildResourceName = $eventHub.Name; }; $eventHubPolicies = Get-AzureRmEventHubAuthorizationRule -ResourceGroupName $this.ResourceContext.ResourceGroupName ` -NamespaceName $this.ResourceContext.ResourceName -EventHubName $eventHub.Name if(($eventHubPolicies|Measure-Object).count -gt 0) { $childControlResult.AddMessage([VerificationResult]::Verify, [MessageData]::new("Validate that Event Hub - ["+ $eventHub.Name +"] must not use access policies defined at Namespace level.")); } else { $childControlResult.AddMessage([VerificationResult]::Failed, [MessageData]::new("No Authorization rules defined for Event Hub - ["+ $eventHub.Name +"]. Applications (senders/receivers) must not use access policies defined at Event Hub namespace level.")); } $resultControlResultList += $childControlResult } } else { $controlResult.AddMessage([MessageData]::new("Event Hub not available in Namespace - ["+ $this.ResourceContext.ResourceName +"]")); } #endregion return $resultControlResultList; } hidden [ControlResult[]] CheckEventHubAuthorizationRule([ControlResult] $controlResult) { [ControlResult[]] $resultControlResultList = @() #region "NameSpace" [ControlResult] $childControlResult = [ControlResult]@{ #ChildResourceName = $this.ResourceContext.ResourceName; }; $childControlResult.AddMessage([VerificationResult]::Verify, [MessageData]::new("Authorization rules for Namespace - ["+ $this.ResourceContext.ResourceName +"]. Validate that these rules are defined at correct entity level and with more limited permissions.", $this.NameSpacePolicies)); $resultControlResultList += $childControlResult #endregion #region "Event Hub" if(($this.EventHubs|Measure-Object).count -gt 0) { foreach ($eventHub in $this.EventHubs) { [ControlResult] $childControlResult = [ControlResult]@{ ChildResourceName = $eventHub.Name; }; $eventHubPolicies = Get-AzureRmEventHubAuthorizationRule -ResourceGroupName $this.ResourceContext.ResourceGroupName ` -NamespaceName $this.ResourceContext.ResourceName -EventHubName $eventHub.Name if(($eventHubPolicies|Measure-Object).count -gt 0) { $childControlResult.AddMessage([VerificationResult]::Verify, [MessageData]::new("Authorization rules for Event Hub - ["+ $eventHub.Name +"]. Validate that these rules are defined at correct entity level and with more limited permissions.", $eventHubPolicies)); } else { $childControlResult.AddMessage([VerificationResult]::Passed, [MessageData]::new("No Authorization rules defined for Event Hub - ["+ $eventHub.Name +"].")); } $resultControlResultList += $childControlResult } } else { $controlResult.AddMessage([MessageData]::new("Event Hub not available in Namespace - ["+ $this.ResourceContext.ResourceName +"]")); } #endregion return $resultControlResultList; } }
PowerShellCorpus/PowerShellGallery/AzSDKPreview/2.2.0/Framework/Core/SVT/Services/VirtualMachine.ps1
VirtualMachine.ps1
using namespace Microsoft.Azure.Commands.Network.Models using namespace Microsoft.Azure.Commands.Compute.Models Set-StrictMode -Version Latest class VirtualMachine: SVTBase { hidden [PSVirtualMachine] $ResourceObject; hidden [PSNetworkInterface[]] $VMNICs = $null; VirtualMachine([string] $subscriptionId, [string] $resourceGroupName, [string] $resourceName): Base($subscriptionId, $resourceGroupName, $resourceName) { $this.GetResourceObject(); } VirtualMachine([string] $subscriptionId, [SVTResource] $svtResource): Base($subscriptionId, $svtResource) { $this.GetResourceObject(); } hidden [PSVirtualMachine] GetResourceObject() { if (-not $this.ResourceObject) { $this.ResourceObject = Get-AzureRmVM -ResourceGroupName $this.ResourceContext.ResourceGroupName -Name $this.ResourceContext.ResourceName -WarningAction SilentlyContinue if(-not $this.ResourceObject) { throw ("Resource '{0}' not found under Resource Group '{1}'" -f ($this.ResourceContext.ResourceName), ($this.ResourceContext.ResourceGroupName)) } } return $this.ResourceObject; } hidden [PSNetworkInterface[]] GetVMNICObjects() { if (-not $this.VMNICs) { $this.VMNICs = @(); if($this.ResourceObject.NetworkProfile -and $this.ResourceObject.NetworkProfile.NetworkInterfaces) { $this.ResourceObject.NetworkProfile.NetworkInterfaces | ForEach-Object { $currentNic = Get-AzureRmResource -ResourceId $_.Id -ErrorAction SilentlyContinue if($currentNic) { $nicResource = Get-AzureRmNetworkInterface -Name $currentNic.ResourceName ` -ResourceGroupName $currentNic.ResourceGroupName ` -ExpandResource NetworkSecurityGroup ` -ErrorAction SilentlyContinue if($nicResource) { $this.VMNICs += $nicResource; } } } } } return $this.VMNICs; } hidden [bool] IsLinuxVM() { return ($this.ResourceObject.OSProfile -and $this.ResourceObject.OSProfile.LinuxConfiguration); } hidden [ControlResult] CheckOSVersion([ControlResult] $controlResult) { $vmOSDetails = $this.ResourceObject.StorageProfile.ImageReference if($this.ResourceObject.StorageProfile -and $this.ResourceObject.StorageProfile.ImageReference) { $message = ""; $verificationResult = [VerificationResult]::Failed; if($vmOSDetails.Version -eq "latest") { $verificationResult = [VerificationResult]::Passed $message = "Virtual Machine is running latest OS version" } else { $message = "Virtual Machine is not running latest OS version. Please upgrade the OS in order to comply." } $controlResult.AddMessage($verificationResult, $message, $vmOSDetails); } else { $controlResult.AddMessage([MessageData]::new("We are not able to fetch the required data for the resource", [MessageType]::Error)); } return $controlResult; } hidden [ControlResult] CheckOSAutoUpdateStatus([ControlResult] $controlResult) { #TCP is not applicable for Linux. if($this.ResourceObject.OSProfile -and $this.ResourceObject.OSProfile.WindowsConfiguration) { $message = ""; $verificationResult = [VerificationResult]::Failed; if($this.ResourceObject.OSProfile.WindowsConfiguration.EnableAutomaticUpdates -eq $true) { $verificationResult = [VerificationResult]::Passed; $message = "Automatic OS updates are enabled on Windows Virtual Machine"; } else { $message = "Automatic OS updates are disabled on Windows Virtual Machine. Please enable OS automatic updates in order to comply."; } $controlResult.AddMessage($verificationResult, $message, $this.ResourceObject.OSProfile.WindowsConfiguration); } elseif($this.IsLinuxVM()) { $controlResult.AddMessage([VerificationResult]::Manual, "The control is not applicable on Linux Virtual Machine. It's good pratice to periodically update OS of Virtual Machine.", $this.ResourceObject.OSProfile.LinuxConfiguration); } else { $controlResult.AddMessage([MessageData]::new("We are not able to fetch the required data for the resource", [MessageType]::Error)); } return $controlResult; } hidden [ControlResult] CheckAntimalwareStatus([ControlResult] $controlResult) { #TCP is not applicable for Linux. if($this.ResourceObject.Extensions) { $antimalwareExt = $this.ResourceObject.Extensions | Where-Object { $_.VirtualMachineExtensionType -eq 'IaaSAntimalware'} | Select-Object -First 1 if($antimalwareExt -and $antimalwareExt.Settings) { #create Antimalware data object $antimalwareData = @{ AntimalwareEnabled = $antimalwareExt.Settings.AntimalwareEnabled.Value; RealtimeProtectionEnabled = $antimalwareExt.Settings.RealtimeProtectionEnabled.Value; ScheduledScanSettings = @{ IsEnabled = $antimalwareExt.Settings.ScheduledScanSettings.isEnabled.Value ScanType = $antimalwareExt.Settings.ScheduledScanSettings.scanType.Value Day = $antimalwareExt.Settings.ScheduledScanSettings.day.Value Time = $antimalwareExt.Settings.ScheduledScanSettings.time.Value }; }; #$Exclusions = $antimalwareExt.Settings | where{ $_.Path -eq 'Exclusions'} #-and $scheduleScanSettings.isEnabled $message = ""; $verificationResult = [VerificationResult]::Failed; if(($antimalwareData.AntimalwareEnabled -eq $true) -and ($antimalwareData.RealtimeProtectionEnabled -eq $true)-and ($antimalwareData.ScheduledScanSettings.IsEnabled -eq $true)) { $verificationResult = [VerificationResult]::Passed; $message = "Antimalware extension is installed and is configured correctly"; } else { $verificationResult = [VerificationResult]::Failed $message = "Antimalware extension is installed but is not configured correctly"; } $controlResult.AddMessage($verificationResult, $message, $antimalwareData); } else { $controlResult.AddMessage([VerificationResult]::Failed, "Antimalware extension is not installed"); } } else { $controlResult.AddMessage([MessageData]::new("We are not able to fetch the required data for the resource", [MessageType]::Error)); } return $controlResult; } hidden [ControlResult] CheckNSGConfig([ControlResult] $controlResult) { $controlResult.VerificationResult = [VerificationResult]::Failed; $this.GetVMNICObjects() | ForEach-Object { #Check NSGs applied at NIC level if($_.NetworkSecurityGroup) { if($_.NetworkSecurityGroup.SecurityRules.Count -gt 0) { $controlResult.AddMessage("Validate NSG security rules applied to NIC - [$($_.Name)], Total - $($_.NetworkSecurityGroup.SecurityRules.Count)", $_.NetworkSecurityGroup.SecurityRules); } if($_.NetworkSecurityGroup.DefaultSecurityRules.Count -gt 0) { $controlResult.AddMessage("Validate NSG default security rules applied to NIC - [$($_.Name)], Total - $($_.NetworkSecurityGroup.DefaultSecurityRules.Count)", $_.NetworkSecurityGroup.DefaultSecurityRules); } $controlResult.VerificationResult = [VerificationResult]::Verify; } #check NSGs applied at subnet level if($_.IpConfigurations) { $_.IpConfigurations | ForEach-Object { $subnetId = $_.Subnet.Id; $subnetName = $subnetId.Substring($subnetId.LastIndexOf("/") + 1); #vnet id = trim '/subnets/' from subnet id $vnetResource = Get-AzureRmResource -ResourceId $subnetId.Substring(0, $subnetId.IndexOf("/subnets/")) if($vnetResource) { $vnetObject = Get-AzureRmVirtualNetwork -Name $vnetResource.Name -ResourceGroupName $vnetResource.ResourceGroupName if($vnetObject) { $subnetConfig = Get-AzureRmVirtualNetworkSubnetConfig -Name $subnetName -VirtualNetwork $vnetObject if($subnetConfig -and $subnetConfig.NetworkSecurityGroup -and $subnetConfig.NetworkSecurityGroup.Id) { $nsgResource = Get-AzureRmResource -ResourceId $subnetConfig.NetworkSecurityGroup.Id if($nsgResource) { $nsgObject = Get-AzureRmNetworkSecurityGroup -Name $nsgResource.Name -ResourceGroupName $nsgResource.ResourceGroupName if($nsgObject) { if($nsgObject.SecurityRules.Count -gt 0) { $controlResult.AddMessage("Validate NSG security rules applied to Subnet - [$subnetName] in Virtual Network - [$($vnetResource.Name)]. Total - $($nsgObject.SecurityRules.Count)", $nsgObject.SecurityRules); } if($nsgObject.DefaultSecurityRules.Count -gt 0) { $controlResult.AddMessage("Validate NSG default security rules applied to Subnet - [$subnetName] in Virtual Network - [$($vnetResource.Name)]. Total - $($nsgObject.DefaultSecurityRules.Count)", $nsgObject.DefaultSecurityRules); } $controlResult.VerificationResult = [VerificationResult]::Verify; } } } } } } } } if($controlResult.VerificationResult -ne [VerificationResult]::Verify) { $controlResult.AddMessage("No NSG is configured on Virtual Machine") } return $controlResult; } hidden [ControlResult] CheckPublicIP([ControlResult] $controlResult) { $publicIps = @(); $this.GetVMNICObjects() | ForEach-Object { $_.IpConfigurations | Where-Object { $_.PublicIpAddress } | ForEach-Object { $ipResource = Get-AzureRmResource -ResourceId $_.PublicIpAddress.Id if($ipResource) { $publicIpObject = Get-AzureRmPublicIpAddress -Name $ipResource.Name -ResourceGroupName $ipResource.ResourceGroupName if($publicIpObject) { $_.PublicIpAddress = $publicIpObject; $publicIps += $publicIpObject; } } } } if($publicIps.Count -gt 0) { $controlResult.AddMessage([VerificationResult]::Verify, "Validate Public IP(s) associated with Virtual Machine. Total - $($publicIps.Count)", $publicIps); } else { $controlResult.AddMessage([VerificationResult]::Passed, "No Public IP is associated with Virtual Machine"); } return $controlResult; } hidden [ControlResult] CheckDiskEncryption([ControlResult] $controlResult) { #TCP is not applicable for Linux. if($this.ResourceObject.OSProfile -and $this.ResourceObject.OSProfile.WindowsConfiguration) { $diskEncryptionStatus = Get-AzureRmVMDiskEncryptionStatus -ResourceGroupName $this.ResourceContext.ResourceGroupName -VMName $this.ResourceContext.ResourceName $message = ""; $verificationResult = [VerificationResult]::Failed; #Need to convert the string values to Enum [Microsoft.Azure.Commands.Compute.Models.EncryptionStatus] #Enum type is not resolving here if(($diskEncryptionStatus.OsVolumeEncrypted -eq "NotEncrypted") -or ($diskEncryptionStatus.DataVolumesEncrypted -eq "NotEncrypted")) { $message = "All Virtual Machine disks (OS and Data disks) are not encrypted"; } else { $verificationResult = [VerificationResult]::Passed; $message = "All Virtual Machine disks (OS and Data disks) are encrypted"; } $controlResult.AddMessage($verificationResult, $message, $diskEncryptionStatus); } elseif($this.IsLinuxVM()) { $controlResult.AddMessage([VerificationResult]::Manual, "The control is not applicable on Linux Virtual Machine."); } else { $controlResult.AddMessage([MessageData]::new("We are not able to fetch the required data for the resource", [MessageType]::Error)); } return $controlResult; } hidden [ControlResult] CheckASCStatus([ControlResult] $controlResult) { $isManual = $false; $result = $null $uri = [System.String]::Format("{0}subscriptions/{1}/providers/microsoft.Security/securityStatuses?api-version=2015-06-01-preview", [WebRequestHelper]::AzureManagementUri, $this.SubscriptionContext.SubscriptionId) try { $result = [WebRequestHelper]::InvokeGetWebRequest($uri) } catch { $isManual = $true; } if(($result | Measure-Object).Count -gt 0) { $vmSecurityState = $result | Where-Object { $_.name -eq $this.ResourceContext.ResourceName -and $_.properties.type -eq 'VirtualMachine' } | Select-Object -First 1; if($vmSecurityState) { $vmSecurityStateProperties = @{ SecurityState = $vmSecurityState.properties.securityState; DetailedStatus = @{ Monitered = $vmSecurityState.properties.baselineScannerData.securityState; SystemUpdates = $vmSecurityState.properties.patchScannerData.securityState; EndpointProtection = $vmSecurityState.properties.antimalwareScannerData.securityState; Vulnerabilities = $vmSecurityState.properties.vulnerabilityAssessmentScannerStatus.securityState; DiskEncryption = $vmSecurityState.properties.encryptionDataState.securityState; }; }; if($vmSecurityState.properties.securityState -ne 'Healthy') { $controlResult.VerificationResult = [VerificationResult]::Failed } else { $controlResult.VerificationResult = [VerificationResult]::Passed } $controlResult.AddMessage("Security Center status for Virtual Machine [$($this.ResourceContext.ResourceName)] is: [$($vmSecurityState.properties.securityState)]", $vmSecurityStateProperties); } else { $isManual = $true; } } else { $isManual = $true; } if($isManual) { $controlResult.AddMessage([VerificationResult]::Manual, "We are not able to check Security Center status right now. Please validate manually."); } return $controlResult; } hidden [ControlResult] CheckVMDiagnostics([ControlResult] $controlResult) { if($this.ResourceObject.Extensions) { $diagnosticExtensionType = if($this.IsLinuxVM()) { "LinuxDiagnostic" } else { "IaaSDiagnostics" } $diagExtension = $this.ResourceObject.Extensions | Where-Object { $_.VirtualMachineExtensionType -eq $diagnosticExtensionType } | Select-Object -First 1 if($diagExtension) { $controlResult.AddMessage([VerificationResult]::Passed, "'$diagnosticExtensionType' extension is installed on Virtual Machine"); } else { $controlResult.AddMessage([VerificationResult]::Failed, "'$diagnosticExtensionType' extension is not installed on Virtual Machine"); } } else { $controlResult.AddMessage([MessageData]::new("We are not able to fetch the required data for the resource", [MessageType]::Error)); } return $controlResult; } hidden [ControlResult] CheckOpenPorts([ControlResult] $controlResult) { $isManual = $false $controlResult.AddMessage("Checking for Virtual Machine management ports RDP - $($this.ControlSettings.VirtualMachine.RDP_Port) and WinRM - $($this.ControlSettings.VirtualMachine.WinRM_Port)"); $vulnerableNSGsWithRules = @(); $this.GetVMNICObjects() | ForEach-Object { $effectiveNSG = $null; try { $effectiveNSG = Get-AzureRmEffectiveNetworkSecurityGroup -NetworkInterfaceName $_.Name -ResourceGroupName $_.ResourceGroupName -WarningAction SilentlyContinue -ErrorAction Stop } catch { $isManual = $true $statusCode = ($_.Exception).InnerException.Response.StatusCode; if($statusCode -eq [System.Net.HttpStatusCode]::BadRequest -or $statusCode -eq [System.Net.HttpStatusCode]::Forbidden) { $controlResult.AddMessage(($_.Exception).InnerException.Message); } else { throw $_ } } if($effectiveNSG) { $vulnerableRules = @(); $vulnerableRules += $effectiveNSG.EffectiveSecurityRules | Where-Object { ($_.direction -eq "Inbound") -and ($_.access -eq "Allow") -and ($_.destinationPortRange -like "*$($this.ControlSettings.VirtualMachine.RDP_Port)*" -or $_.destinationPortRange -like "*$($this.ControlSettings.VirtualMachine.WinRM_Port)*")} if($vulnerableRules.Count -ne 0) { $vulnerableNSGsWithRules += @{ Association = $effectiveNSG.Association; NetworkSecurityGroup = $effectiveNSG.NetworkSecurityGroup; VulnerableRules = $vulnerableRules; NicName = $_.Name }; } } } if($isManual) { $controlResult.AddMessage([VerificationResult]::Manual, "We are not able to check the NSG rules for some NICs. Please validate manually."); if($vulnerableNSGsWithRules.Count -ne 0) { $controlResult.AddMessage([VerificationResult]::Manual, "Management ports are open on Virtual Machine. Please verify and remove the NSG rules in order to comply.", $vulnerableNSGsWithRules); } } else { if($vulnerableNSGsWithRules.Count -eq 0) { $controlResult.AddMessage([VerificationResult]::Passed, "No management ports are open on Virtual Machine"); } else { $controlResult.AddMessage([VerificationResult]::Failed, "Management ports are open on Virtual Machine. Please verify and remove the NSG rules in order to comply.", $vulnerableNSGsWithRules); } } return $controlResult; } }
PowerShellCorpus/PowerShellGallery/AzSDKPreview/2.2.0/Framework/Core/SVT/Services/RedisCache.ps1
RedisCache.ps1
Set-StrictMode -Version Latest class RedisCache: SVTBase { hidden [PSObject] $ResourceObject; RedisCache([string] $subscriptionId, [string] $resourceGroupName, [string] $resourceName): Base($subscriptionId, $resourceGroupName, $resourceName) { $this.GetResourceObject(); } RedisCache([string] $subscriptionId, [SVTResource] $svtResource): Base($subscriptionId, $svtResource) { $this.GetResourceObject(); } hidden [PSObject] GetResourceObject() { if (-not $this.ResourceObject) { $this.ResourceObject = Get-AzureRmRedisCache -Name $this.ResourceContext.ResourceName -ResourceGroupName $this.ResourceContext.ResourceGroupName -ErrorAction Stop if(-not $this.ResourceObject) { throw ("Resource '{0}' not found under Resource Group '{1}'" -f ($this.ResourceContext.ResourceName), ($this.ResourceContext.ResourceGroupName)) } } return $this.ResourceObject; } hidden [ControlResult] CheckRedisCacheFirewallIPAddressRange([ControlResult] $controlResult) { #check for applicablle sku $RDBBackupSkuMappingCheck = $this.ControlSettings.RedisCache.FirewallApplicableSku | Where-Object { $_ -eq $this.ResourceObject.Sku } | Select-Object -First 1; if(-not $RDBBackupSkuMappingCheck) { $controlResult.AddMessage([VerificationResult]::Failed, [MessageData]::new("Firewall settings are not supported for Sku Tier - [$($this.ResourceObject.Sku)]")); return $controlResult; } #PowerShell Get command is provided for Firewall setting. Using Rest API to get firewall details $uri = [string]::Format("{0}{1}/firewallRules?api-version=2016-04-01",[WebRequestHelper]::AzureManagementUri,$this.ResourceObject.Id) $result = [WebRequestHelper]::InvokeGetWebRequest($uri) if($null -ne $result){ #Filtering web request responce and getting only required details $firewallDtls = $result | select name , @{Label="StartIp"; Expression={$_.properties.startIp}} , @{Label="EndIp"; Expression={$_.properties.endIp} } | Where-Object { $null -ne $_.StartIp -and $null -ne $_.endIp } if(($firewallDtls | Measure-Object ).Count -gt 0){ $controlResult.AddMessage([MessageData]::new("Current firewall settings for - ["+ $this.ResourceContext.ResourceName +"]", $firewallDtls)); #Check for any to any firewall rule. $anyToAnyRule = $firewallDtls | Where-Object { $_.StartIp -eq $this.ControlSettings.IPRangeStartIP -and $_.EndIp -eq $this.ControlSettings.IPRangeEndIP} if (($anyToAnyRule | Measure-Object).Count -gt 0){ $controlResult.AddMessage([VerificationResult]::Failed, [MessageData]::new("Firewall rule covering all IPs (Start IP address: $($this.ControlSettings.IPRangeStartIP) To End IP Address: $($this.ControlSettings.IPRangeEndIP)) is defined.")); } else { $controlResult.VerificationResult = [VerificationResult]::Verify } } else { $controlResult.AddMessage([VerificationResult]::Verify, "Firewall rules are not defined"); } } else { $controlResult.AddMessage("Unable to get Firewall settings for - ["+ $this.ResourceContext.ResourceName +"]"); } return $controlResult } hidden [ControlResult] CheckRedisCacheRDBBackup([ControlResult] $controlResult) { #check for applicablle sku $RDBBackupSkuMappingCheck = $this.ControlSettings.RedisCache.RDBBackApplicableSku | Where-Object { $_ -eq $this.ResourceObject.Sku } | Select-Object -First 1; if(-not $RDBBackupSkuMappingCheck) { $controlResult.AddMessage([VerificationResult]::Failed, [MessageData]::new("RDB Backup are not supported for Sku Tier - [$($this.ResourceObject.Sku)]")); return $controlResult; } if($null -ne $this.ResourceObject.RedisConfiguration){ if(($this.ResourceObject.RedisConfiguration.Keys.Contains('rdb-backup-enabled')) -and ($this.ResourceObject.RedisConfiguration.'rdb-backup-enabled' -eq $true)){ $controlResult.AddMessage([VerificationResult]::Passed, "RDB Backup is enabled"); } else{ $controlResult.AddMessage([VerificationResult]::Failed, "RDB Backup is not enabled"); } } else{ $controlResult.AddMessage("Unable to get RDB backup details for - [$($this.ResourceContext.ResourceName)]"); } return $controlResult } hidden [ControlResult] CheckRedisCacheSSLConfig([ControlResult] $controlResult) { if($null -ne $this.ResourceObject.EnableNonSslPort){ if($this.ResourceObject.EnableNonSslPort -eq $false){ $controlResult.AddMessage([VerificationResult]::Passed, "Non-SSL port is not enabled"); } else{ $controlResult.AddMessage([VerificationResult]::Failed, "Non-SSL port is enabled"); } } else{ $controlResult.AddMessage("Unable to get SSL Configuration details for - [$($this.ResourceContext.ResourceName)]"); } return $controlResult } }
PowerShellCorpus/PowerShellGallery/AzSDKPreview/2.2.0/Framework/Core/SVT/Services/CDN.ps1
CDN.ps1
Set-StrictMode -Version Latest class CDN: SVTBase { hidden [PSObject] $ResourceObject; CDN([string] $subscriptionId, [string] $resourceGroupName, [string] $resourceName): Base($subscriptionId, $resourceGroupName, $resourceName) { } CDN([string] $subscriptionId, [SVTResource] $svtResource): Base($subscriptionId, $svtResource) { } hidden [ControlResult] CheckCDNHttpsProtocol([ControlResult] $controlResult) { $cdnEndpoints = Get-AzureRmCdnEndpoint -ProfileName $this.ResourceContext.ResourceName ` -ResourceGroupName $this.ResourceContext.ResourceGroupName ` -ErrorAction Stop if(($cdnEndpoints | Measure-Object).Count -eq 0) { $controlResult.AddMessage([VerificationResult]::Passed, [MessageData]::new("No CDN endpoints are found in the CDN profile.")); } else { $httpAllowedEndpointList = $cdnEndpoints | Where-Object { $_.IsHttpAllowed -eq $true } if(($httpAllowedEndpointList | Measure-Object).Count -eq 0) { $controlResult.AddMessage([VerificationResult]::Passed, [MessageData]::new("All CDN endpoints in the CDN profile [" + $this.ResourceContext.ResourceName + "] are using HTTPS protocol only - ", ($cdnEndpoints | Select-Object -Property Name, HostName, OriginHostHeader, IsHttpAllowed, IsHttpsAllowed))); } else { $controlResult.AddMessage([VerificationResult]::Failed, [MessageData]::new("Below CDN endpoints in the CDN profile [" + $this.ResourceContext.ResourceName + "] are using HTTP protocol - ", ($httpAllowedEndpointList | Select-Object -Property Name, HostName, OriginHostHeader, IsHttpAllowed, IsHttpsAllowed))); } } return $controlResult; } }
PowerShellCorpus/PowerShellGallery/AzSDKPreview/2.2.0/Framework/Core/SVT/Services/CloudService.ps1
CloudService.ps1
# # CloudServices.ps1 # Set-StrictMode -Version Latest class CloudService: SVTBase { hidden [PSCloudService] $ResourceObject; CloudService([string] $subscriptionId, [string] $resourceGroupName, [string] $resourceName): Base($subscriptionId, $resourceGroupName, $resourceName) { $this.GetResourceObject(); } CloudService([string] $subscriptionId, [SVTResource] $svtResource): Base($subscriptionId, $svtResource) { $this.GetResourceObject(); } hidden [PSObject] GetResourceObject() { if (-not $this.ResourceObject) { $cloudService = Get-AzureRmResource -ResourceName $this.ResourceContext.ResourceName ` -ResourceType "Microsoft.ClassicCompute/domainNames" ` -ResourceGroupName $this.ResourceContext.ResourceGroupName ` -ErrorAction Stop $this.UpdateCloudServiceInstance() if(-not $this.ResourceObject) { throw ("Resource '{0}' not found under Resource Group '{1}'" -f ($this.ResourceContext.ResourceName), ($this.ResourceContext.ResourceGroupName)) } } return $this.ResourceObject; } hidden [void] UpdateCloudServiceInstance() { $ResourceAppIdURI = [WebRequestHelper]::ClassicManagementUri; $ClassicAccessToken = [Helpers]::GetAccessToken($ResourceAppIdURI) if($null -ne $ClassicAccessToken) { $header = "Bearer " + $ClassicAccessToken $headers = @{"Authorization"=$header;"Content-Type"="application/json"; "x-ms-version" ="2013-08-01"} $uri = [string]::Format("{0}/{1}/services/hostedservices/{2}?embed-detail=true","https://management.core.windows.net", $this.SubscriptionContext.SubscriptionId ,$this.ResourceContext.ResourceName) $cloudServiceResponse = Invoke-WebRequest -Method GET -Uri $uri -Headers $headers if($cloudServiceResponse.StatusCode -ge 200 -and $cloudServiceResponse.StatusCode -le 399) { if($null -ne $cloudServiceResponse.Content) { [xml] $cloudService = $cloudServiceResponse.Content $this.ResourceObject = [PSCloudService]::new() $this.ResourceObject.LoadCloudConfiguration($cloudServiceResponse.Content); } } } } hidden [ControlResult] CheckCloudServiceHttpCertificateSSLOnInstanceEndpoints([ControlResult] $controlResult) { $isCompliant = $true; $nonCompliantInstanceEndpoints = @(); if($null -ne $this.ResourceObject -and $null -ne $this.ResourceObject.RoleInstances) { $this.ResourceObject.RoleInstances | Foreach-Object{ $roleInstance = $_; if($null -ne $roleInstance) { $roleInstance.InstanceEndpoints | ForEach-Object { $instanceEndpoint = $_ if($instanceEndpoint.Protocol -eq "http") { $isCompliant = $false; $nonCompliantInstanceEndpoints += $_ } } } } } if($isCompliant) { $controlResult.VerificationResult = [VerificationResult]::Passed; } else { #$controlResult.AddMessage([VerificationResult]::Failed, "Instance endpoints of cloud service must have http disabled.",$nonCompliantInstanceEndpoints, $true, "InstanceEndpoints"); $controlResult.AddMessage([VerificationResult]::Failed, "Instance endpoints of cloud service must have http disabled.",$nonCompliantInstanceEndpoints); } return $controlResult; } hidden [ControlResult] CheckCloudServiceHttpCertificateSSLOnInputEndpoints([ControlResult] $controlResult) { $isCompliant = $true; $nonCompliantInputEndpoints = @(); if($null -ne $this.ResourceObject -and $null -ne $this.ResourceObject.Roles) { $this.ResourceObject.Roles | Foreach-Object { $role = $_; if($null -ne $role.InputEndpoint) { $role.InputEndpoint | ForEach-Object { $endpoint = $_ if($endpoint.Protocol -eq "http") { $isCompliant = $false; $nonCompliantInputEndpoints += $_ } } } } } if($isCompliant) { $controlResult.VerificationResult = [VerificationResult]::Passed; } else { #$controlResult.AddMessage([VerificationResult]::Failed, "Input endpoints of cloud service must have http disabled.", $nonCompliantInputEndpoints, $true, "InputEndpoints"); $controlResult.AddMessage([VerificationResult]::Failed, "Input endpoints of cloud service must have http disabled.", $nonCompliantInputEndpoints); } return $controlResult; } hidden [ControlResult] CheckCloudServiceInstanceEndpointsIPSettings([ControlResult] $controlResult) { $instanceEndpoints = @(); if($null -ne $this.ResourceObject -and $null -ne $this.ResourceObject.RoleInstances) { $this.ResourceObject.RoleInstances | Foreach-Object{ $roleInstance = $_; if($null -ne $roleInstance) { $roleInstance.InstanceEndpoints | ForEach-Object { $instanceEndpoints += $_ } } } } #$controlResult.AddMessage([VerificationResult]::Verify, "Validate the IP Settings configured for the instance endpoints on cloud service.", $instanceEndpoints, $true, "InstanceEndpoints" ); $controlResult.AddMessage([VerificationResult]::Verify, "Validate the IP Settings configured for the instance endpoints on cloud service.", $instanceEndpoints); return $controlResult; } hidden [ControlResult] CheckCloudServiceInputEndpoints([ControlResult] $controlResult) { $isCompliant = $true; $inputEndpoints = @(); if($null -ne $this.ResourceObject -and $null -ne $this.ResourceObject.Roles) { $this.ResourceObject.Roles | Foreach-Object { $role = $_; if($null -ne $role.InputEndpoint) { $role.InputEndpoint | ForEach-Object { $inputEndpoints += $role.InputEndpoint } } } } #$controlResult.AddMessage([VerificationResult]::Verify, "Remove any un-used internal endpoints from your cloud service.", $inputEndpoints, $true, "InputEndpoints" ); $controlResult.AddMessage([VerificationResult]::Verify, "Remove any un-used internal endpoints from your cloud service.", $inputEndpoints); return $controlResult; } hidden [ControlResult] CheckCloudServiceRemoteDebuggingStatus([ControlResult] $controlResult) { $isCompliant = $true; $nonCompliantInstanceEndpoints = @(); if($null -ne $this.ResourceObject -and $null -ne $this.ResourceObject.RoleInstances) { $this.ResourceObject.RoleInstances | Foreach-Object{ $roleInstance = $_; if($null -ne $roleInstance) { $roleInstance.InstanceEndpoints | ForEach-Object { $instanceEndpoint = $_ if($instanceEndpoint.Name -like "Microsoft.WindowsAzure.Plugins.RemoteDebugger*") { $isCompliant = $false; $nonCompliantInstanceEndpoints += $_ } } } } } if($isCompliant) { $controlResult.VerificationResult = [VerificationResult]::Passed; } else { #$controlResult.AddMessage([VerificationResult]::Failed, "Remote debugging endpoints enabled on cloud service.", $nonCompliantInstanceEndpoints, $true, "InstanceEndpoints"); $controlResult.AddMessage([VerificationResult]::Failed, "Remote debugging endpoints enabled on cloud service.", $nonCompliantInstanceEndpoints); } return $controlResult; } hidden [ControlResult] CheckCloudServiceAntiMalwareStatus([ControlResult] $controlResult) { $isCompliant = $false; $extensions = @{}; if($null -ne $this.ResourceObject -and $null -ne $this.ResourceObject.Extensions) { $this.ResourceObject.Extensions | Foreach-Object{ $extension = $_; $extensions.Add($extension.RoleName,$false); if($null -ne $extension -and $null -ne $extension.ExtensionId) { $extension.ExtensionId | ForEach-Object { $extensionId = $_ if($extensionId.Id -like "*Antimalware*") { $extensions[$extension.RoleName] = $true } } } } } if(($extensions.Values | Where-Object {-not $_} | Measure-Object).Count -le 0) { $controlResult.VerificationResult = [VerificationResult]::Passed; } else { #$controlResult.AddMessage([VerificationResult]::Failed, "Antimalware extension is not enabled on cloud service.", $this.ResourceObject.Extensions, $true, "Extensions"); $controlResult.AddMessage([VerificationResult]::Failed, "Antimalware extension is not enabled on cloud service.", $this.ResourceObject.Extensions); } return $controlResult; } hidden [ControlResult] CheckCloudServiceRemoteDesktopAccess([ControlResult] $controlResult) { $extensions = @{}; if($null -ne $this.ResourceObject -and $null -ne $this.ResourceObject.Extensions) { $this.ResourceObject.Extensions | Foreach-Object{ $extension = $_; $extensions.Add($extension.RoleName,$true); if($null -ne $extension -and $null -ne $extension.ExtensionId) { $extension.ExtensionId | ForEach-Object { $extensionId = $_ if($extensionId.Id -like "*RDP*") { $extensions[$extension.RoleName] = $false } } } } } if(($extensions.Values | Where-Object {-not $_} | Measure-Object).Count -le 0) { $isCompliant = $true; } else { $isCompliant = $false; #$controlResult.AddMessage("Remote desktop endpoints are enabled on cloud service.", $extensions, $true, "InstanceEndpoints"); $controlResult.AddMessage("Remote desktop endpoints are enabled on cloud service.", $extensions); } #$b.ServiceConfiguration.Role[0].ConfigurationSettings.Setting.SyncRoot["Microsoft.WindowsAzure.Plugins.RemoteAccess.Enabled"] $nonCompliantInstanceEndpoints = @(); if($isCompliant) { if($null -ne $this.ResourceObject -and $null -ne $this.ResourceObject.RoleInstances) { $this.ResourceObject.RoleInstances | Foreach-Object{ $roleInstance = $_; if($null -ne $roleInstance) { $roleInstance.InstanceEndpoints | ForEach-Object { $instanceEndpoint = $_ if($instanceEndpoint.Name -like "Microsoft.WindowsAzure.Plugins.RemoteForwarder*") { $isCompliant = $false; $nonCompliantInstanceEndpoints += $_ } } } } } } if(-not $isCompliant) { if($null -ne $this.ResourceObject.Configuration -and $null -ne $this.ResourceObject.Configuration.ServiceConfiguration -and $null -ne $this.ResourceObject.Configuration.ServiceConfiguration.Role) { $isRemoteAccessEnabled = $false; $tempRoles = $this.ResourceObject.Configuration.ServiceConfiguration.Role; $tempRoles | ForEach-Object { $tempRole = $_; if($null -ne $tempRole.ConfigurationSettings -and $null -ne $tempRole.ConfigurationSettings.Setting) { $remoteEndpointValue = $tempRole.ConfigurationSettings.Setting | Where-Object { $_.name -eq 'Microsoft.WindowsAzure.Plugins.RemoteAccess.Enabled'} if(($remoteEndpointValue| Measure-Object).Count -eq 1) { if(-not $isRemoteAccessEnabled) { $isRemoteAccessEnabled = [bool]::Parse($remoteEndpointValue.Value); } } } } if(-not $isRemoteAccessEnabled) { $isCompliant = $true; } else { #$controlResult.AddMessage("Remote desktop endpoints are enabled on cloud service.", $nonCompliantInstanceEndpoints, $true, "InstanceEndpoints"); $controlResult.AddMessage("Remote desktop endpoints are enabled on cloud service.", $nonCompliantInstanceEndpoints); } } } if($isCompliant) { $controlResult.VerificationResult = [VerificationResult]::Passed; } else { $controlResult.VerificationResult = [VerificationResult]::Failed; } return $controlResult; } }
PowerShellCorpus/PowerShellGallery/AzSDKPreview/2.2.0/Framework/Core/SVT/Services/Storage.ps1
Storage.ps1
using namespace Microsoft.Azure.Management.Storage.Models using namespace Microsoft.WindowsAzure.Storage.Shared.Protocol Set-StrictMode -Version Latest class Storage: SVTBase { hidden [PSObject] $ResourceObject; Storage([string] $subscriptionId, [string] $resourceGroupName, [string] $resourceName): Base($subscriptionId, $resourceGroupName, $resourceName) { $this.GetResourceObject(); } Storage([string] $subscriptionId, [SVTResource] $svtResource): Base($subscriptionId, $svtResource) { $this.GetResourceObject(); } hidden [PSObject] GetResourceObject() { if (-not $this.ResourceObject) { $this.ResourceObject = Get-AzureRmStorageAccount -Name $this.ResourceContext.ResourceName -ResourceGroupName $this.ResourceContext.ResourceGroupName -ErrorAction Stop if(-not $this.ResourceObject) { throw ("Resource '{0}' not found under Resource Group '{1}'" -f ($this.ResourceContext.ResourceName), ($this.ResourceContext.ResourceGroupName)) } } return $this.ResourceObject; } hidden [ControlResult] CheckStorageContainerPublicAccessTurnOff([ControlResult] $controlResult) { $allContainers = @(); try { $allContainers += Get-AzureStorageContainer -Context $this.ResourceObject.Context -ErrorAction Stop } catch { if(($_.Exception).Response.StatusCode -eq [System.Net.HttpStatusCode]::Forbidden) { $controlResult.AddMessage([VerificationResult]::Manual, ($_.Exception).Message); return $controlResult } else { throw $_ } } #Containers others than private $publicContainers = $allContainers | Where-Object { $_.PublicAccess -ne [Microsoft.WindowsAzure.Storage.Blob.BlobContainerPublicAccessType]::Off } if(($publicContainers | Measure-Object ).Count -eq 0) { $controlResult.AddMessage([VerificationResult]::Passed, "There are no containers having pubic access with anonymous authentication"); } else { $controlResult.AddMessage([VerificationResult]::Failed , [MessageData]::new("Remove public access from following containers. Total - $(($publicContainers | Measure-Object ).Count)", ($publicContainers | Select-Object -Property Name, PublicAccess))); } return $controlResult; } hidden [ControlResult] CheckStorageEnableDiagnosticsLog([ControlResult] $controlResult) { #Checking for storage kind $serviceMapping = $this.ControlSettings.StorageKindMapping | Where-Object { $_.Kind -eq $this.ResourceObject.Kind } | Select-Object -First 1; if(-not $serviceMapping) { #Currently only 'General purpose' or 'Blob storage' account kind is present #If new storage kind is introduced code needs to be updated as per new storage kind $controlResult.AddMessage("Storage Account kind is not supported"); return $controlResult; } #Checking for premium storage $daignosticsSkuMapping = $this.ControlSettings.StorageDiagnosticsSkuMapping | Where-Object { $_ -eq $this.ResourceObject.Sku.Name } | Select-Object -First 1; if(-not $daignosticsSkuMapping) { #Daignostics settings are not availeble for premium storage. $controlResult.AddMessage([VerificationResult]::Failed, [MessageData]::new("Diagnostics settings are not supported for Sku Tier - [$($this.ResourceObject.Sku.Name)]")); return $controlResult; } try{ $result = $true #Check Metrics diagnistics log property $serviceMapping.DiagnosticsLogServices | ForEach-Object { $result = $this.GetServiceLoggingProperty($_, $controlResult) -and $result ; } #Check Metrics logging property $serviceMapping.Services | ForEach-Object { $result = $this.GetServiceMetricsProperty($_, $controlResult) -and $result ; } if($result){ $controlResult.VerificationResult = [VerificationResult]::Passed } else{ $controlResult.VerificationResult = [VerificationResult]::Failed } } catch{ #With Reader Role exception will be is thrown. if(($_.Exception).Response.StatusCode -eq [System.Net.HttpStatusCode]::Forbidden) { $controlResult.AddMessage("Access denied: The user does not have the permission to perform this operation. Please check Diagnostics settings manually."); return $controlResult } else { throw $_ } } return $controlResult; } hidden [ControlResult] CheckStorageGeoRedundantReplication([ControlResult] $controlResult) { if($null -ne $this.ResourceObject.Sku.Tier -and $null -ne $this.ResourceObject.Sku.Name){ $controlResult.AddMessage("Current storage sku tier is - [$($this.ResourceObject.Sku.Tier)] and sku name is - [$($this.ResourceObject.Sku.Name)]"); } else{ $controlResult.AddMessage("Unable to get sku details for - [$($this.ResourceContext.ResourceName)]"); return $controlResult } if($this.ResourceObject.Sku.Tier -eq [SkuTier]::Standard){ $isGeoRedundantSku = $this.ControlSettings.StorageGeoRedundantSku | Where-Object { $_ -eq $this.ResourceObject.Sku.Name } | Select-Object -First 1; if($isGeoRedundantSku){ $controlResult.VerificationResult = [VerificationResult]::Passed } else { $controlResult.VerificationResult = [VerificationResult]::Failed } } else{ $controlResult.AddMessage([VerificationResult]::Failed, [MessageData]::new("This security control is applicable for below sku -",$this.ControlSettings.StorageGeoRedundantSku)); } return $controlResult; } hidden [ControlResult] CheckStorageBlobEncryptionEnabled([ControlResult] $controlResult) { if($null -ne $this.ResourceObject.Encryption) { if($null -eq $this.ResourceObject.Encryption.Services.Blob.Enabled ){ $controlResult.AddMessage([MessageData]::new("Unable to get Blob encryption setting's")) return $controlResult; } if($this.ResourceObject.Encryption.Services.Blob.Enabled -eq $true){ $controlResult.VerificationResult = [VerificationResult]::Passed } else{ $controlResult.VerificationResult = [VerificationResult]::Failed } } else { $controlResult.AddMessage([MessageData]::new("Storage blob encryption is not enabled")) $controlResult.VerificationResult = [VerificationResult]::Failed } return $controlResult; } hidden [ControlResult] CheckStorageMetricAlert([ControlResult] $controlResult) { $serviceMapping = $this.ControlSettings.StorageKindMapping | Where-Object { $_.Kind -eq $this.ResourceObject.Kind } | Select-Object -First 1; if(-not $serviceMapping) { #Currently only 'General purpose' or 'Blob storage' account kind is present #If new storage kind is introduced code needs to be updated as per new storage kind $controlResult.AddMessage("Storage Account kind is not supported"); return $controlResult; } $result = $true; $serviceMapping.Services | ForEach-Object { $result = $this.CheckMetricAlertConfiguration($this.ControlSettings.MetricAlert.Storage, $controlResult, ("/services/" + $_)) -and $result ; } if($result) { $controlResult.VerificationResult = [VerificationResult]::Passed } else { $controlResult.VerificationResult = [VerificationResult]::Failed } return $controlResult; } hidden [boolean] GetServiceLoggingProperty([string] $serviceType,[ControlResult] $controlResult) { $loggingProperty = Get-AzureStorageServiceLoggingProperty -ServiceType $ServiceType -Context $this.ResourceObject.Context -ErrorAction Stop if($null -ne $loggingProperty){ #Check For Retention day's if($loggingProperty.LoggingOperations -eq [LoggingOperations]::All -and (($loggingProperty.RetentionDays -eq $this.ControlSettings.Diagnostics_RetentionPeriod_Forever) -or ($loggingProperty.RetentionDays -eq $this.ControlSettings.Diagnostics_RetentionPeriod_Min))){ return $True } else{ $controlResult.AddMessage("Diagnostics settings($($serviceType) logs) is either disabled OR not retaining logs for atleast $($this.ControlSettings.Diagnostics_RetentionPeriod_Min) days for service type - [$($serviceType)]") return $false } } else { $controlResult.AddMessage("Diagnostics settings($($serviceType) logs) is disabled for service type - [$($serviceType)]") return $false } } hidden [boolean] GetServiceMetricsProperty([string] $serviceType,[ControlResult] $controlResult) { $serviceMetricsProperty= Get-AzureStorageServiceMetricsProperty -MetricsType Hour -ServiceType $ServiceType -Context $this.ResourceObject.Context -ErrorAction Stop if($null -ne $serviceMetricsProperty){ #Check For Retention day's if($serviceMetricsProperty.MetricsLevel -eq [MetricsLevel]::ServiceAndApi -and (($serviceMetricsProperty.RetentionDays -eq $this.ControlSettings.Diagnostics_RetentionPeriod_Min) -or ($serviceMetricsProperty.RetentionDays -eq $this.ControlSettings.Diagnostics_RetentionPeriod_Forever))) { return $True } else { $controlResult.AddMessage("Diagnostics settings($($serviceType) aggregate metrics,$($serviceType) per API metrics) is either disabled OR not retaining logs for atleast $($this.ControlSettings.Diagnostics_RetentionPeriod_Min) days for service type - [$($serviceType)]") return $false } } else { $controlResult.AddMessage("Diagnostics settings($($serviceType) aggregate metrics,$($serviceType) per API metrics) is disabled for service type - [$($serviceType)]") return $false } } }
PowerShellCorpus/PowerShellGallery/AzSDKPreview/2.2.0/Framework/Core/SVT/Services/Batch.ps1
Batch.ps1
Set-StrictMode -Version Latest class Batch: SVTBase { Batch([string] $subscriptionId, [string] $resourceGroupName, [string] $resourceName): Base($subscriptionId, $resourceGroupName, $resourceName) { } Batch([string] $subscriptionId, [SVTResource] $svtResource): Base($subscriptionId, $svtResource) { } hidden [ControlResult] CheckBatchStorageSSE([ControlResult] $controlResult) { $batchResource = Get-AzureRmBatchAccount -AccountName $this.ResourceContext.ResourceName -ResourceGroupName $this.ResourceContext.ResourceGroupName if($batchResource) { if($batchResource.AutoStorageProperties -and (-not [string]::IsNullOrEmpty($batchResource.AutoStorageProperties.StorageAccountId))) { $storageAccount = Get-AzureRmResource -ResourceId $batchResource.AutoStorageProperties.StorageAccountId -ExpandProperties if($storageAccount -and $storageAccount.Properties) { if((Get-Member -InputObject $storageAccount.Properties -Name 'encryption' -MemberType Properties) -and $storageAccount.Properties.encryption.services -and $storageAccount.Properties.encryption.services.blob -and $storageAccount.Properties.encryption.services.blob.enabled -eq $true) { $controlResult.AddMessage([VerificationResult]::Passed, "Storage Service Encryption is enabled on blob service of Storage Account [$($storageAccount.ResourceName)] associated with Batch account", $storageAccount.Properties.encryption.services); } else { $controlResult.AddMessage([VerificationResult]::Failed, "Storage Service Encryption is not enabled on blob service of Storage Account [$($storageAccount.ResourceName)] associated with Batch account"); } } else { $controlResult.AddMessage([MessageData]::new("No valid Storage Account found which is associated with Batch account", [MessageType]::Error)); } } else { $controlResult.AddMessage([MessageData]::new("No valid Storage Account found which is associated with Batch account", [MessageType]::Error)); } } else { $controlResult.AddMessage([MessageData]::new("We are not able to fetch the required data for the resource", [MessageType]::Error)); } return $controlResult; } hidden [ControlResult] CheckBatchMetricAlert([ControlResult] $controlResult) { $this.CheckMetricAlertConfiguration($this.ControlSettings.MetricAlert.Batch, $controlResult, ""); return $controlResult; } }
PowerShellCorpus/PowerShellGallery/AzSDKPreview/2.2.0/Framework/Core/SVT/Services/ODG.ps1
ODG.ps1
#using namespace Microsoft.Azure.Commands.EventHub.Models Set-StrictMode -Version Latest class ODG: SVTBase { ODG([string] $subscriptionId, [string] $resourceGroupName, [string] $resourceName): Base($subscriptionId, $resourceGroupName, $resourceName) { } ODG([string] $subscriptionId, [SVTResource] $svtResource): Base($subscriptionId, $svtResource) { } }
PowerShellCorpus/PowerShellGallery/AzSDKPreview/2.2.0/Framework/Core/SVT/Services/DataLakeAnalytics.ps1
DataLakeAnalytics.ps1
Set-StrictMode -Version Latest class DataLakeAnalytics: SVTBase { hidden [PSObject] $ResourceObject; DataLakeAnalytics([string] $subscriptionId, [string] $resourceGroupName, [string] $resourceName): Base($subscriptionId, $resourceGroupName, $resourceName) { $this.GetResourceObject(); } DataLakeAnalytics([string] $subscriptionId, [SVTResource] $svtResource): Base($subscriptionId, $svtResource) { $this.GetResourceObject(); } hidden [PSObject] GetResourceObject() { if (-not $this.ResourceObject) { $this.ResourceObject = Get-AzureRmDataLakeAnalyticsAccount -Name $this.ResourceContext.ResourceName ` -ResourceGroupName $this.ResourceContext.ResourceGroupName if(-not $this.ResourceObject) { throw ("Resource '{0}' not found under Resource Group '{1}'" -f ($this.ResourceContext.ResourceName), ($this.ResourceContext.ResourceGroupName)) } } return $this.ResourceObject; } hidden [ControlResult] CheckEncryptionAtRest([ControlResult] $controlResult) { $defaultADLSAccount = Get-AzureRmDataLakeStoreAccount -Name $this.ResourceObject.DefaultDataLakeStoreAccount -ResourceGroupName $this.ResourceContext.ResourceGroupName if($defaultADLSAccount) { $encryptionSettings = $defaultADLSAccount | Select-Object -Property EncryptionConfig, EncryptionState, EncryptionProvisioningState if($defaultADLSAccount.EncryptionState -eq [Microsoft.Azure.Management.DataLake.Store.Models.EncryptionState]::Enabled) { $controlResult.VerificationResult = [VerificationResult]::Passed; } else { $controlResult.VerificationResult = [VerificationResult]::Failed; } $controlResult.AddMessage("Encryption settings of default Data Lake Store account [$($this.ResourceObject.DefaultDataLakeStoreAccount)]", $encryptionSettings); } else { $controlResult.AddMessage([MessageData]::new("We are not able to fetch the details of default Data Lake Store account [$($this.ResourceObject.DefaultDataLakeStoreAccount)]", [MessageType]::Error)); } return $controlResult; } }
PowerShellCorpus/PowerShellGallery/AzSDKPreview/2.2.0/Framework/Core/SVT/Services/DataFactory.ps1
DataFactory.ps1
#using namespace Microsoft.Azure.Commands.DataFactory.Models Set-StrictMode -Version Latest class DataFactory: SVTBase { DataFactory([string] $subscriptionId, [string] $resourceGroupName, [string] $resourceName): Base($subscriptionId, $resourceGroupName, $resourceName) { } DataFactory([string] $subscriptionId, [SVTResource] $svtResource): Base($subscriptionId, $svtResource) { } hidden [ControlResult] CheckDataFactoryLinkedService([ControlResult] $controlResult) { # Get all the Linked Service $linkedServices = @(); $linkedServices += Get-AzureRmDataFactoryLinkedService -ResourceGroupName $this.ResourceContext.ResourceGroupName -DataFactoryName $this.ResourceContext.ResourceName if($linkedServices.Count -gt 0) { $linkedServicesProps = $linkedServices | Select-Object -Property LinkedServiceName, Properties #@{ Label="Type"; Expression= { $_.Properties.Type } }, #@{ Label="ProvisioningState"; Expression= { $_.Properties.ProvisioningState } }, #@{ Label="TypeProperties"; Expression= { $_.Properties.TypeProperties } }, $controlResult.AddMessage([VerificationResult]::Verify, "Validate that the following Linked Services are using encryption in transit. Total Linked Services found - $($linkedServices.Count)", $linkedServicesProps); } else { $controlResult.AddMessage([VerificationResult]::Passed, [MessageData]::new("The are no Linked Services configured in Data Factory - ["+ $this.ResourceContext.ResourceName +"]")); } return $controlResult; } }
PowerShellCorpus/PowerShellGallery/AzSDKPreview/2.2.0/Framework/Core/SVT/Services/KeyVault.ps1
KeyVault.ps1
using namespace Microsoft.Azure.Commands.KeyVault.Models Set-StrictMode -Version Latest class KeyVault: SVTBase { hidden [PSVault] $ResourceObject; KeyVault([string] $subscriptionId, [string] $resourceGroupName, [string] $resourceName): Base($subscriptionId, $resourceGroupName, $resourceName) { $this.GetResourceObject(); } KeyVault([string] $subscriptionId, [SVTResource] $svtResource): Base($subscriptionId, $svtResource) { $this.GetResourceObject(); } hidden [PSVault] GetResourceObject() { if (-not $this.ResourceObject) { $this.ResourceObject = Get-AzureRmKeyVault -VaultName $this.ResourceContext.ResourceName ` -ResourceGroupName $this.ResourceContext.ResourceGroupName if(-not $this.ResourceObject) { throw ("Resource '{0}' not found under Resource Group '{1}'" -f ($this.ResourceContext.ResourceName), ($this.ResourceContext.ResourceGroupName)) } } return $this.ResourceObject; } hidden [ControlResult] CheckAdvancedAccessPolicies([ControlResult] $controlResult) { $accessPolicies = @{}; $accessPolicies.Add("Enable access to Azure Virtual Machines for deployment", $this.ResourceObject.EnabledForDeployment); $accessPolicies.Add("Enable access to Azure Resource Manager for template deployment", $this.ResourceObject.EnabledForTemplateDeployment); $accessPolicies.Add("Enable access to Azure Disk Encryption for volume encryption", $this.ResourceObject.EnabledForDiskEncryption); if($this.ResourceObject.EnabledForDeployment -and $this.ResourceObject.EnabledForDiskEncryption -and $this.ResourceObject.EnabledForTemplateDeployment) { $controlResult.AddMessage([VerificationResult]::Failed, [MessageData]::new("All Advanced Access Policies are enabled - ["+ $this.ResourceContext.ResourceName +"]" , $accessPolicies)); } elseif($this.ResourceObject.EnabledForDeployment -or $this.ResourceObject.EnabledForDiskEncryption -or $this.ResourceObject.EnabledForTemplateDeployment) { $controlResult.AddMessage([VerificationResult]::Verify, [MessageData]::new("Validate Advanced Access Policies - ["+ $this.ResourceContext.ResourceName +"]" , $accessPolicies)); } else { $controlResult.AddMessage([VerificationResult]::Passed, [MessageData]::new("All Advanced Access Policies are disabled - ["+ $this.ResourceContext.ResourceName +"]", $accessPolicies)); } return $controlResult; } hidden [ControlResult] CheckAccessPolicies([ControlResult] $controlResult) { $accessPolicies = $this.ResourceObject.AccessPolicies $allPermisionUsers = $accessPolicies | Where-Object { $_.PermissionsToKeys -eq "All" -and $_.PermissionsToSecrets -eq "All" -and $_.PermissionsToCertificates -eq "All" } if(($allPermisionUsers | Measure-Object).count -gt 0) { $controlResult.VerificationResult = [VerificationResult]::Failed; $controlResult.AddMessage([MessageData]::new("Applications/Users having full control to Key/Secret/Certificate - ["+ $this.ResourceContext.ResourceName +"]" , $allPermisionUsers)); } else { $controlResult.VerificationResult = [VerificationResult]::Verify; } $controlResult.AddMessage([MessageData]::new("Validate access policies and their assigned permissions to Key/Secret/Certificate - ["+ $this.ResourceContext.ResourceName +"]" , $accessPolicies)); return $controlResult; } hidden [ControlResult] CheckKeyHSMProtected([ControlResult] $controlResult) { try { $allKeys = Get-AzureKeyVaultKey -VaultName $this.ResourceContext.ResourceName -ErrorAction Stop if(($allKeys | Measure-Object).Count -gt 0) { $nonHsmKeys = @(); $allKeys | ForEach-Object { Get-AzureKeyVaultKey -VaultName $this.ResourceContext.ResourceName -Name $_.Name -IncludeVersions | ForEach-Object { $nonHsmKeys += Get-AzureKeyVaultKey -VaultName $this.ResourceContext.ResourceName -Name $_.Name -Version $_.Version | Where-Object { $_.Attributes.KeyType -ne $this.ControlSettings.KeyVault.KeyType }; } } if(($nonHsmKeys | Measure-Object).Count -eq 0) { $controlResult.AddMessage( [VerificationResult]::Passed, [MessageData]::new("All Keys, including previous versions, are protected by HSM for Key Vault - ["+ $this.ResourceContext.ResourceName +"]")); } else { $controlResult.AddMessage([VerificationResult]::Failed, [MessageData]::new("Following Keys, including previous versions, are not protected by HSM. Delete the key versions in order to comply." , ($nonHsmKeys | Select-Object Name, Version -ExpandProperty Attributes ))); } } else { $controlResult.AddMessage([VerificationResult]::Passed, [MessageData]::new("No Keys found in - ["+ $this.ResourceContext.ResourceName +"]")); } } catch { if ($_.Exception.GetType().FullName -eq "Microsoft.Azure.KeyVault.Models.KeyVaultErrorException") { $controlResult.AddMessage([MessageData]::new("Access denied: Read access is required on Key Vault Keys.")); } else { throw $_ } } return $controlResult; } hidden [ControlResult] CheckKeyMinimumOperations([ControlResult] $controlResult) { try { $allKeys = Get-AzureKeyVaultKey -VaultName $this.ResourceContext.ResourceName -ErrorAction Stop if(($allKeys| Measure-Object).Count -gt 0) { $keyDetails = @(); $allKeys | ForEach-Object { Get-AzureKeyVaultKey -VaultName $this.ResourceContext.ResourceName -Name $_.Name -IncludeVersions | ForEach-Object { $key = Get-AzureKeyVaultKey -VaultName $this.ResourceContext.ResourceName -Name $_.Name -Version $_.Version #| Where-Object {$null -eq $_.Attributes.Expires } $keyDetails += $key #rename variable } } $controlResult.AddMessage([VerificationResult]::Verify, [MessageData]::new("Verify the operations permitted using Key on - ["+ $this.ResourceContext.ResourceName +"]", ($keyDetails | Select-Object Name, Version, @{Label="Key Operations"; Expression={[system.string]::Join(", ",$_.Key.KeyOps)}} ) ) ); } else { $controlResult.AddMessage([VerificationResult]::Passed, [MessageData]::new("No Keys found in - ["+ $this.ResourceContext.ResourceName +"]")); } } catch { if ($_.Exception.GetType().FullName -eq "Microsoft.Azure.KeyVault.Models.KeyVaultErrorException") { $controlResult.AddMessage([MessageData]::new("Access denied: Read access is required on Key Vault Keys.")); } else { throw $_ } } return $controlResult; } hidden [ControlResult] CheckAppAuthenticationCertificate([ControlResult] $controlResult) { try{ $outputList = @(); $appList = $this.GetAzureRmKeyVaultApplications() $appList | ForEach-Object { $credentials = Get-AzureRmADAppCredential -ApplicationId $_.ApplicationId $compliance = if (($credentials| Where-Object { $_.Type -eq $this.ControlSettings.KeyVault.ADAppCredentialTypePwd } | Measure-Object).Count -eq 0 ) { "Yes" } else { "No" } ; $output = New-Object System.Object $output | Add-Member -type NoteProperty -name AzureADAppName -Value $_.DisplayName $output | Add-Member -type NoteProperty -name ApplicationId -Value $_.ApplicationId $output | Add-Member -type NoteProperty -name CertificateCredentialCount -Value ($credentials | Where-Object { $_.Type -eq $this.ControlSettings.KeyVault.ADAppCredentialTypeCrt } | Measure-Object ).Count $output | Add-Member -type NoteProperty -name PasswordCredentialCount -Value ($credentials | Where-Object { $_.Type -eq $this.ControlSettings.KeyVault.ADAppCredentialTypePwd } | Measure-Object).Count $output | Add-Member -type NoteProperty -name Compliance -Value $compliance $outputList += $output; } if(($outputList| Measure-Object).Count -gt 0) { $controlResult.AddMessage([MessageData]::new("Compliance details of Azure Active Directory applications:", $outputList)); if (($outputList | Where-Object { ($_.Compliance -eq "No") } | Measure-Object ).Count -gt 0) { $controlResult.AddMessage([VerificationResult]::Failed , [MessageData]::new("Remove the password credentials from Azure AD Applications which are non-compliant.") ); } else { $controlResult.VerificationResult = [VerificationResult]::Passed } } else { $controlResult.AddMessage([VerificationResult]::Passed , [MessageData]::new("No Azure AD Applications have access to Key Vault.") ); } } catch { if ($_.Exception.GetType().FullName -eq "Microsoft.Azure.KeyVault.Models.KeyVaultErrorException") { $controlResult.AddMessage([MessageData]::new("Access denied: Read access is required on Key Vault Keys.")); } else { throw $_ } } return $controlResult; } hidden [ControlResult] CheckAppsSharingKayVault([ControlResult] $controlResult) { $appList = $this.GetAzureRmKeyVaultApplications() if( ($appList | Measure-Object ).Count -gt 1) { $controlResult.AddMessage([VerificationResult]::Verify, [MessageData]::new("Validate that Azure AD Applications requires access to Key Vault. Total:" + ($appList | Measure-Object ).Count , $appList)); } elseif( ($appList | Measure-Object ).Count -eq 1) { $controlResult.AddMessage([VerificationResult]::Passed, "Only 1 Azure AD Application has access to Key Vault.", $appList); } else { $controlResult.AddMessage([VerificationResult]::Passed, "No Azure AD Applications have access to Key Vault."); } return $controlResult; } hidden [ControlResult] CheckKeyExpirationDate([ControlResult] $controlResult) { $IsKeysCompliant = $True $IsAccessDenied = $False try { $allKeys = Get-AzureKeyVaultKey -VaultName $this.ResourceContext.ResourceName -ErrorAction Stop if(($allKeys| Measure-Object).Count -gt 0) { $keysWithoutExpiry = @(); $keysWithExpiry = @(); $longDurationActiveKeys = @(); $allKeys | ForEach-Object { Get-AzureKeyVaultKey -VaultName $this.ResourceContext.ResourceName -Name $_.Name -IncludeVersions | ForEach-Object { $key = Get-AzureKeyVaultKey -VaultName $this.ResourceContext.ResourceName -Name $_.Name -Version $_.Version #| Where-Object { $_.Attributes.Expires -eq $null } if($null -eq $key.Attributes.Expires) { $keysWithoutExpiry += $key } else { $keysWithExpiry += $key } } } if(($keysWithoutExpiry | Measure-Object ).Count -gt 0) { $IsKeysCompliant = $False $controlResult.AddMessage([MessageData]::new("Following Keys, including previous versions, does not have expiry date. Set the expiry date in order to comply.", ($keysWithoutExpiry | Select-Object -Property Name, Version -ExpandProperty Attributes) )); } if(($keysWithExpiry | Measure-Object ).Count -gt 0) { $controlResult.AddMessage([MessageData]::new("Keys, including previous versions, have expiry date for Key Vault - ["+$this.ResourceContext.ResourceName+"]", ($keysWithExpiry | Select-Object -Property Name, Version -ExpandProperty Attributes ) )); $keysWithExpiry | ForEach-Object { $startDate = [DateTime] $_.Attributes.Created if($null -ne $_.Attributes.NotBefore) { $startDate = [DateTime] $_.Attributes.NotBefore; } if ((((([DateTime] $_.Attributes.Expires) - $startDate).TotalDays)/($this.ControlSettings.KeyVault.KeyRotationDuration_Days)) -gt 1) { $longDurationActiveKeys += $_ } } if (($longDurationActiveKeys| Measure-Object ).Count -gt 0) { $IsKeysCompliant = $False $controlResult.AddMessage([MessageData]::new("Following Keys, including previous versions, are active for more than $($this.ControlSettings.KeyVault.KeyRotationDuration_Days) Days. Please delete/rotate the keys in order to comply.", ($longDurationActiveKeys | Select-Object -Property Name, Version -ExpandProperty Attributes ) )); } } } else { $controlResult.AddMessage( [MessageData]::new("No Keys found in - ["+ $this.ResourceContext.ResourceName +"]")); } } catch { $IsKeysCompliant = $False $IsAccessDenied = $True if ($_.Exception.GetType().FullName -eq "Microsoft.Azure.KeyVault.Models.KeyVaultErrorException") { $controlResult.AddMessage([MessageData]::new("Access denied: Read access is required on Key Vault Keys.")); } else { throw $_ } } $IsSecretCompliant = $True try { $allSecrets = Get-AzureKeyVaultSecret -VaultName $this.ResourceContext.ResourceName -ErrorAction Stop if(($allSecrets| Measure-Object).Count -gt 0) { $secretsWithoutExpiry = @(); $secretsWithExpiry = @(); $longDurationActiveSecrets = @(); $allSecrets | ForEach-Object { Get-AzureKeyVaultSecret -VaultName $this.ResourceContext.ResourceName -Name $_.Name -IncludeVersions | ForEach-Object { $secret = Get-AzureKeyVaultSecret -VaultName $this.ResourceContext.ResourceName -Name $_.Name -Version $_.Version #| Where-Object { $_.Attributes.Expires -eq $null } if($null -eq $secret.Attributes.Expires) { $secretsWithoutExpiry += $secret } else { $secretsWithExpiry += $secret } } } if(($secretsWithoutExpiry| Measure-Object ).Count -gt 0) { $IsSecretCompliant = $False $controlResult.AddMessage([MessageData]::new("Following Secrets, including previous versions, does not have expiry date. Set the expiry date in order to comply.", ($secretsWithoutExpiry | Select-Object Name, Version -ExpandProperty Attributes ) )); } if(($secretsWithExpiry| Measure-Object ).Count -gt 0) { $controlResult.AddMessage([MessageData]::new("Secrets, including previous versions, have expiry date for Key Vault - ["+ $this.ResourceContext.ResourceName +"]", ( $secretsWithExpiry | Select-Object Name, Version -ExpandProperty Attributes ) )); $secretsWithExpiry | ForEach-Object { $startDate = [DateTime] $_.Attributes.Created if($null -ne $_.Attributes.NotBefore) { $startDate = [DateTime] $_.Attributes.NotBefore; } if ((((([DateTime] $_.Attributes.Expires) - $startDate).TotalDays)/($this.ControlSettings.KeyVault.SecretRotationDuration_Days)) -gt 1) { $longDurationActiveSecrets += $_ } } if (($longDurationActiveSecrets| Measure-Object ).Count -gt 0) { $IsSecretCompliant = $False $controlResult.AddMessage([MessageData]::new("Following Secrets, including previous versions, are active for more than $($this.ControlSettings.KeyVault.SecretRotationDuration_Days) Days. Please delete/renew the secrets in order to comply.", ( $longDurationActiveSecrets | Select-Object Name, Version -ExpandProperty Attributes ) )); } } } else { $controlResult.AddMessage( [MessageData]::new("No Secrets found in - ["+ $this.ResourceContext.ResourceName +"]")); } } catch { $IsSecretCompliant = $False $IsAccessDenied = $True if ($_.Exception.GetType().FullName -eq "Microsoft.Azure.KeyVault.Models.KeyVaultErrorException") { $controlResult.AddMessage([MessageData]::new("Access denied: Read access is required on Key Vault Secrets.")); } else { throw $_ } } #Got exception becuase of acess denied, Keeping status Verify. if(-not $IsAccessDenied) { if($IsKeysCompliant -and $IsSecretCompliant) { $controlResult.VerificationResult = [VerificationResult]::Passed } else { $controlResult.VerificationResult = [VerificationResult]::Failed } } return $controlResult; } hidden [PSObject] GetAzureRmKeyVaultApplications () { $applicationList = @(); $this.ResourceObject.AccessPolicies | ForEach-Object { $svcPrincipal= Get-AzureRmADServicePrincipal -ObjectId $_.ObjectId if($svcPrincipal){ $application = Get-AzureRmADApplication -ApplicationId $svcPrincipal.ApplicationId if($application){ $applicationList += $application } } } return $applicationList; } }
PowerShellCorpus/PowerShellGallery/AzSDKPreview/2.2.0/Framework/Core/SVT/Services/SQLDatabase.ps1
SQLDatabase.ps1
using namespace Microsoft.Azure.Commands.Sql.Auditing.Model using namespace Microsoft.Azure.Commands.Sql.ServerUpgrade.Model using namespace Microsoft.Azure.Commands.Sql.TransparentDataEncryption.Model using namespace Microsoft.Azure.Commands.Sql.ThreatDetection.Model Set-StrictMode -Version Latest class SQLDatabase: SVTBase { hidden [PSObject] $ResourceObject; SQLDatabase([string] $subscriptionId, [string] $resourceGroupName, [string] $resourceName): Base($subscriptionId, $resourceGroupName, $resourceName) { $this.GetResourceObject(); } SQLDatabase([string] $subscriptionId, [SVTResource] $svtResource): Base($subscriptionId, $svtResource) { $this.GetResourceObject(); } hidden [PSObject] GetResourceObject() { if (-not $this.ResourceObject) { $this.ResourceObject = Get-AzureRmResource -ResourceName $this.ResourceContext.ResourceName -ResourceGroupName $this.ResourceContext.ResourceGroupName if(-not $this.ResourceObject) { throw ("Resource '{0}' not found under Resource Group '{1}'" -f ($this.ResourceContext.ResourceName), ($this.ResourceContext.ResourceGroupName)) } } return $this.ResourceObject; } hidden [ControlResult] CheckSqlServerVersionUpgrade([ControlResult] $controlResult) { $upgradeStatus = Get-AzureRmSqlServerUpgrade -ResourceGroupName $this.ResourceContext.ResourceGroupName -ServerName $this.ResourceContext.ResourceName -ErrorAction Stop $controlResult.AddMessage([MessageData]::new("Current status of SQL Database server upgrade -", $upgradeStatus)); if ($upgradeStatus.Status -eq [ServerUpgradeStatus]::Completed) { $controlResult.VerificationResult = [VerificationResult]::Passed } else { $controlResult.VerificationResult = [VerificationResult]::Failed } return $controlResult; } hidden [ControlResult] CheckSqlServerAuditing([ControlResult] $controlResult) { #Facing issue while refrencing AuditEventType class. #--------------Enforced Events------------------------------------------------- $enforcedEvents = ([AuditEventType]::Login_Failure, ` [AuditEventType]::Login_Success, ` [AuditEventType]::ParameterizedSQL_Failure, ` [AuditEventType]::PlainSQL_Failure,` [AuditEventType]::StoredProcedure_Failure,` [AuditEventType]::TransactionManagement_Failure` ) #--------------------------------------------------------------------------- $controlResult.AddMessage([MessageData]::new("Following event types must be enabled under SQL Server Auditing:", ($enforcedEvents | Select-Object -ExcludeProperty * ))); $serverAudit = Get-AzureRmSqlServerAuditingPolicy -ResourceGroupName $this.ResourceContext.ResourceGroupName -ServerName $this.ResourceContext.ResourceName -ErrorAction Stop $controlResult.AddMessage([MessageData]::new("Current audit status for server ["+ $this.ResourceContext.ResourceName +"]", $serverAudit)) $excudedTypesCount = ((($enforcedEvents) | Select-Object @{ Name = "Status"; Expression = { $serverAudit.EventType.Contains($_) } }).Status | Where-Object { $_ -eq $false } | Measure-Object ).Count if($excudedTypesCount -gt 0) { $controlResult.AddMessage([MessageData]::new("All the required audit event types are not enabled for SQL Server - ["+ $this.ResourceContext.ResourceName +"]")); } $isCompliant = ((($serverAudit.AuditState -eq [AuditStateType]::Enabled)) ` -and ($excudedTypesCount -eq 0) -and ($serverAudit.RetentionInDays -eq $this.ControlSettings.SqlServer.AuditRetentionPeriod_Days)) if ($isCompliant){ $controlResult.VerificationResult = [VerificationResult]::Passed } else{ $controlResult.VerificationResult = [VerificationResult]::Failed } return $controlResult; } hidden [ControlResult[]] CheckSqlDatabaseAuditing([ControlResult] $controlResult) { [ControlResult[]] $resultControlResultList = @() #--------------Enforced Events-------------------------------------------------- $enforcedEvents = ([AuditEventType]::Login_Failure, ` [AuditEventType]::Login_Success, ` [AuditEventType]::ParameterizedSQL_Failure, ` [AuditEventType]::PlainSQL_Failure,` [AuditEventType]::StoredProcedure_Failure,` [AuditEventType]::TransactionManagement_Failure) #------------------------------------------------------------------------------- $sqlDataBaseDtls = Get-AzureRmSqlDatabase -ResourceGroupName $this.ResourceContext.ResourceGroupName -ServerName $this.ResourceContext.ResourceName -ErrorAction Stop | Where-Object { $_.DatabaseName -ne "master" } if(($sqlDataBaseDtls | Measure-Object ).Count -eq 0) { $controlResult.AddMessage([MessageData]::new("No database found on SQL Server - ["+ $this.ResourceContext.ResourceName +"]")); #Passing the status as there is no database found on the SQL Server $controlResult.VerificationResult = [VerificationResult]::Passed; $resultControlResultList += $controlResult } else { $sqlDataBaseDtls | ForEach-Object { $dbName = $_.DatabaseName; [ControlResult] $childControlResult = $this.CreateControlResult($dbName); $childControlResult.AddMessage([MessageData]::new("Following event types must be enabled under SQL Server Database Auditing - ["+ $dbName +"]", ($enforcedEvents | Select-Object -ExcludeProperty *))); $dbAuditPolicy = Get-AzureRmSqlDatabaseAuditingPolicy ` -ResourceGroupName $this.ResourceContext.ResourceGroupName ` -ServerName $this.ResourceContext.ResourceName ` -DatabaseName $dbName ` -ErrorAction Stop $childControlResult.AddMessage([MessageData]::new("Current audit status for database '$dbName'", ($dbAuditPolicy))); if(Get-Member -InputObject $dbAuditPolicy -Name 'UseServerDefault' -MemberType Properties) { $isCompliant = $dbAuditPolicy.UseServerDefault -eq [UseServerDefaultOptions]::Enabled } else { $isCompliant = $false } if(-not $isCompliant) { $excudedTypesCount = ((($enforcedEvents) | Select-Object @{ Name = "Status"; Expression = { $dbAuditPolicy.EventType.Contains($_) } }).Status | Where-Object { $_ -eq $false } | Measure-Object ).Count if($excudedTypesCount -gt 0) { $childControlResult.AddMessage([MessageData]::new("All the required audit event types are not enabled for SQL Database '$dbName'")); } if(($dbAuditPolicy.AuditState -eq [AuditStateType]::Enabled) ` -and ($excudedTypesCount -eq 0) -and ($dbAuditPolicy.RetentionInDays -eq $this.ControlSettings.SqlServer.AuditRetentionPeriod_Days)) { $isCompliant = $True } else{ $isCompliant = $false } } #$propClone = $telemetryProperties.Clone() # #$propClone.Add($Global:TeleKeys::NestedResourceName, $dbName) if($isCompliant){ $childControlResult.VerificationResult = [VerificationResult]::Passed; } else { $childControlResult.AddMessage([VerificationResult]::Failed, "All required Audit settings are not configured correctly for SQL Database '$dbName'"); } $resultControlResultList += $childControlResult } } return $resultControlResultList; } hidden [ControlResult[]] CheckSqlDatabaseTDE([ControlResult] $controlResult) { [ControlResult[]] $resultControlResultList = @() $sqlDataBaseDtls = Get-AzureRmSqlDatabase -ResourceGroupName $this.ResourceContext.ResourceGroupName -ServerName $this.ResourceContext.ResourceName -ErrorAction Stop | Where-Object { $_.DatabaseName -ne "master" } if(($sqlDataBaseDtls | Measure-Object ).Count -eq 0) { $controlResult.AddMessage([MessageData]::new("No database found on SQL Server - ["+ $this.ResourceContext.ResourceName +"]")); #Since there is no database found we are passing this control $controlResult.VerificationResult = [VerificationResult]::Passed; $resultControlResultList += $controlResult } else { $sqlDataBaseDtls | ForEach-Object { $dbName = $_.DatabaseName; [ControlResult] $childControlResult = [ControlResult]@{ ChildResourceName = $dbName; }; $tdeStatus = Get-AzureRmSqlDatabaseTransparentDataEncryption ` -ResourceGroupName $this.ResourceContext.ResourceGroupName ` -ServerName $this.ResourceContext.ResourceName ` -DatabaseName $dbName ` -ErrorAction Stop $childControlResult.AddMessage([MessageData]::new("Current TDE Status for - ["+ $dbName +"]", ($tdeStatus ))); if($tdeStatus.State -eq [TransparentDataEncryptionStateType]::Enabled){ $childControlResult.VerificationResult = [VerificationResult]::Passed; } else{ $childControlResult.VerificationResult = [VerificationResult]::Failed; } $resultControlResultList += $childControlResult } #End of ForEach-Object } return $resultControlResultList; } hidden [ControlResult] CheckSqlServerADAdmin([ControlResult] $controlResult) { $adAdmin = Get-AzureRmSqlServerActiveDirectoryAdministrator -ResourceGroup $this.ResourceContext.ResourceGroupName -Server $this.ResourceContext.ResourceName -ErrorAction Stop $controlResult.AddMessage([MessageData]::new("Current status of Active Directory Admin for ["+ $this.ResourceContext.ResourceName +"] is")); if(($adAdmin | Measure-Object).Count -gt 0){ $controlResult.VerificationResult = [VerificationResult]::Passed $controlResult.AddMessage([MessageData]::new("Active Directory admins are assigned on SQL Server - ["+ $this.ResourceContext.ResourceName +"]", ($adAdmin))); } else{ $controlResult.VerificationResult = [VerificationResult]::Failed $controlResult.AddMessage([MessageData]::new("No Active Directory admin is assigned on SQL Server - ["+ $this.ResourceContext.ResourceName +"]")); } return $controlResult } hidden [ControlResult] CheckSqlServerThreatDetection([ControlResult] $controlResult) { $isCompliant = $false $serverThreat = Get-AzureRmSqlServerThreatDetectionPolicy ` -ResourceGroupName $this.ResourceContext.ResourceGroupName ` -ServerName $this.ResourceContext.ResourceName ` -ErrorAction Stop $controlResult.AddMessage([MessageData]::new("Current threat detection status for server ["+ $this.ResourceContext.ResourceName +"] is", ($serverThreat))); $excludedTypeCount = ($serverThreat.ExcludedDetectionTypes | Measure-Object ).Count if($excludedTypeCount -gt 0){ $controlResult.AddMessage([MessageData]::new("All the required audit event types are not enabled for SQL Server - ["+ $this.ResourceContext.ResourceName +"]")); } $isCompliant = (($serverThreat.ThreatDetectionState -eq [ThreatDetectionStateType]::Enabled) ` -and ($excludedTypeCount -eq 0) ` -and (($serverThreat.EmailAdmins -eq $True) -or ($null -ne $serverThreat.NotificationRecipientsEmails))) if ($isCompliant) { $controlResult.VerificationResult = [VerificationResult]::Passed } else{ $controlResult.VerificationResult = [VerificationResult]::Failed } return $controlResult } hidden [ControlResult[]] CheckSqlDatabaseThreatDetection([ControlResult] $controlResult) { [ControlResult[]] $resultControlResultList = @() $sqlDataBaseDtls = Get-AzureRmSqlDatabase -ResourceGroupName $this.ResourceContext.ResourceGroupName -ServerName $this.ResourceContext.ResourceName -ErrorAction Stop | Where-Object { $_.DatabaseName -ne "master" } if(($sqlDataBaseDtls | Measure-Object ).Count -eq 0) { $controlResult.AddMessage([MessageData]::new("No database found on SQL Server - ["+ $this.ResourceContext.ResourceName +"]")); #Since there is no database found we are passing this control $controlResult.VerificationResult = [VerificationResult]::Passed; $resultControlResultList += $controlResult } else { $sqlDataBaseDtls | ForEach-Object { $dbName = $_.DatabaseName; [ControlResult] $childControlResult = [ControlResult]@{ ChildResourceName = $dbName; }; #$telemetryTimerPerDb = [System.Diagnostics.Stopwatch]::StartNew() $dbThreat = Get-AzureRmSqlDatabaseThreatDetectionPolicy ` -ResourceGroupName $this.ResourceContext.ResourceGroupName ` -ServerName $this.ResourceContext.ResourceName ` -DatabaseName $dbName ` -ErrorAction Stop $childControlResult.AddMessage([MessageData]::new("Current threat detection state for database - ["+ $dbName +"]", ($dbThreat))); $dbAuditPolicy = Get-AzureRmSqlDatabaseAuditingPolicy ` -ResourceGroupName $this.ResourceContext.ResourceGroupName ` -ServerName $this.ResourceContext.ResourceName ` -DatabaseName $dbName ` -ErrorAction Stop $childControlResult.AddMessage([MessageData]::new("Current audit status for database - ["+ $dbName +"]", ($dbAuditPolicy ))); if(Get-Member -InputObject $dbAuditPolicy -Name 'UseServerDefault' -MemberType Properties) { $isCompliant = $dbAuditPolicy.UseServerDefault -eq [UseServerDefaultOptions]::Enabled } else { $isCompliant = $false } if(-not $isCompliant) { if(($dbThreat.ThreatDetectionState -eq [ThreatDetectionStateType]::Enabled) ` -and ($dbThreat.ExcludedDetectionTypes.Count -eq 0) ` -and (($dbThreat.EmailAdmins -eq $True) -or ($dbThreat.NotificationRecipientsEmails.Length -gt 0))) { $isCompliant = $True } else{ $isCompliant = $false } } if($isCompliant) { $childControlResult.VerificationResult = [VerificationResult]::Passed; } else { $childControlResult.VerificationResult = [VerificationResult]::Failed; } $resultControlResultList += $childControlResult } } return $resultControlResultList; } hidden [ControlResult] CheckSqlDatabaseFirewallEnabled([ControlResult] $controlResult) { $firewallDtls = Get-AzureRmSqlServerFirewallRule -ResourceGroupName $this.ResourceContext.ResourceGroupName -ServerName $this.ResourceContext.ResourceName if(($firewallDtls | Measure-Object ).Count -gt 0){ $controlResult.VerificationResult = [VerificationResult]::Passed } else{ $controlResult.VerificationResult = [VerificationResult]::Failed } return $controlResult } hidden [ControlResult] CheckSqlDatabaseFirewallIPAddressRange([ControlResult] $controlResult) { #As current function will check firewall ip address renages, if firewall is enabled. When it enabled, it allows any traffic from services within your Azure subscription to pass through. #Default record will be their with Start IP address as 0.0.0.0 and End Ip address as 0.0.0.0 $firewallDtls = Get-AzureRmSqlServerFirewallRule -ResourceGroupName $this.ResourceContext.ResourceGroupName -ServerName $this.ResourceContext.ResourceName if(($firewallDtls | Measure-Object ).Count -gt 0) { $controlResult.AddMessage([MessageData]::new("Current firewall settings for - ["+ $this.ResourceContext.ResourceName +"]", $firewallDtls)); $anyToAnyRule = $firewallDtls | Where-Object { $_.StartIpAddress -eq $this.ControlSettings.IPRangeStartIP -and $_.EndIpAddress -eq $this.ControlSettings.IPRangeEndIP} if (($anyToAnyRule | Measure-Object).Count -gt 0) { $controlResult.AddMessage([VerificationResult]::Failed, [MessageData]::new("Firewall rule covering all IPs (Start IP address: $($this.ControlSettings.IPRangeStartIP) To End IP Address: $($this.ControlSettings.IPRangeEndIP)) is defined.")); } else { $controlResult.VerificationResult = [VerificationResult]::Verify } $controlResult.SetStateData("Firewall IP addresses:", $firewallDtls); } else { $controlResult.AddMessage([VerificationResult]::Failed, "Control can not be validated: Firewall is not enabled"); } return $controlResult } }
PowerShellCorpus/PowerShellGallery/AzSDKPreview/2.2.0/Framework/Core/SVT/Services/VirtualNetwork.ps1
VirtualNetwork.ps1
#using namespace Microsoft.Azure.Commands.VirtualNetwork.Models Set-StrictMode -Version Latest class VirtualNetwork: SVTIaasBase { VirtualNetwork([string] $subscriptionId, [string] $resourceGroupName, [string] $resourceName): Base($subscriptionId, $resourceGroupName, $resourceName) { } VirtualNetwork([string] $subscriptionId, [SVTResource] $svtResource): Base($subscriptionId, $svtResource) { } hidden [ControlResult] CheckPublicIps([ControlResult] $controlResult) { if($null -ne $this.vNetNicsOutput) { $controlResult.AddMessage([MessageData]::new("Analyzing all the NICs configured in the VNet")); $PublicIpCount = (($this.vNetNicsOutput | Where-Object {!([System.String]::IsNullOrWhiteSpace($_.PublicIpAddress))}) | Measure-Object).count if($PublicIpCount -gt 0) { $controlResult.AddMessage([VerificationResult]::Verify, [MessageData]::new("Verify below Public IP(s) on the Vnet")); $this.vNetNicsOutput | ForEach-Object{ Set-Variable -Name nic -Scope Local -Value $_ $controlResult.AddMessage([MessageData]::new(($nic | Select-Object NICName, VMName, PrimaryStatus, NetworkSecurityGroupName, PublicIpAddress, PrivateIpAddress))); } } else { $controlResult.AddMessage([VerificationResult]::Passed, [MessageData]::new("No Public IP is configured in any NIC on the Vnet")); } } else { $controlResult.AddMessage([VerificationResult]::Passed, [MessageData]::new("No NICs found on the VNet with Public IP configured")); } return $controlResult; } hidden [ControlResult] CheckIPForwardingforNICs([ControlResult] $controlResult) { if(-not $this.vNetNicsOutput -and ($this.vNetNicsOutput | Measure-Object).count -gt 0) { [array] $vNetNicsIPFwed = $this.vNetNicsOutput | Where-Object { $_.EnableIPForwarding } if($null -ne $vNetNicsIPFwed -and ($vNetNicsIPFwed | Measure-Object).count -gt 0) { $controlResult.AddMessage([VerificationResult]::Verify, [MessageData]::new("Verify IP Forwarding is enabled for below NIC(s) in VNet")); $controlResult.AddMessage([MessageData]::new(($vNetNicsIPFwed | Select-Object NICName, EnableIPForwarding))); } else { $controlResult.AddMessage([VerificationResult]::Passed, [MessageData]::new("There are no NICs with EnableIPForwarding turned on the VNet")); } } else { $controlResult.AddMessage([VerificationResult]::Passed, [MessageData]::new("There are no NICs with EnableIPForwarding turned on the VNet")); } return $controlResult; } hidden [ControlResult] CheckNSGUseonGatewaySubnet([ControlResult] $controlResult) { $gateWaySubnet = $this.ResourceObject.Subnets | Where-Object {$_.Name -eq "GatewaySubnet"} if($null -ne $gateWaySubnet) { if($null-ne $gateWaySubnet.NetworkSecurityGroup -and -not [System.String]::IsNullOrWhiteSpace($gateWaySubnet.NetworkSecurityGroup.Id)) { $controlResult.AddMessage([VerificationResult]::Failed, [MessageData]::new("NSG is configured on the Gateway Subnet of VNet", ($gateWaySubnet | Select-Object Name, NetworkSecurityGroupText))); } else { $controlResult.AddMessage([VerificationResult]::Passed, [MessageData]::new("There are no NSG's configured on the Gateway subnet of VNet")); } } else { $controlResult.AddMessage([VerificationResult]::Passed, [MessageData]::new("No Gateway subnet found on the VNet")); } return $controlResult; } hidden [ControlResult] CheckNSGConfigured([ControlResult] $controlResult) { $hasTCPPassed = $true if($null -ne $this.ResourceObject.Subnets) { $subnetsWithoutNSG = $this.ResourceObject.Subnets | Where-Object {$null -eq $_.NetworkSecurityGroup -and $_.Name.ToLower() -ne "gatewaysubnet"} $subnetsWithNSG = $this.ResourceObject.Subnets | Where-Object {$null -ne $_.NetworkSecurityGroup -and $_.Name.ToLower() -ne "gatewaysubnet"} if($null-ne $subnetsWithoutNSG -and ($subnetsWithoutNSG | Measure-Object).count -gt 0) { $hasTCPPassed = $false $controlResult.AddMessage([VerificationResult]::Failed, [MessageData]::new("NSG is not configured for below subnet(s) of VNet", ($subnetsWithoutNSG | Select-Object Name, Id))); } if($null-ne $subnetsWithNSG -and ($subnetsWithNSG | Measure-Object).Count -gt 0) { #$checkSubnets = @() $InvalidRulesList = @() $subnetsWithNSG | ForEach-Object{ $nsgid = $_.NetworkSecurityGroup.Id $nsglist = Get-AzureRmResource -ResourceId $nsgid $nsglist | ForEach-Object{ $rules = $_.Properties.SecurityRules $rules | ForEach-Object{ $ruleproperties = $_.Properties if((($ruleproperties.Direction -eq "outbound") -or ($ruleproperties.Direction -eq "inbound")) -and $ruleproperties.SourceAddressPrefix -eq '*' -and $ruleproperties.DestinationAddressPrefix -eq '*' -and $ruleproperties.Access -eq "allow") { $InvalidRulesList += $_ } } } $currentsubnet=$_ if(($InvalidRulesList | Measure-Object).Count -gt 0) { $hasTCPPassed = $false $controlResult.AddMessage([VerificationResult]::Failed, [MessageData]::new("Potentially dangerous any to any outbound security rule(s) found in subnet - ["+ $_.Name +"]", ($InvalidRulesList | Format-list name, properties))); } } } } else { $controlResult.AddMessage([VerificationResult]::Passed, [MessageData]::new("No subnets found on VNet")); } if($hasTCPPassed -eq $true) { $controlResult.VerificationResult = [VerificationResult]::Passed; } return $controlResult; } hidden [ControlResult] CheckGatewayUsed([ControlResult] $controlResult) { $vNetGateways = @() $VNetSubnets = $this.ResourceObject.Subnets if($null -ne $VNetSubnets) { $VNetSubnets | ForEach-Object{ Set-Variable -Name currentsubnet -Scope Local -Value $_ if($null -ne $currentsubnet.IpConfigurations ) { $currentsubnet.IpConfigurations | ForEach-Object{ Set-Variable -Name currentipconfig -Scope Local -Value $_ if($currentipconfig.Id.ToLower().Contains("microsoft.network/virtualnetworkgateways")) { $currentipconfig = $currentipconfig.Id.ToLower() $gatewayresourceid = $currentipconfig.Substring(0,$currentipconfig.LastIndexOf("ipconfigurations")-1) $gateway = Get-AzureRmResource -ResourceId $gatewayresourceid $vNetGateway = New-Object System.Object $vNetGateway | Add-Member -type NoteProperty -name ResourceName -Value $gateway.ResourceName $vNetGateway | Add-Member -type NoteProperty -name ResourceGroupName -Value $gateway.ResourceGroupName $vNetGateway | Add-Member -type NoteProperty -name GatewayType -Value $gateway.Properties.gatewayType $vNetGateway | Add-Member -type NoteProperty -name VPNType -Value $gateway.Properties.vpnType $vNetGateways += $vNetGateway } } } } } if($null -ne $vNetGateways -and ($vNetGateways | Measure-Object).Count -gt 0) { $controlResult.AddMessage([VerificationResult]::Verify, [MessageData]::new("Verify below virtual network gateways found on VNet", $vNetGateways)); } else { $controlResult.AddMessage([VerificationResult]::Passed, [MessageData]::new("No gateways found in VNet")); } return $controlResult; } hidden [ControlResult] CheckVnetPeering([ControlResult] $controlResult) { $vnetPeerings = Get-AzureRmVirtualNetworkPeering -VirtualNetworkName $this.ResourceContext.ResourceName -ResourceGroupName $this.ResourceContext.ResourceGroupName if($null -ne $vnetPeerings -and ($vnetPeerings|Measure-Object).count -gt 0) { $controlResult.AddMessage([VerificationResult]::Verify, [MessageData]::new("Verify below peering found on VNet", $vnetPeerings)); } else { $controlResult.AddMessage([VerificationResult]::Passed, [MessageData]::new("No VNet peerings found on VNet", $vnetPeerings)); } return $controlResult; } }
PowerShellCorpus/PowerShellGallery/AzSDKPreview/2.2.0/Framework/Core/SVT/Services/TrafficManager.ps1
TrafficManager.ps1
Set-StrictMode -Version Latest class TrafficManager : SVTBase { hidden [PSObject] $ResourceObject; TrafficManager([string] $subscriptionId, [string] $resourceGroupName, [string] $resourceName): Base($subscriptionId, $resourceGroupName, $resourceName) { } TrafficManager([string] $subscriptionId, [SVTResource] $svtResource): Base($subscriptionId, $svtResource) { } hidden [ControlResult] CheckTrafficManagerEndpointMonitorProtocol([ControlResult] $controlResult) { $trafficManagerProfile = Get-AzureRmTrafficManagerProfile -Name $this.ResourceContext.ResourceName ` -ResourceGroupName $this.ResourceContext.ResourceGroupName ` -ErrorAction Stop #Checking if endpoints are there or not in the profile if(($trafficManagerProfile.Endpoints | Measure-Object).Count -ne 0) { $EnabledEndpointList = $trafficManagerProfile.Endpoints | Where-Object { $_.EndpointStatus -eq 'Enabled' } #check if all endpoints are not disabled if(($EnabledEndpointList | Measure-Object).Count -eq 0) { $controlResult.AddMessage([VerificationResult]::Passed, [MessageData]::new("All endpoints are disabled in the Traffic Manager profile ["+ $this.ResourceContext.ResourceName +"].")); } else { if($trafficManagerProfile.MonitorProtocol -eq 'HTTPS') { $controlResult.AddMessage([VerificationResult]::Passed, [MessageData]::new("The Traffic Manager profile ["+ $this.ResourceContext.ResourceName +"] is using HTTPS protocol for endpoint monitoring.")); } else { $controlResult.AddMessage([VerificationResult]::Failed, [MessageData]::new("The Traffic Manager profile ["+ $this.ResourceContext.ResourceName +"] is using HTTP protocol for endpoint monitoring.")); } } } else { $controlResult.AddMessage([VerificationResult]::Passed, [MessageData]::new("No endpoints found in the Traffic Manager profile ["+ $this.ResourceContext.ResourceName +"].")); } return $controlResult; } }
PowerShellCorpus/PowerShellGallery/AzSDKPreview/2.2.0/Framework/Core/SVT/Services/AppService.ps1
AppService.ps1
#using namespace Microsoft.Azure.Commands.AppService.Models Set-StrictMode -Version Latest class AppService: SVTBase { hidden [PSObject] $ResourceObject; hidden [PSObject] $WebAppDetails; hidden [PSObject] $AuthenticationSettings; hidden [bool] $IsReaderRole; AppService([string] $subscriptionId, [string] $resourceGroupName, [string] $resourceName): Base($subscriptionId, $resourceGroupName, $resourceName) { $this.GetResourceObject(); } AppService([string] $subscriptionId, [SVTResource] $svtResource): Base($subscriptionId, $svtResource) { $this.GetResourceObject(); } hidden [PSObject] GetResourceObject() { if (-not $this.ResourceObject) { # Get App Service details $this.ResourceObject = Get-AzureRmResource -ResourceName $this.ResourceContext.ResourceName ` -ResourceType $this.ResourceContext.ResourceType ` -ResourceGroupName $this.ResourceContext.ResourceGroupName if(-not $this.ResourceObject) { throw ("Resource '$($this.ResourceContext.ResourceName)' not found under Resource Group '$($this.ResourceContext.ResourceGroupName)'") } # Get web sites details $this.WebAppDetails = Get-AzureRmWebApp -Name $this.ResourceContext.ResourceName ` -ResourceGroupName $this.ResourceContext.ResourceGroupName try { $this.AuthenticationSettings = Invoke-AzureRmResourceAction -ResourceType "Microsoft.Web/sites/config/authsettings" ` -ResourceGroupName $this.ResourceContext.ResourceGroupName ` -ResourceName $this.ResourceContext.ResourceName ` -Action list ` -ApiVersion $this.ControlSettings.AppService.AADAuthAPIVersion ` -Force ` -ErrorAction Stop $this.IsReaderRole = $false; } catch { if(($_.Exception | Get-Member -Name "HttpStatus" ) -and $_.Exception.HttpStatus -eq "Forbidden") { $this.IsReaderRole = $true; } } } return $this.ResourceObject; } hidden [ControlResult] CheckAppServiceCustomDomainWithSSLConfig([ControlResult] $controlResult) { # Get custom domain URLs $customHostNames = $this.ResourceObject.Properties.HostNames | Where-Object { -not $_.EndsWith(".azurewebsites.net") }; # Combine custom domain name and SSL configuration TCP if(($customHostNames | Measure-Object).Count -gt 0) { $controlResult.AddMessage([MessageData]::new("Custom domains are configured for resource " + $this.ResourceContext.ResourceName), $customHostNames); $SSLStateNotEnabled = $this.ResourceObject.Properties.hostNameSslStates | Where-Object {$_.sslState -eq 'Disabled'} | Select-Object -Property Name if($null -eq $SSLStateNotEnabled) { $controlResult.AddMessage([VerificationResult]::Passed, [MessageData]::new("SSL configuration for resource " + $this.ResourceContext.ResourceName + " is enabled for all host names", $this.ResourceObject.Properties.hostNameSslStates)); } else { $controlResult.AddMessage([VerificationResult]::Failed, [MessageData]::new("SSL configuration for resource " + $this.ResourceContext.ResourceName + " is not enabled for host names", $this.ResourceObject.Properties.hostNameSslStates)); } } else { $controlResult.AddMessage([VerificationResult]::Failed, [MessageData]::new("Custom domains are not configured for resource " + $this.ResourceContext.ResourceName, $this.ResourceObject.Properties.HostNames)); } return $controlResult; } hidden [ControlResult] CheckAppServiceADAuthentication([ControlResult] $controlResult) { try { if($this.IsReaderRole) { $controlResult.AddMessage([VerificationResult]::Manual, [MessageData]::new("Control can not be validated due to insufficient access permission on resource")); } else { $aadSettings = New-Object PSObject Add-Member -InputObject $aadSettings -MemberType NoteProperty -Name "Enabled" -Value $this.AuthenticationSettings.Properties.enabled Add-Member -InputObject $aadSettings -MemberType NoteProperty -Name "ClientId" -Value $this.AuthenticationSettings.Properties.ClientId $AADEnabled = $false if($this.AuthenticationSettings.Properties.enabled -eq $True) { if($null -ne $this.AuthenticationSettings.Properties.ClientId) { $AADEnabled = $True; } } if($AADEnabled) { $controlResult.AddMessage([VerificationResult]::Passed, [MessageData]::new("AAD Authentication for resource " + $this.ResourceContext.ResourceName + " is enabled", $aadSettings)); } else { $controlResult.AddMessage([VerificationResult]::Verify, [MessageData]::new("Verify that AAD Authentication for resource " + $this.ResourceContext.ResourceName + " is enabled", $aadSettings)); } } } catch { throw; } return $controlResult; } hidden [ControlResult] CheckAppServiceRemoteDebuggingConfiguration([ControlResult] $controlResult) { if($this.WebAppDetails.SiteConfig.RemoteDebuggingEnabled) { $controlResult.AddMessage([VerificationResult]::Failed, [MessageData]::new("Remote debugging for resource " + $this.ResourceContext.ResourceName + " is turned on", ($this.WebAppDetails.SiteConfig | Select-Object RemoteDebuggingEnabled))); } else { $controlResult.AddMessage([VerificationResult]::Passed, [MessageData]::new("Remote debugging for resource " + $this.ResourceContext.ResourceName + " is turned off", ($this.WebAppDetails.SiteConfig | Select-Object RemoteDebuggingEnabled))); } return $controlResult; } hidden [ControlResult] CheckAppServiceWebSocketsConfiguration([ControlResult] $controlResult) { if($this.WebAppDetails.SiteConfig.WebSocketsEnabled) { $controlResult.AddMessage([VerificationResult]::Failed, [MessageData]::new("Web sockets for resource " + $this.ResourceContext.ResourceName + " is enabled", ($this.WebAppDetails.SiteConfig | Select-Object WebSocketsEnabled))); } else { $controlResult.AddMessage([VerificationResult]::Passed, [MessageData]::new("Web sockets for resource " + $this.ResourceContext.ResourceName + " is not enabled", ($this.WebAppDetails.SiteConfig | Select-Object WebSocketsEnabled))); } return $controlResult; } hidden [ControlResult] CheckAppServiceAlwaysOnConfiguration([ControlResult] $controlResult) { if($this.WebAppDetails.SiteConfig.AlwaysOn) { $controlResult.AddMessage([VerificationResult]::Passed, [MessageData]::new("Always On feature for resource " + $this.ResourceContext.ResourceName + " is enabled", ($this.WebAppDetails.SiteConfig | Select-Object AlwaysOn))); } else { $controlResult.AddMessage([VerificationResult]::Failed, [MessageData]::new("Always On feature for resource " + $this.ResourceContext.ResourceName + " is not enabled", ($this.WebAppDetails.SiteConfig | Select-Object AlwaysOn))); } return $controlResult; } hidden [ControlResult] CheckAppService64BitPlatformConfiguration([ControlResult] $controlResult) { if($this.WebAppDetails.SiteConfig.Use32BitWorkerProcess) { $controlResult.AddMessage([VerificationResult]::Failed, [MessageData]::new("32-bit platform is used for resource " + $this.ResourceContext.ResourceName, ($this.WebAppDetails.SiteConfig | Select-Object Use32BitWorkerProcess))); } else { $controlResult.AddMessage([VerificationResult]::Passed, [MessageData]::new("64-bit platform is used for resource " + $this.ResourceContext.ResourceName, ($this.WebAppDetails.SiteConfig | Select-Object Use32BitWorkerProcess))); } return $controlResult; } hidden [ControlResult] CheckAppServiceDotNetFrameworkVersion([ControlResult] $controlResult) { $dotNetFrameworkVersion = $this.WebAppDetails.SiteConfig.NetFrameworkVersion $splitVersionNumber = $this.ControlSettings.AppService.LatestDotNetFrameworkVersionNumber.split(".") # Compare App Service Net Framework version with latest Net Framework version from configuration $isCompliant = $dotNetFrameworkVersion.CompareTo($splitVersionNumber[0] + "." + $splitVersionNumber[1]) -eq 0 if($isCompliant) { $controlResult.AddMessage([VerificationResult]::Passed, [MessageData]::new("Latest .Net Framework version is used for resource " + $this.ResourceContext.ResourceName, ($this.WebAppDetails.SiteConfig | Select-Object NetFrameworkVersion))); } else { $controlResult.AddMessage([VerificationResult]::Failed, [MessageData]::new("Latest .Net Framework version is not used for resource " + $this.ResourceContext.ResourceName, ($this.WebAppDetails.SiteConfig | Select-Object NetFrameworkVersion))); } return $controlResult; } hidden [ControlResult] CheckAppServiceInstanceCount([ControlResult] $controlResult) { # Get number of instances $sku = (Get-AzureRmResource -ResourceId $this.ResourceObject.Properties.ServerFarmId).Sku if($sku.Capacity -ge $this.ControlSettings.AppService.Minimum_Instance_Count) { $controlResult.AddMessage([VerificationResult]::Passed, [MessageData]::new("SKU for resource " + $this.ResourceContext.ResourceName + " is :", $sku)); } else { $controlResult.AddMessage([VerificationResult]::Failed, [MessageData]::new("SKU for resource " + $this.ResourceContext.ResourceName + " is :", $sku)); } return $controlResult; } hidden [ControlResult] CheckAppServiceBackupConfiguration([ControlResult] $controlResult) { try { if($this.IsReaderRole) { $controlResult.AddMessage([VerificationResult]::Manual, [MessageData]::new("Control can not be validated due to insufficient access permission on resource")); } else { $backupConfiguration = Get-AzureRmWebAppBackupConfiguration ` -ResourceGroupName $this.ResourceContext.ResourceGroupName ` -Name $this.ResourceContext.ResourceName ` -ErrorAction Stop $isCompliant = $False If ($null -ne $backupConfiguration) { # Backup must be enabled and retention period days must be more than 365 and backup start date is less than current time (backup has been already started) # and at least one backup is available If($backupConfiguration.Enabled -eq $True -and ` ($backupConfiguration.RetentionPeriodInDays -eq $this.ControlSettings.AppService.Backup_RetentionPeriod_Forever -or $backupConfiguration.RetentionPeriodInDays -ge $this.ControlSettings.AppService.Backup_RetentionPeriod_Min) -and` $backupConfiguration.StartTime -le $(Get-Date) -and $backupConfiguration.KeepAtLeastOneBackup -eq $True) { $isCompliant = $True } } if(-not $isCompliant) { $controlResult.VerificationResult = [VerificationResult]::Failed; if($null -ne $backupConfiguration) { $controlResult.AddMessage([MessageData]::new("Configured backup for resource " + $this.ResourceContext.ResourceName + " is not as per the security guidelines. Please make sure that the configured backup is inline with below settings:-")); $controlResult.AddMessage([MessageData]::new("Enabled=True, StorageAccountEncryption=Enabled, RetentionPeriodInDays=0 or RetentionPeriodInDays>=365, BackupStartTime<=CurrentTime, KeepAtLeastOneBackup=True", $backupConfiguration)); } else { $controlResult.AddMessage([MessageData]::new("Backup for resource " + $this.ResourceContext.ResourceName + " is not configured", $backupConfiguration)); } } else { $controlResult.AddMessage([VerificationResult]::Passed, [MessageData]::new("Backup for resource " + $this.ResourceContext.ResourceName + " is enabled", $backupConfiguration)); } } } catch { if(($_.Exception).Response.StatusCode.value__ -eq 404) { $controlResult.AddMessage([VerificationResult]::Failed, [MessageData]::new("Backup for resource " + $this.ResourceContext.ResourceName + " is not configured")); } else { throw $_ } } return $controlResult; } hidden [ControlResult] CheckAppServiceDiagnosticLogsConfiguration([ControlResult] $controlResult) { $diagnosticLogsConfig = New-Object PSObject Add-Member -InputObject $diagnosticLogsConfig -MemberType NoteProperty -Name "HttpLoggingEnabled" -Value $this.WebAppDetails.SiteConfig.HttpLoggingEnabled Add-Member -InputObject $diagnosticLogsConfig -MemberType NoteProperty -Name "DetailedErrorLoggingEnabled" -Value $this.WebAppDetails.SiteConfig.DetailedErrorLoggingEnabled Add-Member -InputObject $diagnosticLogsConfig -MemberType NoteProperty -Name "RequestTracingEnabled" -Value $this.WebAppDetails.SiteConfig.RequestTracingEnabled $isCompliant = $diagnosticLogsConfig.HttpLoggingEnabled -eq $true -and ` $diagnosticLogsConfig.DetailedErrorLoggingEnabled -eq $true -and ` $diagnosticLogsConfig.RequestTracingEnabled -eq $true if($isCompliant) { $controlResult.AddMessage([VerificationResult]::Passed, [MessageData]::new("Diagnostics logs for resource " + $this.ResourceContext.ResourceName + " are enabled", $diagnosticLogsConfig)); } else { $controlResult.AddMessage([VerificationResult]::Failed, [MessageData]::new("All configurations of diagnostics logs for resource " + $this.ResourceContext.ResourceName + " are not enabled", $diagnosticLogsConfig)); } return $controlResult; } hidden [ControlResult] CheckAppServiceHttpCertificateSSL([ControlResult] $controlResult) { try { $defaultHostName = $this.ResourceObject.Properties.defaultHostName $request = [System.Net.WebRequest]::Create('http://'+$defaultHostName) $response = $request.GetResponse() $responceURL = $response.ResponseUri.OriginalString $response.Close() $scheme = ([System.Uri]$responceURL).Scheme if($scheme -eq "https") { $controlResult.AddMessage([VerificationResult]::Passed, [MessageData]::new("HTTP requests are not allowed for resource " + $this.ResourceContext.ResourceName, $responceURL)); } else { $controlResult.AddMessage([VerificationResult]::Failed, [MessageData]::new("HTTP requests are allowed for resource " + $this.ResourceContext.ResourceName, $responceURL)); } } catch [System.Management.Automation.MethodInvocationException] { $controlResult.AddMessage([VerificationResult]::Verify, [MessageData]::new("Default Host URL is not reachable or self-signed certificate is used")); } return $controlResult; } hidden [ControlResult] CheckAppServiceLoadCertAppSettings([ControlResult] $controlResult) { if($this.IsReaderRole) { $controlResult.AddMessage([VerificationResult]::Manual, [MessageData]::new("Control can not be validated due to insufficient access permission on resource")); } else { $appSettings = $this.WebAppDetails.SiteConfig.AppSettings $appSettingParameterList = $null if(($appSettings| Measure-Object).Count -gt 0) { $appSettingParameterList = $appSettings | Where-Object { $_.Name -eq $this.ControlSettings.AppService.LoadCertAppSettings -and $_.Value -eq "*"} } if($null -ne $appSettingParameterList) { $controlResult.AddMessage([VerificationResult]::Failed, [MessageData]::new("'WEBSITE_LOAD_CERTIFICATES' parameter defined equal to '*' is found in App Settings for resource " + $this.ResourceContext.ResourceName)); } else { $controlResult.AddMessage([VerificationResult]::Passed, [MessageData]::new("'WEBSITE_LOAD_CERTIFICATES' parameter defined equal to '*' is not found in App Settings for resource " + $this.ResourceContext.ResourceName)); } } return $controlResult; } }
PowerShellCorpus/PowerShellGallery/AzSDKPreview/2.2.0/Framework/Core/SVT/Services/ERvNet.ps1
ERvNet.ps1
#using namespace Microsoft.Azure.Commands.ExpressRouteVirtualNetwork.Models Set-StrictMode -Version Latest class ERvNet : SVTIaasBase { ERvNet([string] $subscriptionId, [string] $resourceGroupName, [string] $resourceName): Base($subscriptionId, $resourceGroupName, $resourceName) { } ERvNet([string] $subscriptionId, [SVTResource] $svtResource): Base($subscriptionId, $svtResource) { } hidden [ControlResult] CheckPublicIps([ControlResult] $controlResult) { if($null -ne $this.vNetNicsOutput ) { $controlResult.AddMessage([MessageData]::new("Analyzing all the NICs configured in the VNet")); $publicIpCount = (($this.vNetNicsOutput | Where-Object {!([System.String]::IsNullOrWhiteSpace($_.PublicIpAddress))}) | Measure-Object).count if($publicIpCount -gt 0) { $controlResult.AddMessage([VerificationResult]::Failed, [MessageData]::new("Below Public IP(s) on the ERVnet")); $this.vNetNicsOutput | ForEach-Object{ Set-Variable -Name nic -Scope Local -Value $_ $controlResult.AddMessage([MessageData]::new(($nic | Select-Object NICName, VMName, PrimaryStatus, NetworkSecurityGroupName, PublicIpAddress, PrivateIpAddress))); } } else { $controlResult.AddMessage([VerificationResult]::Passed, [MessageData]::new("No Public IP is configured in any NIC on the ERVnet")); } } else { $controlResult.AddMessage([VerificationResult]::Passed, [MessageData]::new("No NICs found on the ERVNet")); } return $controlResult; } hidden [ControlResult] CheckIPForwardingforNICs([ControlResult] $controlResult) { if($null -ne $this.vNetNicsOutput) { [array] $vNetNicsIPFwed = $this.vNetNicsOutput | Where-Object { $_.EnableIPForwarding } if($null -ne $vNetNicsIPFwed -and ($vNetNicsIPFwed | Measure-Object).count -gt 0) { $controlResult.AddMessage([VerificationResult]::Failed, [MessageData]::new("IP Forwarding is enabled for below NIC(s) in ERVNet")); $controlResult.AddMessage([MessageData]::new(($vNetNicsIPFwed | Select-Object NICName, EnableIPForwarding))); } else { $controlResult.AddMessage([VerificationResult]::Passed, [MessageData]::new("There are no NICs with EnableIPForwarding turned on the ERVNet")); } } else { $controlResult.AddMessage([VerificationResult]::Passed, [MessageData]::new("No NICs found on the ERVNet")); } return $controlResult; } hidden [ControlResult] CheckNSGUseonGatewaySubnet([ControlResult] $controlResult) { $gateWaySubnet = $this.ResourceObject.Subnets | Where-Object { $_.Name -eq "GatewaySubnet" } if($null -ne $gateWaySubnet) { if($null -ne $gateWaySubnet.NetworkSecurityGroup -and -not [System.String]::IsNullOrWhiteSpace($gateWaySubnet.NetworkSecurityGroup.Id)) { $controlResult.AddMessage([VerificationResult]::Failed, [MessageData]::new("NSG is configured on the Gateway Subnet of ERVNet", ($gateWaySubnet | Select-Object Name, NetworkSecurityGroupText))); } else { $controlResult.AddMessage([VerificationResult]::Passed, [MessageData]::new("There are no NSG's configured on the Gateway subnet of ERVNet")); } } else { $controlResult.AddMessage([VerificationResult]::Passed, [MessageData]::new("No Gateway subnet found on the ERVNet")); } return $controlResult; } hidden [ControlResult] CheckVnetPeering([ControlResult] $controlResult) { $vnetPeerings = Get-AzureRmVirtualNetworkPeering -VirtualNetworkName $this.ResourceContext.ResourceName -ResourceGroupName $this.ResourceContext.ResourceGroupName if($null -ne $vnetPeerings -and ($vnetPeerings|Measure-Object).count -gt 0) { $controlResult.AddMessage([VerificationResult]::Failed, [MessageData]::new("Below peering found on ERVNet", $vnetPeerings)); } else { $controlResult.AddMessage([VerificationResult]::Passed, [MessageData]::new("No VNet peerings found on ERVNet", $vnetPeerings)); } return $controlResult; } hidden [ControlResult] CheckMultiNICVMUsed([ControlResult] $controlResult) { if($null -ne $this.vNetNicsOutput) { $vNetNicsMultiVM = $this.vNetNicsOutput | Group-Object VMId | Where-Object {-not [System.String]::IsNullOrWhiteSpace($_.Name) -and $_.Count -gt 1} $hasTCPPassed = $true if($null -ne $vNetNicsMultiVM) { $vNetNicsMultiVM | ForEach-Object{ $NICGroup = @() $NICGroup += $_.Group if($null -ne $NICGroup) { $NICGroup | ForEach-Object{ Set-Variable -Name tempNIC -Value $_ if($null -ne $tempNIC.IpConfigurations ) { $tempIpConfigurations = [array]($tempNIC.IpConfigurations) $tempIpConfigurations | ForEach-Object{ Set-Variable -Name tempIPConfig -Value $_ if($null -ne $tempIPConfig.Subnet) { if(-not $tempIPConfig.Subnet.Id.StartsWith($this.ResourceObject.Id,"CurrentCultureIgnoreCase")) { $hasTCPPassed = $false } } } } } } } } $controlResult.AddMessage([MessageData]::new(($this.vNetNicsOutput | Group-Object VMId | Where-Object {-not [System.String]::IsNullOrWhiteSpace($_.Name) } | Select-Object @{Name="[Count of NICs]";Expression= {$_.Count}}, @{Name="[VM ResourceID]";Expression= {$_.Name}}))); if(-not $hasTCPPassed) { $controlResult.VerificationResult = [VerificationResult]::Failed; } else { $controlResult.AddMessage([VerificationResult]::Passed, [MessageData]::new("There are no VMs with more than one NIC")); } } else { $controlResult.AddMessage([VerificationResult]::Passed, [MessageData]::new("No NICs found on the ERVNet")); } return $controlResult; } hidden [ControlResult] CheckUDRAddedOnSubnet([ControlResult] $controlResult) { $subnetsWithUDRs = $this.ResourceObject.Subnets | Where-Object {$null -ne $_.RouteTable -and -not [System.String]::IsNullOrWhiteSpace($_.RouteTable.Id)} if($null -ne $subnetsWithUDRs -and ($subnetsWithUDRs | Measure-Object).count -gt 0) { $controlResult.AddMessage([VerificationResult]::Failed, [MessageData]::new(($subnetsWithUDRs | Select-Object Name, RouteTableText))); } else { $controlResult.AddMessage([VerificationResult]::Passed, [MessageData]::new("No UDRs found on any Subnet of ERVNet")); } return $controlResult; } hidden [ControlResult] CheckGatewayUsed([ControlResult] $controlResult) { $hasTCPPassed = $true $gateways = Get-AzureRmVirtualNetworkGateway -ResourceGroupName $this.ResourceContext.ResourceGroupName $count = 0 if(($null -ne $gateways) -and (($gateways | Measure-Object).count -gt 0)) { $gateways | ForEach-Object{ Set-Variable -Name gateway -Scope Local -Value $_ if($null -ne $gateway.IpConfigurations) { $tempIpConfigurations = [array]($gateway.IpConfigurations) $tempIpConfigurations | ForEach-Object{ Set-Variable -Name tempIpConfig -Value $_ if($tempIpConfig.Subnet.Id.StartsWith($this.ResourceObject.Id,"CurrentCultureIgnoreCase")) { if($gateway.GatewayType -ne "ExpressRoute") { $hasTCPPassed = $false } $controlResult.AddMessage([MessageData]::new("GateWay Name: " + $gateway.Name + " GatewayType: " + $gateway.GatewayType)); $count++ } } } } } if($count -eq 0) { $controlResult.AddMessage([MessageData]::new("No gateways found")); } if(-not $hasTCPPassed) { $controlResult.VerificationResult = [VerificationResult]::Failed; } else { $controlResult.VerificationResult = [VerificationResult]::Passed; } return $controlResult; } hidden [ControlResult] CheckInternalLoadBalancers([ControlResult] $controlResult) { $hasTCPPassed = $true $ilbs = Get-AzureRmLoadBalancer $count = 0 if($null -ne $ilbs -and ($ilbs|Measure-Object).count -gt 0) { $ilbs | ForEach-Object { Set-Variable -Name ilb -Value $_ -Scope Local if($null -ne $ilb -and $null -ne $ilb.FrontendIpConfigurations) { $ilb.FrontendIpConfigurations |ForEach-Object{ Set-Variable -Name frontEndIpConfig -Scope Local -Value $_ if($null -ne $frontEndIpConfig.Subnet) { if($frontEndIpConfig.Subnet.Id.StartsWith($this.ResourceObject.Id,"CurrentCultureIgnoreCase")) { if($null -ne $frontEndIpConfig.PublicIpAddress) { $subParts = $frontEndIpConfig.PublicIpAddress.Id.Split('/') $publicIpResourceName = $subParts[$subParts.Length-1] $pubResourceName = Get-AzureRmPublicIpAddress -Name $publicIpResourceName -ResourceGroupName $this.ResourceContext.ResourceGroupName $hasTCPPassed = $false $controlResult.AddMessage([MessageData]::new("ILB Name: " + $ilbs.Name + " PublicIP: " + $pubResourceName.IpAddress)); } $controlResult.AddMessage([MessageData]::new("No public Ips found on ILB: " + $ilbs.Name)); $count++ } } } } } } if($count -eq 0) { $controlResult.AddMessage([MessageData]::new("No ILB found")); } if(-not $hasTCPPassed) { $controlResult.VerificationResult = [VerificationResult]::Failed; } else { $controlResult.VerificationResult = [VerificationResult]::Passed; } return $controlResult; } hidden [ControlResult] CheckOnlyNetworkResourceExist([ControlResult] $controlResult) { $resources = [array](Find-AzureRmResource -ResourceGroupName $this.ResourceContext.ResourceGroupName) if($null -ne $resources) { $nonApprovedResources = [array]($resources | Where-Object { -not $_.ResourceType.StartsWith("Microsoft.Network","CurrentCultureIgnoreCase")}) if($null -ne $nonApprovedResources ) { $controlResult.AddMessage([VerificationResult]::Failed, [MessageData]::new("Other resource types found apart from Microsoft.Network\*. Below are the Resource IDs and Resource Types available under the ResourceGroup - ["+ $this.ResourceContext.ResourceGroupName +"]",($nonApprovedResources | Select-Object ResourceType, ResourceID))); } else { $controlResult.AddMessage([VerificationResult]::Passed, [MessageData]::new("No other resource types found apart from Microsoft.Network\* . Below are the Resource ID available undere the ResourceGroup - ["+ $this.ResourceContext.ResourceGroupName +"]")); } $controlResult.AddMessage([MessageData]::new("Resources configured under ResourceGroup - ["+ $this.ResourceContext.ResourceGroupName +"]",($resources | Select-Object ResourceType, ResourceID))); } else { $controlResult.AddMessage([VerificationResult]::Passed, [MessageData]::new("No other resources found under the ResourceGroup - ["+ $this.ResourceContext.ResourceGroupName +"]")); } return $controlResult; } hidden [ControlResult] CheckResourceLockConfigured([ControlResult] $controlResult) { $locks = [array](Get-AzureRMResourceLock -ResourceGroupName $this.ResourceContext.ResourceGroupName -AtScope) if($null -eq $locks -or $locks.Length -le 0) { $controlResult.AddMessage([VerificationResult]::Failed, [MessageData]::new("No Resource locks are configured at the ResourceGroup scope for - ["+ $this.ResourceContext.ResourceName +"]")); } else { $controlResult.AddMessage([VerificationResult]::Passed, [MessageData]::new("Found Resource locks configured at the ResourceGroup scope for - ["+ $this.ResourceContext.ResourceName +"]", $locks)); } return $controlResult; } hidden [ControlResult] CheckARMPolicyConfigured([ControlResult] $controlResult) { $controlSettings = $this.LoadServerConfigFile("Subscription.ARMPolicies.json"); $hasTCPPassed = $true $UserTags = @() $UserTags += "mandatory" $UserTags += "sdo" $output = @() if($null -ne $controlSettings) { $controlSettings =[array]($controlSettings) $controlSettings | ForEach-Object{ Set-Variable -Name pol -Scope Local -Value $_ Set-Variable -Name polEnabled -Scope Local -Value $_.enabled Set-Variable -Name policyDefinitionName -Scope Local -Value $_.policyDefinitionName Set-Variable -Name tags -Scope Local -Value $_.tags $haveMatchedTags = (($tags | Where-Object { $UserTags.Contains($_.Trim().ToLower()) }).Length -gt 0) if($polEnabled -and $haveMatchedTags) { $mandatoryPolicies = [array](Get-AzureRMPolicyAssignment | Where-Object {$_.Name -eq $policyDefinitionName}) if($null -eq $mandatoryPolicies -or $mandatoryPolicies.Length -le 0) { $hasTCPPassed = $false $output += $pol } } } } else { $controlResult.AddMessage([MessageData]::new("No mandatory ARM policies required to be configured on the subscription because of ERNetwork.")); } if(-not $hasTCPPassed) { $controlResult.AddMessage([VerificationResult]::Failed, [MessageData]::new("Some of the mandatory policies are missing which are demanded by the control tags - ["+ $UserTags +"]", $output )); } else { $controlResult.VerificationResult = [VerificationResult]::Passed; } return $controlResult; } }
PowerShellCorpus/PowerShellGallery/AzSDKPreview/2.2.0/Framework/Core/SVT/Services/ServiceBus.ps1
ServiceBus.ps1
#using namespace Microsoft.Azure.Commands.ServiceBus.Models Set-StrictMode -Version Latest class ServiceBus: SVTBase { hidden [PSObject[]] $NameSpacePolicies; hidden [PSObject[]] $Queues; hidden [PSObject[]] $Topics; ServiceBus([string] $subscriptionId, [string] $resourceGroupName, [string] $resourceName): Base($subscriptionId, $resourceGroupName, $resourceName) { } ServiceBus([string] $subscriptionId, [SVTResource] $svtResource): Base($subscriptionId, $svtResource) { $this.GetServiceBusDetails(); } hidden [void] GetServiceBusDetails() { if (-not $this.NameSpacePolicies) { $this.NameSpacePolicies = Get-AzureRmServiceBusNamespaceAuthorizationRule -ResourceGroup $this.ResourceContext.ResourceGroupName ` -NamespaceName $this.ResourceContext.ResourceName } # Get All Queues if (-not $this.Queues) { $this.Queues = Get-AzureRmServiceBusQueue -ResourceGroup $this.ResourceContext.ResourceGroupName -NamespaceName $this.ResourceContext.ResourceName } if (-not $this.Topics) { $this.Topics = Get-AzureRmServiceBusTopic -ResourceGroup $this.ResourceContext.ResourceGroupName -NamespaceName $this.ResourceContext.ResourceName } } hidden [ControlResult[]] CheckServiceBusRootPolicy([ControlResult] $controlResult) { [ControlResult[]] $resultControlResultList = @() #region "NameSpace" [ControlResult] $childControlResult = [ControlResult]@{ #ChildResourceName = $this.ResourceContext.ResourceName; }; $childControlResult.AddMessage([VerificationResult]::Verify, [MessageData]::new("Authorization rules for Namespace - ["+ $this.ResourceContext.ResourceName +"]. Validate that these rules must not be used at Queue/Topic level to send and receive messages.", $this.NameSpacePolicies)); $resultControlResultList += $childControlResult #endregion #region "Queue" if(($this.Queues|Measure-Object).count -gt 0) { foreach ($queue in $this.Queues) { [ControlResult] $childControlResult = [ControlResult]@{ ChildResourceName = $queue.Name; }; $queuePolicies = Get-AzureRmServiceBusQueueAuthorizationRule -ResourceGroup $this.ResourceContext.ResourceGroupName ` -NamespaceName $this.ResourceContext.ResourceName -QueueName $queue.Name if(($queuePolicies|Measure-Object).count -gt 0) { $childControlResult.AddMessage([VerificationResult]::Verify, [MessageData]::new("Validate that Queue - ["+ $queue.Name +"] must not use access policies defined at Service Bus namespace level.")); } else { $childControlResult.AddMessage([VerificationResult]::Failed, [MessageData]::new("No Authorization rules defined for Queue - ["+ $queue.Name +"]. Applications (senders/receivers) must not use access policies defined at Service Bus namespace level.")); } $resultControlResultList += $childControlResult } } else { $controlResult.AddMessage([MessageData]::new("Queue not available in Namespace - ["+ $this.ResourceContext.ResourceName +"]")); } #endregion #region "Topic" if(($this.Topics|Measure-Object).count -gt 0) { foreach ($topic in $this.Topics) { [ControlResult] $childControlResult = [ControlResult]@{ ChildResourceName = $topic.Name; }; $topicPolicies = Get-AzureRmServiceBusTopicAuthorizationRule -ResourceGroup $this.ResourceContext.ResourceGroupName ` -NamespaceName $this.ResourceContext.ResourceName -TopicName $topic.Name if(($topicPolicies|Measure-Object).count -gt 0) { $childControlResult.AddMessage([VerificationResult]::Verify, [MessageData]::new("Validate that Topic - ["+ $topic.Name +"] must not use access policies defined at Service Bus namespace level.")); } else { $childControlResult.AddMessage([VerificationResult]::Failed, [MessageData]::new("No Authorization rules defined for Topic - ["+ $topic.Name +"]. Applications (senders/receivers) must not use access policies defined at Service Bus namespace level.")); } $resultControlResultList += $childControlResult } } else { $controlResult.AddMessage([MessageData]::new("Topics not available in Namespace - ["+ $this.ResourceContext.ResourceName +"]")); } #endregion return $resultControlResultList; } hidden [ControlResult[]] CheckServiceBusAuthorizationRule([ControlResult] $controlResult) { [ControlResult[]] $resultControlResultList = @() #region "NameSpace" [ControlResult] $childControlResult = [ControlResult]@{ #ChildResourceName = $this.ResourceContext.ResourceName; }; $childControlResult.AddMessage([VerificationResult]::Verify, [MessageData]::new("Authorization rules for Namespace - ["+ $this.ResourceContext.ResourceName +"]. Validate that these rules are defined at correct entity level and with more limited permissions.", $this.NameSpacePolicies)); $resultControlResultList += $childControlResult #endregion #region "Queue" if(($this.Queues|Measure-Object).count -gt 0) { foreach ($queue in $this.Queues) { [ControlResult] $childControlResult = [ControlResult]@{ ChildResourceName = $queue.Name; }; $queuePolicies = Get-AzureRmServiceBusQueueAuthorizationRule -ResourceGroup $this.ResourceContext.ResourceGroupName ` -NamespaceName $this.ResourceContext.ResourceName -QueueName $queue.Name if(($queuePolicies|Measure-Object).count -gt 0) { $childControlResult.AddMessage([VerificationResult]::Verify, [MessageData]::new("Authorization rules for Queue - ["+ $queue.Name +"]. Validate that these rules are defined at correct entity level and with more limited permissions.", $queuePolicies)); } else { $childControlResult.AddMessage([VerificationResult]::Passed, [MessageData]::new("No Authorization rules defined for Queue - ["+ $queue.Name +"].")); } $resultControlResultList += $childControlResult } } else { $controlResult.AddMessage([MessageData]::new("Queue not available in Namespace - ["+ $this.ResourceContext.ResourceName +"]")); } #endregion #region "Topic" if(($this.Topics|Measure-Object).count -gt 0) { foreach ($topic in $this.Topics) { [ControlResult] $childControlResult = [ControlResult]@{ ChildResourceName = $topic.Name; }; $topicPolicies = Get-AzureRmServiceBusTopicAuthorizationRule -ResourceGroup $this.ResourceContext.ResourceGroupName ` -NamespaceName $this.ResourceContext.ResourceName -TopicName $topic.Name if(($topicPolicies|Measure-Object).count -gt 0) { $childControlResult.AddMessage([VerificationResult]::Verify, [MessageData]::new("Authorization rules for Topic - ["+ $topic.Name +"]. Validate that these rules are defined at correct entity level and with more limited permissions.", $topicPolicies)); } else { $childControlResult.AddMessage([VerificationResult]::Passed, [MessageData]::new("No Authorization rules defined for Topic - ["+ $topic.Name +"].")); } $resultControlResultList += $childControlResult } } else { $controlResult.AddMessage([MessageData]::new("Topics not available in Namespace - ["+ $this.ResourceContext.ResourceName +"]")); } #endregion return $resultControlResultList; } }
PowerShellCorpus/PowerShellGallery/AzSDKPreview/2.2.0/Framework/Core/SVT/Services/DataLakeStore.ps1
DataLakeStore.ps1
Set-StrictMode -Version Latest class DataLakeStore: SVTBase { hidden [PSObject] $ResourceObject; DataLakeStore([string] $subscriptionId, [string] $resourceGroupName, [string] $resourceName): Base($subscriptionId, $resourceGroupName, $resourceName) { $this.GetResourceObject(); } DataLakeStore([string] $subscriptionId, [SVTResource] $svtResource): Base($subscriptionId, $svtResource) { $this.GetResourceObject(); } hidden [PSObject] GetResourceObject() { if (-not $this.ResourceObject) { $this.ResourceObject = Get-AzureRmDataLakeStoreAccount -Name $this.ResourceContext.ResourceName ` -ResourceGroupName $this.ResourceContext.ResourceGroupName if(-not $this.ResourceObject) { throw ("Resource '{0}' not found under Resource Group '{1}'" -f ($this.ResourceContext.ResourceName), ($this.ResourceContext.ResourceGroupName)) } } return $this.ResourceObject; } hidden [ControlResult] CheckFirewall([ControlResult] $controlResult) { $firewallSetting = New-Object PSObject Add-Member -InputObject $firewallSetting -MemberType NoteProperty -Name FirewallState -Value $this.ResourceObject.Properties.FirewallState Add-Member -InputObject $firewallSetting -MemberType NoteProperty -Name FirewallRules -Value $this.ResourceObject.Properties.FirewallRules #Check for any to any rule (0.0.0.0-255.255.255.255) $anyToAnyRuleCount = 0 if(($firewallSetting.FirewallRules|Measure-Object).Count -gt 0) { $anyToAnyRuleCount = (($firewallSetting.FirewallRules | Where-Object{ $_.StartIpAddress -eq $this.ControlSettings.IPRangeStartIP -and $_.EndIpAddress -eq $this.ControlSettings.IPRangeEndIP}) | Measure-Object).count } if($firewallSetting.FirewallState -eq "Disabled") { $controlResult.AddMessage([VerificationResult]::Failed, "Firewall status - Disabled") } elseif($anyToAnyRuleCount -gt 0) { $controlResult.AddMessage("Firewall rules - [$this.ResourceContext.ResourceName]", $firewallSetting.FirewallRules) $controlResult.AddMessage([VerificationResult]::Failed,"Any to Any firewall rule ` (Start IP address: $this.ControlSettings.IPRangeStartIP To End IP Address :$this.ControlSettings.IPRangeEndIP) ` is defined which must be removed.") } elseif(($firewallSetting.FirewallRules | Measure-Object).Count -gt 0) { $controlResult.AddMessage([VerificationResult]::Verify, "Please verify Firewall rules", $firewallSetting.FirewallRules) } else { $controlResult.VerificationResult = [VerificationResult]::Passed } return $controlResult; } hidden [ControlResult] CheckACLAccess([ControlResult] $controlResult) { $rootAcl= $null $otherACLDetails = $null try { $rootAcl=Get-AzureRmDataLakeStoreItemAclEntry -Account $this.ResourceContext.ResourceName -Path "/" -ErrorAction Stop } catch { if(($_.Exception).Response.StatusCode -eq [System.Net.HttpStatusCode]::Forbidden) { $controlResult.AddMessage("Access denied: The user does not have the permission to perform this operation. Please check firewall and ACL settings."); return $controlResult } else { throw $_ } } $displayAclObj = $rootAcl | Select-Object Scope,Type,Id,Permission $controlResult.AddMessage("Current ACL setting for root folder of data lake store:", $displayAclObj) #check if ACL access is enabled for "Other" users (Public access) $otherACLDetails= $rootAcl | where-object { $_.Type -eq "Other" -and ($_.Scope -eq "Access" -or $_.Scope -eq "Default") } | Where-Object {$_.Permission -ne "---"} $isCompliant = $null -eq $otherACLDetails if($isCompliant) { $controlResult.VerificationResult = [VerificationResult]::Passed; } else { $displayOtherPermission = $otherACLDetails | Select-Object Scope,Type,Id,Permission $controlResult.AddMessage( [VerificationResult]::Failed, "Other have access to root folder of data lake store:", $displayOtherPermission) } return $controlResult; } hidden [ControlResult] CheckEncryptionAtRest([ControlResult] $controlResult) { $encryptionSettings = $this.ResourceObject | Select-Object -Property EncryptionConfig, EncryptionState, EncryptionProvisioningState if($this.ResourceObject.EncryptionState -eq [Microsoft.Azure.Management.DataLake.Store.Models.EncryptionState]::Enabled) { $controlResult.VerificationResult = [VerificationResult]::Passed; } else { $controlResult.VerificationResult = [VerificationResult]::Failed; } $controlResult.AddMessage("Encryption settings of Data Lake Store account", $encryptionSettings); return $controlResult; } }
PowerShellCorpus/PowerShellGallery/AzSDKPreview/2.2.0/Framework/Core/SVT/Services/LogicApps.ps1
LogicApps.ps1
Set-StrictMode -Version Latest class LogicAppControl { [string] $Name = "" [string] $Automated = "" [string] $MethodName = "" [string] $Remarks = "" } class LogicAppApprovedConnector { [string] $connectorName = "" [LogicAppControl[]] $ApplicableControls = @() [LogicAppControl[]] $NotApplicableControls = @() } class LogicAppNotApprovedConnector { [string] $connectorName = "" [string] $Remarks = "" } class LogicAppConnectorsMetadata { [LogicAppApprovedConnector[]] $ApprovedConnectors = @() [LogicAppNotApprovedConnector[]] $notApprovedConnectors = @() } class LogicApps: SVTBase { hidden [PSObject] $ResourceObject; hidden [LogicAppConnectorsMetadata] $LogicAppConnectorsMetadata LogicApps([string] $subscriptionId, [string] $resourceGroupName, [string] $resourceName): Base($subscriptionId, $resourceGroupName, $resourceName) { $this.GetResourceObject(); $this.LogicAppConnectorsMetadata = [LogicAppConnectorsMetadata] ($this.LoadServerConfigFile("LogicApps.Connectors.json")); } LogicApps([string] $subscriptionId, [SVTResource] $svtResource): Base($subscriptionId, $svtResource) { $this.GetResourceObject(); $this.LogicAppConnectorsMetadata = [LogicAppConnectorsMetadata] ($this.LoadServerConfigFile("LogicApps.Connectors.json")); } hidden [PSObject] GetResourceObject() { if (-not $this.ResourceObject) { $this.ResourceObject = Get-AzureRmResource -Name $this.ResourceContext.ResourceName ` -ResourceGroupName $this.ResourceContext.ResourceGroupName -ResourceType $this.ResourceContext.ResourceType if(-not $this.ResourceObject) { throw ("Resource '{0}' not found under Resource Group '{1}'" -f ($this.ResourceContext.ResourceName), ($this.ResourceContext.ResourceGroupName)) } } return $this.ResourceObject; } hidden [ControlResult[]] CheckConnectorsAADAuth([ControlResult] $controlResult) { [ControlResult[]] $controlResultList = @() [PSObject[]] $Connectors = @() if(Get-Member -InputObject $this.ResourceObject.Properties.parameters -Name '$connections' -MemberType Properties) { $apiConnections = $this.ResourceObject.Properties.parameters.'$connections'.value if($null -ne $apiConnections) { $apiConnections | Get-Member -MemberType *Property | ForEach-Object{ $apiConId = ($apiConnections.($_.name) | Select-Object connectionId).connectionId $apiConObj = Get-AzureRmResource -ResourceId $apiConId $apiName=$apiConObj.Properties.Api.Name $Connector = New-Object PSObject Add-Member -InputObject $Connector -MemberType NoteProperty -Name ConnectorName -Value $apiName Add-Member -InputObject $Connector -MemberType NoteProperty -Name ConnectorType -Value $apiName Add-Member -InputObject $Connector -MemberType NoteProperty -Name ConnectorObj -Value $null $Connectors+=$Connector } } } $Definition=$this.ResourceObject.Properties.definition if($null -ne $Definition.Actions -and -not[string]::IsNullOrEmpty($this.ResourceObject.Properties.definition.actions)) { $Definition.Actions | Get-Member -MemberType *Property | ForEach-Object{ $Name=$_.name if($Definition.Actions.$Name.type -ne 'ApiConnection') { $Connector = New-Object PSObject Add-Member -InputObject $Connector -MemberType NoteProperty -Name ConnectorName -Value $Name Add-Member -InputObject $Connector -MemberType NoteProperty -Name ConnectorType -Value $Definition.Actions.$Name.type Add-Member -InputObject $Connector -MemberType NoteProperty -Name ConnectorObj -Value $Definition.Actions.$Name $Connectors+=$Connector } } } if($null -ne $Definition.triggers -and -not[string]::IsNullOrEmpty($this.ResourceObject.Properties.definition.triggers)) { $Definition.Triggers | Get-Member -MemberType *Property | ForEach-Object{ $Name=$_.name if($Definition.Triggers.$Name.type -ne 'ApiConnection') { $Connector = New-Object PSObject Add-Member -InputObject $Connector -MemberType NoteProperty -Name ConnectorName -Value $Name Add-Member -InputObject $Connector -MemberType NoteProperty -Name ConnectorType -Value $Definition.Triggers.$Name.type Add-Member -InputObject $Connector -MemberType NoteProperty -Name ConnectorObj -Value $Definition.Triggers.$Name $Connectors+=$Connector } } } if($Connectors.Count -gt 0) { $Result = $this.GetConnectorsStatus($Connectors , "AAD") if($null -ne $Result) { $controlResultList += $Result } } else { $controlResult.AddMessage([VerificationResult]::Passed,"Logic app workflow is empty. No connectors found.") $controlResultList += $controlResult } return $controlResultList } hidden [ControlResult[]] CheckConnectorsEncryptionInTransit([ControlResult] $controlResult) { [ControlResult[]] $controlResultList = @() [PSObject[]] $Connectors = @() if(Get-Member -InputObject $this.ResourceObject.Properties.parameters -Name '$connections' -MemberType Properties) { $apiConnections = $this.ResourceObject.Properties.parameters.'$connections'.value if($null -ne $apiConnections) { $apiConnections | Get-Member -MemberType *Property | ForEach-Object{ $apiConId = ($apiConnections.($_.name) | Select-Object connectionId).connectionId $apiConObj = Get-AzureRmResource -ResourceId $apiConId $apiName=$apiConObj.Properties.Api.Name $Connector = New-Object PSObject Add-Member -InputObject $Connector -MemberType NoteProperty -Name ConnectorName -Value $apiName Add-Member -InputObject $Connector -MemberType NoteProperty -Name ConnectorType -Value $apiName Add-Member -InputObject $Connector -MemberType NoteProperty -Name ConnectorObj -Value $null $Connectors+=$Connector } } } $Definition=$this.ResourceObject.Properties.definition if($null -ne $Definition.Actions -and -not[string]::IsNullOrEmpty($this.ResourceObject.Properties.definition.actions)) { $Definition.Actions | Get-Member -MemberType *Property | ForEach-Object{ $Name=$_.name if($Definition.Actions.$Name.type -ne 'ApiConnection') { $Connector = New-Object PSObject Add-Member -InputObject $Connector -MemberType NoteProperty -Name ConnectorName -Value $Name Add-Member -InputObject $Connector -MemberType NoteProperty -Name ConnectorType -Value $Definition.Actions.$Name.type Add-Member -InputObject $Connector -MemberType NoteProperty -Name ConnectorObj -Value $Definition.Actions.$Name $Connectors+=$Connector } } } if($null -ne $Definition.triggers -and -not[string]::IsNullOrEmpty($this.ResourceObject.Properties.definition.triggers)) { $Definition.Triggers | Get-Member -MemberType *Property | ForEach-Object{ $Name=$_.name if($Definition.Triggers.$Name.type -ne 'ApiConnection') { $Connector = New-Object PSObject Add-Member -InputObject $Connector -MemberType NoteProperty -Name ConnectorName -Value $Name Add-Member -InputObject $Connector -MemberType NoteProperty -Name ConnectorType -Value $Definition.Triggers.$Name.type Add-Member -InputObject $Connector -MemberType NoteProperty -Name ConnectorObj -Value $Definition.Triggers.$Name $Connectors+=$Connector } } } if($Connectors.Count -gt 0) { $Result = $this.GetConnectorsStatus($Connectors , "EncryptionTransit") if($null -ne $Result) { $controlResultList += $Result } } return $controlResultList } hidden [ControlResult] CheckConnectorsSecretsHandling([ControlResult] $controlResult) { $complianceStatus = [VerificationResult]::Manual $userMsg = [string]::Empty $IsFailed = $false $Definition=$this.ResourceObject.Properties.definition if($null -ne $Definition.Actions -and -not[string]::IsNullOrEmpty($this.ResourceObject.Properties.definition.actions)) { $Definition.Actions | Get-Member -MemberType *Property | ForEach-Object{ $connectorName=$_.name $Connector = $Definition.Actions.$connectorName if($Connector.type -eq 'http') { $complianceStatus = $this.CheckSecretsHandlingForHttp($Connector) if($complianceStatus -eq [VerificationResult]::Failed) { $IsFailed = $true $userMsg += "Connector - " + $connectorName + "`r`nType - " + $Connector.type ` +"`r`nSecret(s) are given as plain text in Code View, must use 'SecureString' parameter" } } } } if($null -ne $Definition.triggers -and -not[string]::IsNullOrEmpty($this.ResourceObject.Properties.definition.triggers)) { $Definition.Triggers | Get-Member -MemberType *Property | ForEach-Object{ $connectorName=$_.name $Connector = $Definition.Triggers.$connectorName if($Connector.type -eq 'http') { $complianceStatus = $this.CheckSecretsHandlingForHttp($Connector) if($complianceStatus -eq [VerificationResult]::Failed) { $IsFailed = $true $userMsg += "Connector - " + $connectorName + "`r`nType - " + $Connector.type ` +"`r`nSecret(s) are given as plain text in Code View, must use 'SecureString' parameter" } } } } #No HTTP connector is present. Display generic message for users. if($userMsg -eq [string]::Empty) { $userMsg = "Please verify manually that Logic App code view doesn't contain any secrets/credentials in plain text" } if($IsFailed) { $complianceStatus = [VerificationResult]::Failed } $controlResult.AddMessage($complianceStatus , $userMsg) return $controlResult } hidden [ControlResult] CheckLogicAppsInSameRG([ControlResult] $controlResult) { $OtherAppsinSameRG= Get-AzureRmResource -ResourceGroupName $this.ResourceContext.ResourceGroupName -ResourceType $this.ResourceContext.ResourceType | Where-Object{$_.ResourceId -ne $this.ResourceObject.ResourceId } if($null -ne $OtherAppsinSameRG) { $controlResult.AddMessage("Below are the Logic Apps present in the same resource group as " + $this.ResourceContext.ResourceName + " - Logic App") $controlResult.AddMessage([VerificationResult]::Verify, "Validate that these Logic Apps trust each other",$OtherAppsinSameRG) } else { $controlResult.AddMessage([VerificationResult]::Passed, "No other logic apps found in resource group ["+ $this.ResourceContext.ResourceGroupName +"]") } return $controlResult } hidden [ControlResult] CheckTriggersAccessControl([ControlResult] $controlResult) { $IsFailed = $False $IsAccessConfigSet = ($null -ne (Get-Member -InputObject $this.Resourceobject.Properties -Name accessControl -MemberType Properties)) if($IsAccessConfigSet) { $IsTriggerRestricted = ($null -ne (Get-Member -InputObject $this.Resourceobject.Properties.accessControl -Name triggers -MemberType Properties)) #Check trigger access control if($IsTriggerRestricted) { if($this.ResourceObject.Properties.accessControl.triggers.allowedCallerIpAddresses.Count -eq 0) { #verify scenario $controlResult.AddMessage("Access control for triggers is set to `"Only other Logic Apps`"") } else { $triggerIPRange = $this.ResourceObject.Properties.accessControl.triggers.allowedCallerIpAddresses.addressRange if($triggerIPRange -contains $this.ControlSettings.UniversalIPRange) { #fail if universal IP range found $IsFailed = $True $controlResult.AddMessage("IP range $($this.ControlSettings.UniversalIPRange) must be removed from triggers IP ranges") } else { $controlResult.AddMessage("Please verify below:") } $controlResult.AddMessage("IP ranges for triggers :",$triggerIPRange) } } else { #fail if no trigger access control found $IsFailed = $True $controlResult.AddMessage("Access control for triggers is not found") } } else { $IsFailed = $True $controlResult.AddMessage("Access control for triggers is not found") } if($IsFailed -eq $True) { $controlResult.VerificationResult = [VerificationResult]::Failed } else { $controlResult.VerificationResult = [VerificationResult]::Verify } return $controlResult } hidden [ControlResult] CheckContentsAccessControl([ControlResult] $controlResult) { $IsFailed = $False $IsAccessConfigSet = ($null -ne (Get-Member -InputObject $this.Resourceobject.Properties -Name accessControl -MemberType Properties)) if($IsAccessConfigSet) { $IsContentRestricted = ($null -ne (Get-Member -InputObject $this.Resourceobject.Properties.accessControl -Name contents -MemberType Properties)) #check content access control if($IsContentRestricted) { $contentIPRange = $this.ResourceObject.Properties.accessControl.contents.allowedCallerIpAddresses.addressRange if($contentIPRange -contains $this.ControlSettings.UniversalIPRange) { #fail if universal IP range assigned $IsFailed = $True $controlResult.AddMessage("IP range $($this.ControlSettings.UniversalIPRange) must be removed from contents IP ranges") } else { $controlResult.AddMessage("Please verify below:") } $controlResult.AddMessage("IP ranges for contents :", $contentIPRange) } else { #fail if content access control not found $IsFailed = $True $controlResult.AddMessage("Access control for contents is not found") } } else { $IsFailed = $True $controlResult.AddMessage("Access control for contents is not found") } if($IsFailed -eq $True) { $controlResult.VerificationResult = [VerificationResult]::Failed } else { $controlResult.VerificationResult = [VerificationResult]::Verify } return $controlResult } #internal functions hidden [boolean] CheckSecretParameter([string] $secretString,[PSObject[]] $parametersList) { if(!$secretString.Trim().StartsWith("@parameters(")) { return $false } else { $temp=($secretString.replace(' ','')).split('(')[1] $parametervalue=$temp.split(')')[0].Trim("'") $type=$parametersList.$parametervalue.type if($type -ne "securestring") {return $false} else {return $true} } } hidden [VerificationResult] CheckSecretsHandlingForHttp([PSObject] $Connector) { $complianceStatus = [VerificationResult]::Manual if(Get-Member -inputobject $Connector.inputs -name "authentication" -Membertype Properties) { $authentication = $Connector.inputs.authentication switch($authentication.type) { "ActiveDirectoryOAuth" { $IsValidSecret=$this.CheckSecretParameter($authentication.secret,$this.ResourceObject.Properties.definition.parameters) if($IsValidSecret -ne $true) { $complianceStatus = [VerificationResult]::Failed } } "ClientCertificate" { $IsValidPw=$this.CheckSecretParameter($authentication.Password,$this.ResourceObject.Properties.definition.parameters) if($IsValidPw -ne $true) { $complianceStatus = [VerificationResult]::Failed } } "default" { $complianceStatus = [VerificationResult]::Manual } } } return $complianceStatus } hidden [ControlResult] CheckAadAuthForHttp([string] $remarks , [ControlResult] $childControlResult , [PSObject]$Connector) { $isPassed = $false if(Get-Member -inputobject $Connector.ConnectorObj.inputs -name "authentication" -Membertype Properties) { if($Connector.ConnectorObj.inputs.authentication.type -eq "ActiveDirectoryOAuth") { $isPassed = $true } } if($isPassed) { $childControlResult.AddMessage([VerificationResult]::Passed,"AAD Authentication is used in connector - "+ $Connector.ConnectorName) } else { $childControlResult.AddMessage([VerificationResult]::Failed, "AAD Authentication is not used in connector - "+ $Connector.ConnectorName) } return $childControlResult } hidden [ControlResult] CheckEncryptionTransitForHttp([string] $remarks , [ControlResult] $childControlResult , [PSObject]$Connector) { $isPassed = $true $uriString = $Connector.ConnectorObj.inputs.uri if(([system.Uri]$uriString).Scheme -ne 'https') { $isPassed = $false } if($isPassed) { $childControlResult.AddMessage([VerificationResult]::Passed,"Connector name : " + $Connector.ConnectorName + "`r`nConnector URI : "+ $uriString) } else { $childControlResult.AddMessage([VerificationResult]::Failed, ` "Must use HTTPS URI for below connector`r`n" ` + "Connector name : " + $Connector.ConnectorName + "`r`nConnector URI : "+$uriString) } return $childControlResult } hidden [ControlResult] CheckEncryptionTransitForWebhook([string] $remarks , [ControlResult] $childControlResult , [PSObject]$Connector) { $isPassed = $true $subURI = $Connector.connectorObj.inputs.subscribe.uri $unSubURI = $connector.connectorObj.inputs.unsubscribe.uri if(([system.Uri]$subURI).Scheme -ne 'https' -or ([system.Uri]$unSubURI).Scheme -ne 'https') { $isPassed = $false } if($isPassed) { $childControlResult.AddMessage([VerificationResult]::Passed, "Connector name : " + $Connector.ConnectorName ` + "`r`nWebhook subscribe URI : "+ $subURI` + "`r`nWebhook unsubscribe URI : "+$unSubURI) } else { $childControlResult.AddMessage([VerificationResult]::Failed, "Must use HTTPS URI(s) for below connector`r`n" ` + "Connector name : " + $Connector.ConnectorName ` + "`r`nWebhook subscribe URI : "+ $subURI` + "`r`nWebhook unsubscribe URI : "+$unSubURI) } return $childControlResult } hidden [ControlResult[]] GetConnectorsStatus([PSObject] $Connectors,[string] $controlName) { $controlResultList = @() $Connectors | ForEach-Object{ $Connector = $_ $connectorName=$Connector.ConnectorName $ConnectorObj = $Connector.ConnectorObj $connectorType=$Connector.ConnectorType [ControlResult] $childControlResult = [ControlResult]@{ChildResourceName = $connectorName + " ("+$connectorType+" connector)";} if($connectorName -eq "manual") { $connectorName = $connectorType } #check if this connector belongs to not approved list $notApprovedConnector = $this.LogicAppConnectorsMetadata.NotApprovedConnectors | Where-Object {$_.connectorName -eq $connectorType} if($notApprovedConnector) { $childControlResult.AddMessage([VerificationResult]::Failed, $notApprovedConnector.Remarks) } else { #Check if it belongs to approved connectors $approvedConnector = $this.LogicAppConnectorsMetadata.ApprovedConnectors | Where-Object {$_.connectorName -eq $connectorType} if(($approvedConnector|Measure-Object).Count -gt 0) { #check if control is applicable on this connector $applicableControl = $approvedConnector.ApplicableControls | Where-Object {$_.Name -eq $controlName} $notApplicableControl = $approvedConnector.NotApplicableControls | Where-Object {$_.Name -eq $controlName} if(($applicableControl|Measure-Object).Count -gt 0) { #Get method name $methodName = $applicableControl.MethodName $childControlResult = $this.$methodName($applicableControl.Remarks , $childControlResult, $Connector) } else { $methodName = $notApplicableControl.MethodName if($notApplicableControl.Remarks -eq [string]::Empty) { $notApplicableControl.Remarks = "This control is not applicable on connector type - " + $connectorType } $childControlResult = $this.$methodName($notApplicableControl.Remarks , $childControlResult, $Connector) } } else { $childControlResult.AddMessage([VerificationResult]::Manual, $connectorType+" connector is not evaluated yet") } } $controlResultList += $childControlResult } return $controlResultList } hidden [ControlResult] DefaultPassed([string] $remarks,[ControlResult] $childControlResult, [PSObject] $Connector) { $childControlResult.AddMessage([VerificationResult]::Passed, $remarks) return $childControlResult } hidden [ControlResult] DefaultManual([string] $remarks,[ControlResult] $childControlResult, [PSObject] $Connector) { $childControlResult.AddMessage([VerificationResult]::Manual, $remarks) return $childControlResult } }
PowerShellCorpus/PowerShellGallery/AzSDKPreview/2.2.0/Framework/Core/AzureMonitoring/OMSMonitoring.ps1
OMSMonitoring.ps1
Set-StrictMode -Version Latest class OMSMonitoring: AzSdkRoot { [string] $OMSSubCCViewTemplateFilepath; [string] $OMSAppCCViewTemplateFilepath; OMSMonitoring([string] $subscriptionId): Base([string] $subscriptionId) { #$this.PublishRunIdentifier(); $OMSSubCCViewTemplateFile = $this.LoadServerConfigFile("AzSDK.AM.OMSSetup.json"); $OMSAppCCViewTemplateFile = $this.LoadServerConfigFile("AzSDK.AM.OMSSetup.App.json"); $OMSLogPath = [Constants]::AzSdkTempFolderPath + "\OMS"; if(-not (Test-Path -Path $OMSLogPath)) { mkdir -Path $OMSLogPath -Force | Out-Null } $this.OMSSubCCViewTemplateFilepath = $OMSLogPath+"\AzSDK.AM.OMSSetup.json"; $this.OMSAppCCViewTemplateFilepath = $OMSLogPath+"\AzSDK.AM.OMSSetup.App.json"; $OMSSubCCViewTemplateFile | ConvertTo-Json -Depth 99 | Out-File $this.OMSSubCCViewTemplateFilepath $OMSAppCCViewTemplateFile | ConvertTo-Json -Depth 99 | Out-File $this.OMSAppCCViewTemplateFilepath } [void] CreateOMSPolicies([string]$OMSResourceGroupName, [string]$OMSSubCCParamFilePath, [string]$OMSAppCCParamFilePath, [bool]$ValidateOnly) { $OptionalParameters = New-Object -TypeName Hashtable $ErrorMessages = @() if ($ValidateOnly) { $ErrorMessages =@() if(-not [string]::IsNullOrWhiteSpace($OMSSubCCParamFilePath)) { Test-AzureRmResourceGroupDeployment -ResourceGroupName $OMSResourceGroupName ` -TemplateFile $this.OMSSubCCViewTemplateFilepath ` -TemplateParameterFile $OMSSubCCParamFilePath -Verbose #$SubErrorMessages = $SubErrorMessages | ForEach-Object { $_.Exception.Message.TrimEnd("`r`n") } #$ErrorMessages += $SubErrorMessages } if(-not [string]::IsNullOrWhiteSpace($OMSAppCCParamFilePath)) { Test-AzureRmResourceGroupDeployment -ResourceGroupName $OMSResourceGroupName ` -TemplateFile $this.OMSAppCCViewTemplateFilepath ` -TemplateParameterFile $OMSAppCCParamFilePath -Verbose #$SubErrorMessages = $SubErrorMessages | ForEach-Object { $_.Exception.Message.TrimEnd("`r`n") } #$ErrorMessages += $SubErrorMessages } } else { $ErrorMessages =@() if(-not [string]::IsNullOrWhiteSpace($OMSSubCCParamFilePath)) { $SubErrorMessages = @() New-AzureRmResourceGroupDeployment -Name ((Get-ChildItem $this.OMSSubCCViewTemplateFilepath).BaseName + '-' + ((Get-Date).ToUniversalTime()).ToString('MMdd-HHmm')) ` -ResourceGroupName $OMSResourceGroupName ` -TemplateFile $this.OMSSubCCViewTemplateFilepath ` -TemplateParameterFile $OMSSubCCParamFilePath ` @OptionalParameters ` -Verbose -Force -ErrorVariable SubErrorMessages $SubErrorMessages = $SubErrorMessages | ForEach-Object { $_.Exception.Message.TrimEnd("`r`n") } $ErrorMessages += $SubErrorMessages } if(-not [string]::IsNullOrWhiteSpace($OMSAppCCParamFilePath)) { $SubErrorMessages = @() New-AzureRmResourceGroupDeployment -Name ((Get-ChildItem $this.OMSAppCCViewTemplateFilepath).BaseName + '-' + ((Get-Date).ToUniversalTime()).ToString('MMdd-HHmm')) ` -ResourceGroupName $OMSResourceGroupName ` -TemplateFile $this.OMSAppCCViewTemplateFilepath ` -TemplateParameterFile $OMSAppCCParamFilePath ` @OptionalParameters ` -Verbose -Force -ErrorVariable SubErrorMessages $SubErrorMessages = $SubErrorMessages | ForEach-Object { $_.Exception.Message.TrimEnd("`r`n") } $ErrorMessages += $SubErrorMessages } } if ($ErrorMessages) { "", ("{0} returned the following errors:" -f ("Template deployment", "Validation")[[bool]$ValidateOnly]), @($ErrorMessages) | ForEach-Object { $this.PublishCustomMessage([MessageData]::new($_));} } } }
PowerShellCorpus/PowerShellGallery/AzSDKPreview/2.2.0/Framework/Core/ContinuousCompliance/CCAutomation.ps1
CCAutomation.ps1
using namespace System.Management.Automation Set-StrictMode -Version Latest class CCAutomation: CommandBase { hidden [AutomationAccount] $AutomationAccount hidden [Runbook[]] $Runbooks = @() hidden [string] $RunbookName = "Continuous_Assurance_Runbook" hidden [RunbookSchedule[]] $RunbookSchedules = @() hidden [string] $ScheduleName = "Scan_Schedule" hidden [Variable[]] $Variables = @() hidden [UserConfig] $UserConfig hidden [string] $AzSDKCCRGName = "AzSDKCCRG" hidden [string] $deprecatedAccountName = "AzSDKCCAutomationAccount" hidden [PSObject] $OutputObject = @{} hidden [SelfSignedCertificate] $certificateDetail = [SelfSignedCertificate]::new() hidden [Hashtable] $reportStorageTags = @{} hidden [string] $exceptionMsg = "There was an error while configuring Automation Account." hidden [boolean] $isExistingADApp = $false hidden [boolean] $cleanupFlag = $true hidden [string] $updateCommandName = "Update-AzSDKContinuousAssurance" hidden [string] $removeCommandName = "Remove-AzSDKContinuousAssurance" hidden [string] $installCommandName = "Install-AzSDKContinuousAssurance" hidden [string] $certificateAssetName = "AzureRunAsCertificate" hidden [string] $connectionAssetName = "AzureRunAsConnection" CCAutomation( [string] $subscriptionId, [InvocationInfo] $invocationContext, [string] $AutomationAccountLocation,` [string] $ResourceGroupNames,` [string] $OMSWorkspaceId,` [string] $OMSSharedKey,` [string] $AzureADAppName) : Base($subscriptionId, $invocationContext) { $this.AutomationAccount = [AutomationAccount]@{ Name = "AzSDKContinuousAssurance"; Location = $AutomationAccountLocation; AzureADAppName = $AzureADAppName } $this.UserConfig = [UserConfig]@{ OMSCredential = [OMSCredential]@{ OMSWorkspaceId = $OMSWorkspaceId; OMSSharedKey = $OMSSharedKey }; ResourceGroupNames = $ResourceGroupNames } } CCAutomation( [string] $subscriptionId, [InvocationInfo] $invocationContext) : Base($subscriptionId, $invocationContext) { $this.AutomationAccount = [AutomationAccount]@{ Name = "AzSDKContinuousAssurance" } } [MessageData[]] InstallAzSDKContinuousAssurance() { [MessageData[]] $messages = @(); try { #region :check if resource provider is registered if((Get-AzureRmResourceProvider -ProviderNamespace "Microsoft.Automation" ` -Location $this.AutomationAccount.Location -ErrorAction Stop | Measure-Object).Count -eq 0) { $this.cleanupFlag = $false throw ($this.exceptionMsg + "Resource provider 'Microsoft.Automation' is not registered under location " + $this.AutomationAccount.Location) } #endregion #region :check if older CC version is installed and remove if exists and code to be removed after 06/30/2017 # $this.DeleteResourceGroup($this.AzSDKCCRGName); #endregion #region :create new resource group/check if RG exists# $this.AutomationAccount.ResourceGroup = [ConfigurationManager]::GetAzSdkConfigData().AzSDKRGName if((Get-AzureRmResourceGroup -Name $this.AutomationAccount.ResourceGroup -ErrorAction SilentlyContinue|Measure-Object).Count -eq 0) { $this.PublishCustomMessage("Started setting up Automation Account for Continuous Assurance"); $this.NewCCResourceGroup() } else { #check if automation account exists in RG and code to be updated after 06/30/2017 $existingAccount = Find-AzureRMresource -ResourceGroupName $this.AutomationAccount.ResourceGroup -ResourceType "Microsoft.Automation/automationAccounts" | where-object{$_.ResourceName -in ($this.AutomationAccount.Name,$this.deprecatedAccountName)} if(($existingAccount|Measure-Object).Count -gt 0) { $existingAccount | ForEach-Object{ $tags = $_.Tags #check if depricated version found (old accounts don't have tags) if($_.ResourceName-eq $this.deprecatedAccountName -or ` $tags.Count -eq 0 -or !$tags.Contains("AzSDKVersion") -or ` ([System.Version]$tags["AzSDKVersion"] -lt [System.Version]([ConfigurationManager]::GetAzSdkConfigData().UpdateCompatibleCCVersion))) { #remove depricated version $this.RemoveAzSDKContinuousAssurance($this.SubscriptionContext.SubscriptionId) } else { $this.cleanupFlag = $false #need to run update command throw("Automation Account [$($this.AutomationAccount.Name)] for Continuous Assurance already exists in subscription. If you want to update existing account, please run command '"+$this.updateCommandName+"' with required parameters") } } } else { #update tags to existing RG $this.PublishCustomMessage("Started setting up Automation Account for Continuous Assurance"); $this.AutomationAccount.RGTags += @{ "AzSDKFeature" = "ContinuousAssurance"; "AzSDKVersion"=$this.GetCurrentModuleVersion(); "CreationTime"=$(get-date).ToUniversalTime().ToString("yyyyMMdd_HHmmss"); } Set-AzureRmResourceGroup -Name $this.AutomationAccount.ResourceGroup ` -Tag $this.AutomationAccount.RGTags ` -ErrorAction Stop $this.OutputObject.ResourceGroup = $null } } #endregion #region: Deploy empty Automation account $this.PublishCustomMessage("Creating Automation Account - [" + $this.AutomationAccount.Name + "]") $this.NewEmptyAutomationAccount() #endregion #region: Create SPN, Certificate $this.NewCCAzureRunAsAccount() #endregion #region: Create/reuse existing storage account (Added this before creating variables since it's value is used in it) $this.UserConfig.StorageAccountRG = $this.AutomationAccount.ResourceGroup $existingStorage = $this.CheckContinuousAssuranceStorage() if(($existingStorage|Measure-Object).Count -gt 0) { $this.UserConfig.StorageAccountName = $existingStorage.ResourceName $this.PublishCustomMessage("Found existing Storage Account ["+ $this.UserConfig.StorageAccountName +"], it will be used to store Continuous Assurance output reports") } else { #create new storage $this.UserConfig.StorageAccountName = ("azsdk" + (Get-Date).ToUniversalTime().ToString("yyyyMMddHHmmss")) $this.PublishCustomMessage("Creating Storage Account ["+ $this.UserConfig.StorageAccountName +"] to store Continuous Assurance output reports") $newStorage = [Helpers]::NewAzsdkCompliantStorage($this.UserConfig.StorageAccountName,$this.UserConfig.StorageAccountRG, $this.AutomationAccount.Location) if(!$newStorage) { $this.cleanupFlag = $false throw ($this.exceptionMsg + "Failed to create AzSDK compliant Storage Account for output reports storage. Please run command again.") } else { #apply tags $timestamp = $(get-date).ToUniversalTime().ToString("yyyyMMdd_HHmmss") $this.reportStorageTags += @{ "AzSDKFeature" = "ContinuousAssuranceStorage"; "CreationTime"=$timestamp; "LastModified"=$timestamp } Set-AzureRmStorageAccount -ResourceGroupName $newStorage.ResourceGroupName -Name $newStorage.StorageAccountName -Tag $this.reportStorageTags -Force -ErrorAction SilentlyContinue } } $this.OutputObject.StorageAccount = $this.CheckContinuousAssuranceStorage() | Select-Object Name,ResourceGroupName,Sku,Tags #endregion #region: Deploy Automation account items (runbooks, variables, schedules) $this.DeployCCAutomationAccountItems() #endregion #succefully installed $this.cleanupFlag = $false $this.PublishCustomMessage("Completed setting up Automation Account for Continuous Assurance") $messages += [MessageData]::new("Below resources are created in resource group ["+$this.AutomationAccount.ResourceGroup+"] as part of Continuous Assurance",$this.OutputObject) } catch { #cleanup if exception occurs if($this.cleanupFlag) { $this.PublishCustomMessage("Error occured. Rolling back the changes.") #$this.DeleteResourceGroup($this.AutomationAccount.ResourceGroup); $account = Get-AzureRMAutomationAccount -ResourceGroupName $this.AutomationAccount.ResourceGroup -Name $this.AutomationAccount.Name -ErrorAction silentlycontinue if(($account|Measure-Object).Count -gt 0) { $account | Remove-AzureRmAutomationAccount -Force -ErrorAction SilentlyContinue } if(!$this.isExistingADApp) { #clean AD App only if AD App was newly created $ADApplication = Get-AzureRmADApplication -DisplayNameStartWith $this.AutomationAccount.AzureADAppName -ErrorAction SilentlyContinue | Where-Object -Property DisplayName -eq $this.AutomationAccount.AzureADAppName if($ADApplication) { Remove-AzureRmADApplication -ObjectId $ADApplication.ObjectId -Force -ErrorAction Stop } } } $this.PublishException($_) } return $messages; } [MessageData[]] UpdateAzSDKContinuousAssurance($ResourceGroupNames,$OMSWorkspaceId,$OMSSharedKey,$AzureADAppName,$UpdateCertificate) { [MessageData[]] $messages = @(); #set default account properties $this.AutomationAccount.Name = "AzSDKContinuousAssurance" $this.AutomationAccount.ResourceGroup = [ConfigurationManager]::GetAzSdkConfigData().AzSDKRGName #region :check if automation account is compatible for update $existingAccount = Find-AzureRMresource -ResourceGroupName $this.AutomationAccount.ResourceGroup -ResourceType "Microsoft.Automation/automationAccounts" | where-object{$_.ResourceName -in ($this.AutomationAccount.Name,$this.deprecatedAccountName)} $automationTags = @() if(($existingAccount|Measure-Object).Count -gt 0) { #check if depricated version found (old accounts don't have tags) $existingAccount | ForEach-Object{ $automationTags = $_.Tags if($automationTags.Count -eq 0 -or !$automationTags.Contains("AzSDKVersion") -or ` ([System.Version]$automationTags["AzSDKVersion"] -lt [System.Version]([ConfigurationManager]::GetAzSdkConfigData().UpdateCompatibleCCVersion))) { throw("Deprecated and uncompatible version of Continuous Assurance Automation Account [$($_.ResourceName)] found. Please remove this account using '"+$this.removeCommandName+"' command and install latest version using '"+$this.installCommandName+"' command with required parameters.") } } } else { throw("No Continuous Assurance Automation Account found. Please install using '"+ $this.installCommandName +"' command with required parameters.") } #endregion $this.PublishCustomMessage("Started updating Automation Account for Continuous Assurance"); #region :Remove existing and create new AzureRunAsConnection if AzureADAppName param is passed else update certificate if UpdateCertificate switch is present if(![string]::IsNullOrWhiteSpace($AzureADAppName)) { $this.PublishCustomMessage("Updating $($this.connectionAssetName) in Automation Account") $this.RemoveCCAzureRunAsAccount() $this.RemoveCCAzureRunAsCertificate() $this.AutomationAccount.AzureADAppName = $AzureADAppName $this.NewCCAzureRunAsAccount() } elseif($UpdateCertificate) { $this.PublishCustomMessage("Updating certificate in $($this.connectionAssetName)") $this.RemoveCCAzureRunAsCertificate() $this.UpdateCCAzureRunAsAccount() } #endregion #region: create storage account if not present and update same in variables# $this.OutputObject.Variables = @() #This is added to initialize variables $newStorageName = $null #check if storage exists $existingStorage = $this.CheckContinuousAssuranceStorage() if(($existingStorage|Measure-Object).Count -gt 0) { #update/add tags $modifyTimestamp = $(get-date).ToUniversalTime().ToString("yyyyMMdd_HHmmss") $storageTags = $existingStorage.Tags if($storageTags.ContainsKey("LastModified")) { $storageTags["LastModified"] = $modifyTimestamp; } else { $storageTags.Add("LastModified",$modifyTimestamp) } if(!$storageTags.ContainsKey("AzSDKFeature")) { $storageTags.Add("AzSDKFeature","ContinuousAssuranceStorage") } if(!$storageTags.ContainsKey("CreationTime")) { $storageTags.Add("CreationTime",$modifyTimestamp) } Set-AzureRmStorageAccount -ResourceGroupName $existingStorage.ResourceGroupName -Name $existingStorage.ResourceName -Tag $storageTags -Force -ErrorAction SilentlyContinue $this.OutputObject.StorageAccountName = $existingStorage.ResourceName } else { #create default storage $newStorageName = ("azsdk" + (Get-Date).ToUniversalTime().ToString("yyyyMMddHHmmss")) $this.PublishCustomMessage("Creating Storage Account [$newStorageName] to store Continuous Assurance output reports") $newStorage = [Helpers]::NewAzsdkCompliantStorage($newStorageName, $this.AutomationAccount.ResourceGroup, $existingAccount.Location) if(!$newStorage) { throw ($this.exceptionMsg + "Failed to create AzSDK compliant Storage Account for output reports storage. Please run command again.") } else { #apply tags $timestamp = $(get-date).ToUniversalTime().ToString("yyyyMMdd_HHmmss") $this.reportStorageTags += @{ "AzSDKFeature" = "ContinuousAssuranceStorage"; "CreationTime"=$timestamp; "LastModified"=$timestamp } Set-AzureRmStorageAccount -ResourceGroupName $newStorage.ResourceGroupName -Name $newStorage.StorageAccountName -Tag $this.reportStorageTags -Force -ErrorAction SilentlyContinue } #update storage account variable with new value $varStorageName = [Variable]@{ Name = "ReportsStorageAccountName"; Value = $newStorage.StorageAccountName; IsEncrypted = $false; Description ="Name of Storage Account where output reports will be stored" } $this.UpdateVariable($varStorageName) $this.OutputObject.StorageAccountName = $newStorageName } #endregion #region :update user configurable variables which are present in params if(![string]::IsNullOrWhiteSpace($OMSWorkspaceId)) { $varOmsWSID = [Variable]@{ Name = "OMSWorkspaceId"; Value = $OMSWorkspaceId; IsEncrypted = $false } $this.UpdateVariable($varOmsWSID) $this.PublishCustomMessage("Updating variable ["+$varOmsWSID.Name+"]") } if(![string]::IsNullOrWhiteSpace($OMSSharedKey)) { $varOMSSharedKey = [Variable]@{ Name = "OMSSharedKey"; Value = $OMSSharedKey; IsEncrypted = $true } $this.UpdateVariable($varOMSSharedKey) $this.PublishCustomMessage("Updating variable ["+$varOMSSharedKey.Name+"]") } if(![string]::IsNullOrWhiteSpace($ResourceGroupNames)) { $varAppRG = [Variable]@{ Name = "AppResourceGroupNames"; Value = $ResourceGroupNames; IsEncrypted = $false } $this.UpdateVariable($varAppRG) $this.PublishCustomMessage("Updating variable ["+$varAppRG.Name+"]") } #endregion #region :update runbook & schedule #unlink runbook from existing schedules $scheduledRunbooks = Get-AzureRmAutomationScheduledRunbook -AutomationAccountName $this.AutomationAccount.Name ` -ResourceGroupName $this.AutomationAccount.ResourceGroup | Where-Object {$_.RunbookName -eq $this.RunbookName} if(($scheduledRunbooks|Measure-Object).Count -gt 0) { $scheduledRunbooks | ForEach-Object { Unregister-AzureRmAutomationScheduledRunbook -RunbookName $_.RunbookName -ScheduleName $_.ScheduleName ` -ResourceGroupName $_.ResourceGroupName ` -AutomationAccountName $_.AutomationAccountName -ErrorAction Stop -Force | Out-Null }; } #remove existing and create new runbook $existingRunbook = Get-AzureRmAutomationRunbook -AutomationAccountName $this.AutomationAccount.Name ` -ResourceGroupName $this.AutomationAccount.ResourceGroup if(($existingRunbook|Measure-Object).Count -gt 0) { $existingRunbook | Remove-AzureRmAutomationRunbook -Force -ErrorAction Stop } $this.PublishCustomMessage("Updating runbook - ["+ $this.RunbookName +"]") $this.NewCCRunbooks() #relink existing schedules with runbook $this.PublishCustomMessage("Linking schedule - ["+$this.ScheduleName+"] to the runbook") if(($scheduledRunbooks|Measure-Object).Count -gt 0) { $scheduledRunbooks | ForEach-Object { Register-AzureRmAutomationScheduledRunbook -RunbookName $this.RunbookName -ScheduleName $_.ScheduleName ` -ResourceGroupName $_.ResourceGroupName ` -AutomationAccountName $_.AutomationAccountName -ErrorAction Stop | Out-Null }; } else { #create default schedule $this.NewCCSchedules() } #endregion #region :update last modified and version tag $modifyTimestamp = $(get-date).ToUniversalTime().ToString("yyyyMMdd_HHmmss") if($automationTags.ContainsKey("LastModified")) { $automationTags["LastModified"] = $modifyTimestamp; } else { $automationTags.Add("LastModified",$modifyTimestamp) } if($automationTags.ContainsKey("AzSDKVersion")) { $automationTags["AzSDKVersion"] = $this.GetCurrentModuleVersion(); } else { $automationTags.Add("AzSDKVersion",$this.GetCurrentModuleVersion()) } Set-AzureRmAutomationAccount -ResourceGroupName $this.AutomationAccount.ResourceGroup -Name $this.AutomationAccount.Name -Tags $automationTags -ErrorAction SilentlyContinue #endregion $this.PublishCustomMessage("Completed updating Automation Account for Continuous Assurance") $messages += [MessageData]::new("Below resources/automation account assets are updated in your subscription", $this.OutputObject) return $messages; } [MessageData[]] GetAzSDKContinuousAssurance() { [MessageData[]] $messages = @(); $this.AutomationAccount.ResourceGroup = [ConfigurationManager]::GetAzSdkConfigData().AzSDKRGName #Fetch automation account components $this.OutputObject.AutomationAccount = Get-AzureRmAutomationAccount -Name $this.AutomationAccount.Name -ResourceGroupName $this.AutomationAccount.ResourceGroup | Select-Object AutomationAccountName,Location,Plan,ResourceGroupName,State,Tags if($this.OutputObject.AutomationAccount) { $this.OutputObject.StorageAccount = $this.CheckContinuousAssuranceStorage() | Select-Object ResourceName,ResourceGroupName,Sku,Tags $this.OutputObject.Variables = Get-AzureRmAutomationVariable -AutomationAccountName $this.AutomationAccount.Name -ResourceGroupName $this.AutomationAccount.ResourceGroup | Select-Object Name,Description,Value,Encrypted $this.OutputObject.Runbooks = Get-AzureRmAutomationRunbook -AutomationAccountName $this.AutomationAccount.Name -ResourceGroupName $this.AutomationAccount.ResourceGroup | Select-Object Name,Description,RunbookType,State,JobCount,CreationTime,LastModifiedTime,LastModifiedBy $this.OutputObject.Schedules = Get-AzureRmAutomationSchedule -AutomationAccountName $this.AutomationAccount.Name -ResourceGroupName $this.AutomationAccount.ResourceGroup $this.OutputObject.AzureRunAsConnection = Get-AzureRmAutomationConnection -AutomationAccountName $this.AutomationAccount.Name -Name $this.connectionAssetName -ResourceGroupName $this.AutomationAccount.ResourceGroup | Select-Object Name,Description,ConnectionTypeName $this.OutputObject.AzureRunAsCertificate = Get-AzureRmAutomationCertificate -AutomationAccountName $this.AutomationAccount.Name -Name $this.certificateAssetName -ResourceGroupName $this.AutomationAccount.ResourceGroup | Select-Object Name,Description,CreationTime,ExpiryTime,LastModifiedTime $this.PublishCustomMessage("Below resources/automation account assets are present in subscription as part of Continuous Assurance") $this.PublishCustomMessage("Automation account : $($this.OutputObject.AutomationAccount.AutomationAccountName)") $this.PublishCustomMessage("Reports storage account: $($this.OutputObject.StorageAccount.ResourceName)") $this.PublishCustomMessage("Variable(s): ") $this.OutputObject.Variables | ForEach-Object{ $this.PublishCustomMessage("Name : " + $_.Name) if(!$_.Encrypted) { $this.PublishCustomMessage("Value : " + $_.Value) } else { $this.PublishCustomMessage("Value : The value is encrypted" ) } } $this.PublishCustomMessage("Runbook(s) : ") $this.OutputObject.Runbooks | ForEach-Object{ $this.PublishCustomMessage($_.Name) } $this.PublishCustomMessage("Schedule(s) :") $this.OutputObject.Schedules | ForEach-Object{ $this.PublishCustomMessage($_.Name) } $this.PublishCustomMessage("Connection name : $($this.OutputObject.AzureRunAsConnection.Name)") $this.PublishCustomMessage("Certificate name : $($this.OutputObject.AzureRunAsCertificate.Name)") $messages += [MessageData]::new("Below resources/automation account assets are present in subscription as part of Continuous Assurance", $this.OutputObject) } else { $this.PublishCustomMessage("No Continuous Assurance Automation Account is installed in this subscription") $messages += [MessageData]::new("No Continuous Assurance Automation Account is installed in this subscription") } return $messages } [MessageData[]] RemoveAzSDKContinuousAssurance($DeleteStorageReports) { [MessageData[]] $messages = @(); $messages += [MessageData]::new("This command will delete resources in your subscription which were installed by AzSDK Continuous Assurance") $this.PublishCustomMessage("This command will delete resources in your subscription which were installed by AzSDK Continuous Assurance") $this.AutomationAccount.ResourceGroup = [ConfigurationManager]::GetAzSdkConfigData().AzSDKRGName #Initialize variables for confirmation pop ups $title = "Confirm" $yes = New-Object System.Management.Automation.Host.ChoiceDescription "&Yes", "This means Yes" $no = New-Object System.Management.Automation.Host.ChoiceDescription "&No", "This means No" $options = [System.Management.Automation.Host.ChoiceDescription[]]($yes, $no) #below is hack for removing error due to strict mode - host variable is not assigned in the method $host = $host #filter accounts with old/new name $accounts = Get-AzureRMAutomationAccount -ResourceGroupName $this.AutomationAccount.ResourceGroup -ErrorAction silentlycontinue | where-object{$_.AutomationAccountName -in ($this.AutomationAccount.Name,$this.deprecatedAccountName)} if($accounts) { $accounts | ForEach-Object{ $accountConfirmMsg = "Are you sure you want to delete Continuous Assurance Automation Account '$($_.AutomationAccountName)'" # user confirmation $result = $host.ui.PromptForChoice($title, $accountConfirmMsg, $options, 1) if($result -eq 0) { #user selected yes Remove-AzureRmAutomationAccount -ResourceGroupName $_.ResourceGroupName -name $_.AutomationAccountName -Force -ErrorAction stop $messages += [MessageData]::new("Removed Automation Account [$($_.AutomationAccountName)] from resource group [$($this.AutomationAccount.ResourceGroup)]") $this.PublishCustomMessage("Removed Automation Account [$($_.AutomationAccountName)] from resource group [$($this.AutomationAccount.ResourceGroup)]") } else { #user selected no $messages += [MessageData]::new("You have chosen not to delete Automation Account [$($_.AutomationAccountName)]") $this.PublishCustomMessage("You have chosen not to delete Automation Account [$($_.AutomationAccountName)]") } } } else { #account not found $messages += [MessageData]::new("Continuous Assurance Automation Account doesn't exist in this subscription") $this.PublishCustomMessage("Continuous Assurance Automation Account doesn't exist in this subscription") } #remove storage account container if switch param is present $existingStorage = $this.CheckContinuousAssuranceStorage() if(($existingStorage|Measure-Object).Count -gt 0) { $containerName = "azsdkexecutionlogs" $keys = Get-AzureRmStorageAccountKey -ResourceGroupName $existingStorage.ResourceGroupName -Name $existingStorage.ResourceName $storageContext = New-AzureStorageContext -StorageAccountName $existingStorage.ResourceName -StorageAccountKey $keys[0].Value -Protocol Https $existingContainer = Get-AzureStorageContainer -Name $containerName -Context $storageContext -ErrorAction SilentlyContinue if($existingContainer) { #switch is present if($DeleteStorageReports) { #user confirmation before deleting container $storageConfirmMsg = "Are you sure you want to delete '$containerName' container in Storage Account '$($existingStorage.ResourceName)' which contains security scan logs/reports ?" $result = $host.ui.PromptForChoice($title, $storageConfirmMsg, $options, 1) if($result -eq 0) { #user selected yes $existingContainer | Remove-AzureStorageContainer -Force -ErrorAction SilentlyContinue if((Get-AzureStorageContainer -Name $containerName -Context $storageContext -ErrorAction SilentlyContinue|Measure-Object).Count -eq 0) { #deleted successfully in confirmation box $messages += [MessageData]::new("Removed '$containerName' container from [$($existingStorage.ResourceName)] Storage Account") $this.PublishCustomMessage("Removed '$containerName' container from [$($existingStorage.ResourceName)] Storage Account") } else { #error occured $messages += [MessageData]::new("Error occured while removing container [$containerName] from Storage Account [$($existingStorage.ResourceName)]. Please check your access permissions and try again.") $this.PublishCustomMessage("Error occured while removing container [$containerName] from Storage Account [$($existingStorage.ResourceName)]. Please check your access permissions and try again.") } } #user selected no in confirmation box else { $messages += [MessageData]::new("You have chosen not to delete container [$containerName] from Storage Account [$($existingStorage.ResourceName)]") $this.PublishCustomMessage("You have chosen not to delete container [$containerName] from Storage Account [$($existingStorage.ResourceName)]") } } #switch param is not present else { $this.PublishCustomMessage("You have chosen not to delete container [$containerName] from reports storage account [$($existingStorage.ResourceName)] so it is retained. It can be deleted by passing 'DeleteStorageReports' switch parameter to this function.") $messages += [MessageData]::new("You have chosen not to delete container [$containerName] from reports storage account [$($existingStorage.ResourceName)] so it is retained. It can be deleted by passing 'DeleteStorageReports' switch parameter to this function.") } } #switch is present but container not found elseif($DeleteStorageReports) { $messages += [MessageData]::new("Container [$containerName] not found in [$($existingStorage.ResourceName)] Storage Account") $this.PublishCustomMessage("Container [$containerName] container not found in [$($existingStorage.ResourceName)] Storage Account") } } #switch is present but no storage account found elseif($DeleteStorageReports) { $this.PublishCustomMessage("AzSDK reports storage account doesn't exist in resource group [$($this.AutomationAccount.ResourceGroup)]") $messages += [MessageData]::new("No AzSDK reports storage doesn't account exist in resource group [$($this.AutomationAccount.ResourceGroup)]") } #remove job collection if exists to make compatible with old accounts $jobCollectionName = "AzSDKCCJobCollection" $jobCollection = Get-AzureRmSchedulerJobCollection -ResourceGroupName $this.AutomationAccount.ResourceGroup -JobCollectionName $jobCollectionName -ErrorAction SilentlyContinue if($jobCollection) { #user confirmation $jobcollectionConfirmMsg = "Are you sure you want to delete Scheduler Job Collection '$jobCollectionName'?" $result = $host.ui.PromptForChoice($title, $jobcollectionConfirmMsg, $options, 1) if($result -eq 0) { #user selected yes $jobCollection | Remove-AzureRmSchedulerJobCollection -ErrorAction SilentlyContinue | Out-Null if((Find-AzureRmResource -ResourceNameEquals $jobCollectionName -ResourceGroupNameEquals $this.AutomationAccount.ResourceGroup -ResourceType "Microsoft.Scheduler/jobCollections"|Measure-Object).Count -eq 0) { $messages += [MessageData]::new("Removed Scheduler Job Collection [$jobCollectionName] from resource group [$($this.AutomationAccount.ResourceGroup)]") $this.PublishCustomMessage("Removed Scheduler Job Collection [$jobCollectionName] from resource group [$($this.AutomationAccount.ResourceGroup)]") } else { #error occured $messages += [MessageData]::new("Error occured while removing [$jobCollectionName)] Scheduler Job Collection from resource group [$($this.AutomationAccount.ResourceGroup)]. Please check your access permissions and try again.") $this.PublishCustomMessage("Error occured while removing [$jobCollectionName] Scheduler Job Collection from resource group [$($this.AutomationAccount.ResourceGroup)]. Please check your access permissions and try again.") } } else { $messages += [MessageData]::new("You have chosen not to delete Scheduler Job Collection [$jobCollectionName]") $this.PublishCustomMessage("You have chosen not to delete Scheduler Job Collection [$jobCollectionName]") } } return $messages } #region: Internal functions for install account hidden [void] DeleteResourceGroup($resourceGroupName) { if((Get-AzureRmResourceGroup -Name $resourceGroupName -ErrorAction SilentlyContinue | Measure-Object).Count -gt 0) { Remove-AzureRmResourceGroup -Name $resourceGroupName -Force -ErrorAction Stop | Out-Null } } hidden [void] NewCCResourceGroup() { $this.AutomationAccount.RGTags += @{ "AzSDKFeature" = "ContinuousAssurance"; "AzSDKVersion"=$this.GetCurrentModuleVersion(); "CreationTime"=$(get-date).ToUniversalTime().ToString("yyyyMMdd_HHmmss"); } $newRG = New-AzureRmResourceGroup -Name $this.AutomationAccount.ResourceGroup -Location $this.AutomationAccount.Location ` -Tag $this.AutomationAccount.RGTags ` -ErrorAction Stop $this.OutputObject.ResourceGroup = $newRG | Select-Object ResourceGroupName,Location } hidden [void] DeployCCAutomationAccountItems() { #Adding below to make schedule available for adding in runbook config $ScanSchedule = [RunbookSchedule]@{ Name = $this.ScheduleName; Frequency = [ScheduleFrequency]::Day; Interval = 1; Description = "Scheduling job to scan subscription and app resource groups"; StartTime = ([System.DateTime]::Now.AddMinutes(10).ToString("yyyy-MM-dd'T'HH:mm:sszzz")); LinkedRubooks = @($this.RunbookName); Key = "Scan_Schedule" } $this.RunbookSchedules += @($ScanSchedule) $this.PublishCustomMessage("Creating runbook - ["+ $this.RunbookName +"]") $this.NewCCRunbooks() $this.PublishCustomMessage("Linking schedule - ["+$this.ScheduleName+"] to the runbook") $this.NewCCSchedules() $this.PublishCustomMessage("Creating variables") $this.NewCCVariables() } hidden [void] NewEmptyAutomationAccount() { #Add tags $timestamp = $(get-date).ToUniversalTime().ToString("yyyyMMdd_HHmmss") $this.AutomationAccount.AccountTags += @{ "AzSDKFeature" = "ContinuousAssurance"; "AzSDKVersion"=$this.GetCurrentModuleVersion(); "CreationTime"=$timestamp; "LastModified"=$timestamp } $this.OutputObject.AutomationAccount = New-AzureRmAutomationAccount -ResourceGroupName $this.AutomationAccount.ResourceGroup ` -Name $this.AutomationAccount.Name -Location $this.AutomationAccount.Location ` -Plan Basic -Tags $this.AutomationAccount.AccountTags -ErrorAction Stop | Select-Object AutomationAccountName,Location,Plan,ResourceGroupName,State,Tags } hidden [void] NewCCRunbooks() { $CCRunbook = [Runbook]@{ Name = $this.RunbookName; Type = "PowerShell"; Description = "This runbook is responsible for running SVT and SS-Health commands and keep all modules updated"; LogProgress = $false; LogVerbose = $false; Key="Continuous_Assurance_Runbook" } $this.Runbooks += @($CCRunbook) $this.Runbooks | ForEach-Object{ $filePath = $this.AddConfigValues($_.Name+".ps1"); Import-AzureRmAutomationRunbook -Name $_.Name -Description $_.Description -Type $_.Type ` -Path $filePath ` -LogProgress $_.LogProgress -LogVerbose $_.LogVerbose ` -AutomationAccountName $this.AutomationAccount.Name ` -ResourceGroupName $this.AutomationAccount.ResourceGroup -Published -ErrorAction Stop #cleanup Remove-Item -Path $filePath -Force } $this.OutputObject.Runbooks = $this.Runbooks | Select-Object Name,Description,Type } hidden [void] NewCCSchedules() { if($this.RunbookSchedules.count -eq 0) { $ScanSchedule = [RunbookSchedule]@{ Name = $this.ScheduleName; Frequency = [ScheduleFrequency]::Day; Interval = 1; Description = "Scheduling job to scan subscription and app resource groups"; StartTime = ([System.DateTime]::Now.AddMinutes(10).ToString("yyyy-MM-dd'T'HH:mm:sszzz")); LinkedRubooks = @($this.RunbookName); Key = "Scan_Schedule" } $this.RunbookSchedules += @($ScanSchedule) } $this.RunbookSchedules | ForEach-Object{ $scheduleName = $_.Name New-AzureRmAutomationSchedule -AutomationAccountName $this.AutomationAccount.Name -Name $_.Name ` -ResourceGroupName $this.AutomationAccount.ResourceGroup -StartTime $_.StartTime ` -Description $_.Description -DayInterval $_.Interval -ErrorAction Stop $_.LinkedRubooks | ForEach-Object{ Register-AzureRmAutomationScheduledRunbook -RunbookName $_ -ScheduleName $scheduleName ` -ResourceGroupName $this.AutomationAccount.ResourceGroup ` -AutomationAccountName $this.AutomationAccount.Name -ErrorAction Stop } } $this.OutputObject.Schedules = $this.RunbookSchedules } hidden [void] NewCCVariables() { $varAppRG = [Variable]@{ Name = "AppResourceGroupNames"; Value = $this.UserConfig.ResourceGroupNames; IsEncrypted = $false; Description ="Comma separated values of the different resource groups that has to be scanned" } $varOmsWSID = [Variable]@{ Name = "OMSWorkspaceId"; Value = $this.UserConfig.OMSCredential.OMSWorkspaceId; IsEncrypted = $false; Description ="OMS Workspace Id" } $varOmsWSKey = [Variable]@{ Name = "OMSSharedKey"; Value = $this.UserConfig.OMSCredential.OMSSharedKey; IsEncrypted = $true; Description ="OMS Workspace Shared Key" } $varStorageName = [Variable]@{ Name = "ReportsStorageAccountName"; Value = $this.UserConfig.StorageAccountName; IsEncrypted = $false; Description ="Name of storage account where output reports will be stored" } $this.Variables += @($varAppRG,$varOmsWSID,$varOmsWSKey,$varStorageName) $this.Variables|ForEach-Object{ New-AzureRmAutomationVariable -Name $_.Name -Encrypted $_.IsEncrypted ` -Description $_.Description -Value $_.Value ` -ResourceGroupName $this.AutomationAccount.ResourceGroup ` -AutomationAccountName $this.AutomationAccount.Name -ErrorAction Stop $this.PublishCustomMessage("Name : "+$_.Name) } $this.OutputObject.Variables = $this.Variables | Select-Object Name,Description } hidden [void] NewCCAzureRunAsAccount() { $pfxFilePath = $null $thumbPrint = $null $ADApplication = $null try { $ADApplication = Get-AzureRmADApplication -DisplayNameStartWith $this.AutomationAccount.AzureADAppName | Where-Object -Property DisplayName -eq $this.AutomationAccount.AzureADAppName if($ADApplication) { $this.PublishCustomMessage("Found azure active directory application - ["+ $this.AutomationAccount.AzureADAppName +"]") #set this flag to identify whether clean up AD App is needed in case of exception $this.isExistingADApp = $true } else { $this.PublishCustomMessage("Creating new azure active directory application - ["+ $this.AutomationAccount.AzureADAppName +"]") #create new AD App $ADApplication = New-AzureRmADApplication -DisplayName $this.AutomationAccount.AzureADAppName ` -HomePage ("https://" + $this.AutomationAccount.AzureADAppName) ` -IdentifierUris ("https://" + $this.AutomationAccount.AzureADAppName) -ErrorAction Stop #create new SP $this.PublishCustomMessage("Creating new service principal") New-AzureRMADServicePrincipal -ApplicationId $ADApplication.ApplicationId -ErrorAction Stop | Out-Null } $selfsignedCertificate = [ActiveDirectoryHelper]::NewSelfSignedCertificate($this.AutomationAccount.AzureADAppName,$this.certificateDetail.CertStartDate,$this.certificateDetail.CertEndDate,$this.certificateDetail.Provider) #create password $secureCertPassword = [Helpers]::NewSecurePassword() $pfxFilePath = $env:TEMP+ "\temp.pfx" Export-PfxCertificate -Cert $selfsignedCertificate -Password $secureCertPassword -FilePath $pfxFilePath | Out-Null $publicCert = New-Object System.Security.Cryptography.X509Certificates.X509Certificate2(,$selfsignedCertificate.GetRawCertData()) #Authenticating AAD App service principal with newly created certificate credential [ActiveDirectoryHelper]::UpdateADAppCredential($ADApplication.ApplicationId,$publicCert,$this.certificateDetail.CredStartDate,$this.certificateDetail.CredEndDate,"False") $this.PublishCustomMessage("Adding service principal to Reader RBAC role at subscription level and Contributor RBAC role at "+ $this.AutomationAccount.ResourceGroup +" resource group level") $NewSPNRole = $null $RetryCount = 0; While ($null -eq $NewSPNRole -and $RetryCount -le 6) { #Assign RBAC to SPN - contributor at RG and reader at subscription level Start-Sleep 10 New-AzureRMRoleAssignment -RoleDefinitionName Reader -ServicePrincipalName $ADApplication.ApplicationId -ErrorAction SilentlyContinue | Out-Null New-AzureRMRoleAssignment -Scope (Get-AzureRmResourceGroup -Name $this.AutomationAccount.ResourceGroup -ErrorAction Stop).ResourceId -RoleDefinitionName Contributor -ServicePrincipalName $ADApplication.ApplicationId -ErrorAction SilentlyContinue | Out-Null $NewSPNRole = Get-AzureRMRoleAssignment -ServicePrincipalName $ADApplication.ApplicationId -ErrorAction SilentlyContinue $RetryCount++; } $thumbPrint = $publicCert.thumbPrint.ToString() #create certificate asset $this.PublishCustomMessage("Adding certificate - ["+ $this.certificateAssetName +"] and connection - ["+ $this.connectionAssetName +"] in Automation Account") $newCertificateAsset = $this.NewCCCertificate($pfxFilePath,$secureCertPassword) # Create a Automation connection asset. This connection uses the service principal. $newConnectionAsset = $this.NewCCConnection($ADApplication.ApplicationId,$thumbPrint) $this.OutputObject.AzureADAppName = $this.AutomationAccount.AzureADAppName $this.OutputObject.AzureRunAsConnection = $newConnectionAsset | Select-Object Name,Description,ConnectionTypeName } finally { #cleanup pfx file if($pfxFilePath) { Remove-Item -Path $pfxFilePath -Force -ErrorAction SilentlyContinue } #cleanup certificate $CertStore = New-Object System.Security.Cryptography.X509Certificates.X509Store([System.Security.Cryptography.X509Certificates.StoreName]::My,[System.Security.Cryptography.X509Certificates.StoreLocation]::CurrentUser) $CertStore.Open([System.Security.Cryptography.X509Certificates.OpenFlags]::ReadWrite) if($thumbPrint) { $tempCert = $CertStore.Certificates.Find("FindByThumbprint",$thumbPrint,$FALSE) if($tempCert) { $CertStore.Remove($tempCert[0]) } } } } hidden [string] AddConfigValues([string]$fileName) { $outputFilePath = "$Env:LOCALAPPDATA\$fileName"; $ccRunbook = $this.LoadServerConfigFile($fileName) #append escape character (`) before '$' symbol $policyStoreUrl = [ConfigurationManager]::GetAzSdkSettings().OnlinePolicyStoreUrl.Replace('$',"``$") $ccRunbook | Foreach-Object { $temp1 = $_ -replace "\[#SubscriptionID#\]",$this.SubscriptionContext.SubscriptionId; $temp2 = $temp1 -replace "\[#AutomationAccountRG#\]",$this.AutomationAccount.ResourceGroup; $temp3 = $temp2 -replace "\[#AutomationAccountName#\]",$this.AutomationAccount.Name; $temp4 = $temp3 -replace "\[#RunbookName#\]",($this.Runbooks|Where-Object{$_.Key -eq "Continuous_Assurance_Runbook"}|Select-Object -ExpandProperty Name); $temp5 = $temp4 -replace "\[#ScanScheduleName#\]",($this.RunbookSchedules|Where-Object{$_.Key -eq "Scan_Schedule"}|Select-Object -ExpandProperty Name); $temp6 = $temp5 -replace "\[#UseOnlinePolicyStore#\]",$this.ConvertBooleanToString([ConfigurationManager]::GetAzSdkSettings().UseOnlinePolicyStore); $temp7 = $temp6 -replace "\[#OnlinePolicyStoreUrl#\]",$policyStoreUrl; $temp8 = $temp7 -replace "\[#EnableAADAuthForOnlinePolicyStore#\]",$this.ConvertBooleanToString([ConfigurationManager]::GetAzSdkSettings().EnableAADAuthForOnlinePolicyStore); $temp8 -replace "\[#ModuleName#\]",$this.GetModuleName(); } | Out-File $outputFilePath return $outputFilePath } hidden [string] ConvertBooleanToString($boolvalue) { switch($boolvalue) { "true"{ return "true" } "false"{ return "false"} } return "false" #adding this to prevent error all path doesn't return value" } #endregion #region: Internal functions for update account hidden [void] UpdateVariable($VariableObj) { $updatedVariable = Set-AzureRmAutomationVariable -Name $VariableObj.Name ` -Encrypted $VariableObj.IsEncrypted ` -Value $VariableObj.Value ` -ResourceGroupName $this.AutomationAccount.ResourceGroup ` -AutomationAccountName $this.AutomationAccount.Name -ErrorAction Stop $this.OutputObject.Variables += ($updatedVariable | Select-Object Name,Description,Value) } hidden [void] RemoveCCAzureRunAsAccount() { #remove existing azurerunasconnection if((Get-AzureRmAutomationConnection -Name $this.connectionAssetName -ResourceGroupName $this.AutomationAccount.ResourceGroup ` -AutomationAccountName $this.AutomationAccount.Name -ErrorAction SilentlyContinue|Measure-Object).Count -gt 0) { Remove-AzureRmAutomationConnection -ResourceGroupName $this.AutomationAccount.ResourceGroup` -AutomationAccountName $this.AutomationAccount.Name -Name $this.connectionAssetName -Force -ErrorAction stop } } hidden [void] RemoveCCAzureRunAsCertificate() { #remove existing certificate $isCertPresent = Get-AzureRmAutomationCertificate -ResourceGroupName $this.AutomationAccount.ResourceGroup ` -AutomationAccountName $this.AutomationAccount.Name -Name $this.certificateAssetName -ErrorAction SilentlyContinue if($isCertPresent) { Remove-AzureRmAutomationCertificate -ResourceGroupName $this.AutomationAccount.ResourceGroup ` -AutomationAccountName $this.AutomationAccount.Name -Name $this.certificateAssetName -ErrorAction SilentlyContinue } } hidden [void] UpdateCCAzureRunAsAccount() { $pfxFilePath = $null $thumbPrint = $null try { #fetch existing AD App used in connection $connection = Get-AzureRmAutomationConnection -AutomationAccountName $this.AutomationAccount.Name ` -ResourceGroupName $this.AutomationAccount.ResourceGroup -Name $this.connectionAssetName -ErrorAction Stop $appID = $connection.FieldDefinitionValues.ApplicationId $this.AutomationAccount.AzureADAppName = (Get-AzureRmADApplication -ApplicationId $connection.FieldDefinitionValues.ApplicationId -ErrorAction stop).DisplayName #create new self-signed certificate $selfsignedCertificate = [ActiveDirectoryHelper]::NewSelfSignedCertificate($this.AutomationAccount.AzureADAppName,$this.certificateDetail.CertStartDate,$this.certificateDetail.CertEndDate,$this.certificateDetail.Provider) #create password $secureCertPassword = [Helpers]::NewSecurePassword() $pfxFilePath = $env:TEMP+ "\temp.pfx" Export-PfxCertificate -Cert $selfsignedCertificate -Password $secureCertPassword -FilePath $pfxFilePath | Out-Null $publicCert = New-Object System.Security.Cryptography.X509Certificates.X509Certificate2(,$selfsignedCertificate.GetRawCertData()) #Authenticating AAD App service principal with newly created certificate credential [ActiveDirectoryHelper]::UpdateADAppCredential($appID,$publicCert,$this.certificateDetail.CredStartDate,$this.certificateDetail.CredEndDate,"False") $thumbPrint = $publicCert.thumbPrint #create certificate asset $newCertificateAsset = $this.NewCCCertificate($pfxFilePath,$secureCertPassword) # Remove existing connection $this.RemoveCCAzureRunAsAccount() # Create a Automation connection asset named AzureRunAsConnection in the Automation account. This connection uses the updated service principal. $newConnectionAsset = $this.NewCCConnection($appID,$thumbPrint) $this.OutputObject.AzureADAppName = $this.AutomationAccount.AzureADAppName $this.OutputObject.AzureRunAsConnection = $newConnectionAsset | Select-Object Name,Description,ConnectionTypeName $this.OutputObject.AzureRunAsCertificate = $newCertificateAsset | Select-Object Name,Description,CreationTime,ExpiryTime,LastModifiedTime } finally { #cleanup pfx file if($pfxFilePath) { Remove-Item -Path $pfxFilePath -Force -ErrorAction SilentlyContinue } #cleanup certificate $CertStore = New-Object System.Security.Cryptography.X509Certificates.X509Store([System.Security.Cryptography.X509Certificates.StoreName]::My,[System.Security.Cryptography.X509Certificates.StoreLocation]::CurrentUser) $CertStore.Open([System.Security.Cryptography.X509Certificates.OpenFlags]::ReadWrite) if($thumbPrint) { $tempCert = $CertStore.Certificates.Find("FindByThumbprint",$thumbPrint,$FALSE) if($tempCert) { $CertStore.Remove($tempCert[0]) } } } } hidden [PSObject] NewCCConnection($appId,$thumbPrint) { $tenantID = (Get-AzureRmSubscription -SubscriptionId $this.SubscriptionContext.SubscriptionId -ErrorAction Stop).TenantId $ConnectionFieldValues = @{"ApplicationId" = $appID; "TenantId" = $tenantID; "CertificateThumbprint" = $thumbPrint; "SubscriptionId" = $this.SubscriptionContext.SubscriptionId} $newConnectionAsset = New-AzureRmAutomationConnection -ResourceGroupName $this.AutomationAccount.ResourceGroup ` -AutomationAccountName $this.AutomationAccount.Name -Name $this.connectionAssetName -ConnectionTypeName AzureServicePrincipal ` -ConnectionFieldValues $ConnectionFieldValues -Description "This connection authenticates runbook with service principal" -ErrorAction stop return $newConnectionAsset } hidden [PSObject] NewCCCertificate($pfxFilePath,$secureCertPassword) { $newCertificateAsset = New-AzureRmAutomationCertificate -ResourceGroupName $this.AutomationAccount.ResourceGroup -AutomationAccountName $this.AutomationAccount.Name ` -Path $pfxFilePath -Name $this.certificateAssetName -Password $secureCertPassword -Exportable -ErrorAction Stop return $newCertificateAsset } #endregion #region: Common internal functions hidden [PSObject] CheckContinuousAssuranceStorage() { #check if tags exist $existingStorage = Find-AzureRmResource -TagName "AzSDKFeature" -TagValue "ContinuousAssuranceStorage" -ExpandProperties| Where-Object {$_.ResourceType -eq "Microsoft.Storage/storageAccounts" -and $_.ResourceGroupName -eq $this.AutomationAccount.ResourceGroup} if(($existingStorage|Measure-Object).Count -eq 0) { #check from name $existingStorage = Find-AzureRmResource -ResourceGroupNameEquals $this.AutomationAccount.ResourceGroup -ResourceNameContains "azsdk" -ResourceType "Microsoft.Storage/storageAccounts" } if(($existingStorage|Measure-Object).Count -gt 1) { throw("Multiple storage accounts found in resource group [$($this.AutomationAccount.ResourceGroup)]. This is not expected."+ " Please backup the required logs/reports from storage. Delete resource group [$($this.AutomationAccount.ResourceGroup)] and install latest version using '"+$this.installCommandName+"' command with required parameters.") } return $existingStorage } #endregion }
PowerShellCorpus/PowerShellGallery/AzSDKPreview/2.2.0/Framework/Core/SubscriptionSecurity/ARMPolicy.ps1
ARMPolicy.ps1
using namespace System.Management.Automation Set-StrictMode -Version Latest # Class to implement Subscription ARM Policy controls class ARMPolicy: CommandBase { hidden [PSObject[]] $Policy = $null; hidden [PSObject[]] $ApplicableARMPolicies = $null; #hidden [PSObject[]] $PolicyAssignments = $null; ARMPolicy([string] $subscriptionId, [InvocationInfo] $invocationContext, [string] $tags): Base($subscriptionId, $invocationContext) { $this.Policy = [array] $this.LoadServerConfigFile("Subscription.ARMPolicies.json"); $this.FilterTags = $this.ConvertToStringArray($tags) | Select-Object -Unique; } hidden [PSObject[]] GetApplicableARMPolices() { if($null -eq $this.ApplicableARMPolicies) { $this.ApplicableARMPolicies = @(); $subscriptionId = $this.SubscriptionContext.SubscriptionId; if(($this.FilterTags | Measure-Object).Count -ne 0) { $this.Policy | ForEach-Object { $currentItem = $_; if(($currentItem.Tags | Where-Object { $this.FilterTags.Contains($_) } | Measure-Object).Count -ne 0) { # Resolve the value of SubscriptionId $currentItem.Scope = $global:ExecutionContext.InvokeCommand.ExpandString($currentItem.Scope); if([string]::IsNullOrWhiteSpace($currentItem.Scope)) { $currentItem.Scope = "/subscriptions/$subscriptionId" } $this.ApplicableARMPolicies += $currentItem; } } } } return $this.ApplicableARMPolicies; } [MessageData[]] SetARMPolicy() { [MessageData[]] $messages = @(); if(($this.Policy | Measure-Object).Count -ne 0) { if($this.GetApplicableARMPolices() -ne 0) { $startMessage = [MessageData]::new("Processing ARM policies. Tags:[$([string]::Join(",", $this.FilterTags))]. Total policies: $($this.GetApplicableARMPolices().Count)"); $messages += $startMessage; $this.PublishCustomMessage($startMessage); $this.PublishCustomMessage("Note: Configuring ARM policies can take few minutes depending on number of policies to be processed...", [MessageType]::Warning); $disabledPolicies = $this.GetApplicableARMPolices() | Where-Object { -not $_.Enabled }; if(($disabledPolicies | Measure-Object).Count -ne 0) { $disabledMessage = "Found ARM policies which are disabled. Total disabled policies: $($disabledPolicies.Count)"; $messages += [MessageData]::new($disabledMessage, $disabledPolicies); $this.PublishCustomMessage($disabledMessage, [MessageType]::Warning); } $enabledPolicies = @(); $enabledPolicies += $this.GetApplicableARMPolices() | Where-Object { $_.Enabled }; if($enabledPolicies.Count -ne 0) { $messages += [MessageData]::new([Constants]::SingleDashLine + "`r`nAdding following ARM policies to the subscription. Total policies: $($enabledPolicies.Count)", $enabledPolicies); $errorCount = 0; $currentCount = 0; $enabledPolicies | ForEach-Object { $policyName = $_.PolicyDefinitionName; $currentCount += 1; # Add ARM policy try { $armPolicy = New-AzureRmPolicyDefinition -Name $_.PolicyDefinitionName -Description $_.Description -Policy ([string]$_.PolicyDefinition) -ErrorAction Stop Start-Sleep -Seconds 10 New-AzureRmPolicyAssignment -Name $_.PolicyDefinitionName -PolicyDefinition $armPolicy -Scope $_.Scope -ErrorAction Stop | Out-Null } catch { $messages += [MessageData]::new("Error while adding ARM policy [$policyName] to the subscription", $_, [MessageType]::Error); $errorCount += 1; } $this.CommandProgress($enabledPolicies.Count, $currentCount, 5); }; [MessageData[]] $resultMessages = @(); if($errorCount -eq 0) { $resultMessages += [MessageData]::new("All ARM policies have been added to the subscription successfully`r`n" + [Constants]::SingleDashLine, [MessageType]::Update); } elseif($errorCount -eq $enabledPolicies.Count) { $resultMessages += [MessageData]::new("No ARM policies have been added to the subscription due to error occured. Please add the ARM policies manually.`r`n" + [Constants]::SingleDashLine, [MessageType]::Error); } else { $resultMessages += [MessageData]::new("[$errorCount] ARM policies have not been added to the subscription. Please add the ARM policies manually.", [MessageType]::Error); $resultMessages += [MessageData]::new("[$($enabledPolicies.Count - $errorCount)] ARM policies have been added to the subscription successfully`r`n" + [Constants]::SingleDashLine, [MessageType]::Update); } $messages += $resultMessages; $this.PublishCustomMessage($resultMessages); } } else { $this.PublishCustomMessage("No ARM policies have been found that matches the specified tags. Tags:[$([string]::Join(",", $this.FilterTags))].", [MessageType]::Warning); } } else { $this.PublishCustomMessage("No ARM policies found in the ARM policy file", [MessageType]::Warning); } return $messages; } [MessageData[]] RemoveARMPolicy() { [MessageData[]] $messages = @(); if(($this.Policy | Measure-Object).Count -ne 0) { if($this.GetApplicableARMPolices() -ne 0) { $startMessage += [MessageData]::new("Processing ARM policies. Tags:[$([string]::Join(",", $this.FilterTags))]. Total policies: $($this.GetApplicableARMPolices().Count)"); $messages += $startMessage; $this.PublishCustomMessage($startMessage); $this.PublishCustomMessage("Note: Removing ARM policies can take few minutes depending on number of policies to be processed...", [MessageType]::Warning); $disabledPolicies = $this.GetApplicableARMPolices() | Where-Object { -not $_.Enabled }; if(($disabledPolicies | Measure-Object).Count -ne 0) { $disabledMessage = "Found ARM policies which are disabled and will not be removed. Total disabled policies: $($disabledPolicies.Count)"; $messages += [MessageData]::new($disabledMessage, $disabledPolicies); $this.PublishCustomMessage($disabledMessage, [MessageType]::Warning); } $enabledPolicies = @(); $enabledPolicies += $this.GetApplicableARMPolices() | Where-Object { $_.Enabled }; if($enabledPolicies.Count -ne 0) { $messages += [MessageData]::new([Constants]::SingleDashLine + "`r`nRemoving following ARM policies from the subscription. Total policies: $($enabledPolicies.Count)", $enabledPolicies); $errorCount = 0; $currentCount = 0; $enabledPolicies | ForEach-Object { $policyName = $_.PolicyDefinitionName; $currentCount += 1; # Remove ARM policy try { Remove-AzureRmPolicyAssignment -Name $_.PolicyDefinitionName -Scope $_.Scope -ErrorAction Stop | Out-Null Start-Sleep -Seconds 10 Remove-AzureRmPolicyDefinition -Name $_.PolicyDefinitionName -Force -ErrorAction Stop | Out-Null } catch { $messages += [MessageData]::new("Error while removing ARM policy [$policyName] from the subscription", $_, [MessageType]::Error); $errorCount += 1; } $this.CommandProgress($enabledPolicies.Count, $currentCount, 5); }; [MessageData[]] $resultMessages = @(); if($errorCount -eq 0) { $resultMessages += [MessageData]::new("All ARM policies have been removed from the subscription successfully`r`n" + [Constants]::SingleDashLine, [MessageType]::Update); } elseif($errorCount -eq $enabledPolicies.Count) { $resultMessages += [MessageData]::new("No ARM policies have been removed from the subscription due to error occured. Please remove the ARM policies manually.`r`n" + [Constants]::SingleDashLine, [MessageType]::Error); } else { $resultMessages += [MessageData]::new("[$errorCount] ARM policies have not been removed from the subscription. Please remove the ARM policies manually.", [MessageType]::Error); $resultMessages += [MessageData]::new("[$($enabledPolicies.Count - $errorCount)] ARM policies have been removed from the subscription successfully`r`n" + [Constants]::SingleDashLine, [MessageType]::Update); } $messages += $resultMessages; $this.PublishCustomMessage($resultMessages); } } else { $this.PublishCustomMessage("No ARM policies have been found that matches the specified tags. Tags:[$([string]::Join(",", $this.FilterTags))].", [MessageType]::Warning); } } else { $this.PublishCustomMessage("No ARM policies found in the ARM policy file", [MessageType]::Warning); } return $messages; } }
PowerShellCorpus/PowerShellGallery/AzSDKPreview/2.2.0/Framework/Core/SubscriptionSecurity/SecurityCenterStatus.ps1
SecurityCenterStatus.ps1
using namespace System.Management.Automation Set-StrictMode -Version Latest # The class serves as an intermediate class to call SecurityCenter class # SecurityCenter class is being used in SubscriptionCore class SecurityCenterStatus: CommandBase { SecurityCenterStatus([string] $subscriptionId, [InvocationInfo] $invocationContext): Base($subscriptionId, $invocationContext) { } [string] SetPolicies([string] $securityContactEmails, [string] $securityPhoneNumber) { $secCenter = [SecurityCenter]::new($this.SubscriptionContext.SubscriptionId); if ($secCenter) { return $this.InvokeFunction($secCenter.SetPolicies, @($securityContactEmails, $securityPhoneNumber)); } return ""; } }
PowerShellCorpus/PowerShellGallery/AzSDKPreview/2.2.0/Framework/Core/SubscriptionSecurity/Alerts.ps1
Alerts.ps1
using namespace System.Management.Automation Set-StrictMode -Version Latest # Class to implement Subscription alert controls class Alerts: CommandBase { hidden [PSObject[]] $Policy = $null; hidden [PSObject[]] $ApplicableAlerts = $null; hidden [string] $TargetResourceGroup; hidden [string] $ResourceGroup = "AzSDKAlertsRG"; hidden [string] $ResourceGroupLocation = "East US"; Alerts([string] $subscriptionId, [InvocationInfo] $invocationContext, [string] $tags): Base($subscriptionId, $invocationContext) { $this.Policy = [array] $this.LoadServerConfigFile("Subscription.InsAlerts.json"); $this.FilterTags = $this.ConvertToStringArray($tags) | Select-Object -Unique; } hidden [PSObject[]] GetApplicableAlerts([string[]] $alertNames) { if($null -eq $this.ApplicableAlerts) { $this.ApplicableAlerts = @(); if($alertNames -and $alertNames.Count -ne 0) { $this.ApplicableAlerts += $this.Policy | Where-Object { $alertNames.Contains($_.Name) }; } elseif(($this.FilterTags | Measure-Object).Count -ne 0) { $this.Policy | ForEach-Object { $currentItem = $_; if(($currentItem.Tags | Where-Object { $this.FilterTags.Contains($_) } | Measure-Object).Count -ne 0) { $this.ApplicableAlerts += $currentItem; } } } } return $this.ApplicableAlerts; } hidden [PSObject[]] GetApplicableAlerts() { return $this.GetApplicableAlerts(@()); } [MessageData[]] SetAlerts([string] $targetResourceGroup, [string] $securityContactEmails, [string] $alertResourceGroupLocation) { # Parameter validation if([string]::IsNullOrWhiteSpace($securityContactEmails)) { throw [System.ArgumentException] ("The argument 'securityContactEmails' is null or empty"); } $allEmails = @(); $allEmails += $this.ConvertToStringArray($securityContactEmails); if($allEmails.Count -eq 0) { throw [System.ArgumentException] ("Please provide valid email address(es)"); } if(-not [string]::IsNullOrWhiteSpace($alertResourceGroupLocation)) { $this.ResourceGroupLocation = $alertResourceGroupLocation; } [MessageData[]] $messages = @(); if(($this.Policy | Measure-Object).Count -ne 0) { if($this.GetApplicableAlerts() -ne 0) { $startMessage = [MessageData]::new("Processing alerts. Tags:[$([string]::Join(",", $this.FilterTags))]. Total alerts: $($this.GetApplicableAlerts().Count)"); $messages += $startMessage; $this.PublishCustomMessage($startMessage); $this.PublishCustomMessage("Note: Configuring alerts can take about 10-12 minutes depending on number of alerts to be processed...", [MessageType]::Warning); $disabledAlerts = $this.GetApplicableAlerts() | Where-Object { -not $_.Enabled }; if(($disabledAlerts | Measure-Object).Count -ne 0) { $disabledMessage = "Found alerts which are disabled. Total disabled alerts: $($disabledAlerts.Count)"; $messages += [MessageData]::new($disabledMessage, $disabledAlerts); $this.PublishCustomMessage($disabledMessage, [MessageType]::Warning); } $enabledAlerts = @(); $enabledAlerts += $this.GetApplicableAlerts() | Where-Object { $_.Enabled }; if($enabledAlerts.Count -ne 0) { $messages += [MessageData]::new([Constants]::SingleDashLine + "`r`nAdding following alerts to the subscription. Total alerts: $($enabledAlerts.Count)", $enabledAlerts); # Check if Resource Group exists $existingRG = Get-AzureRmResourceGroup -Name $this.ResourceGroup -ErrorAction SilentlyContinue if(-not $existingRG) { New-AzureRmResourceGroup -Name $this.ResourceGroup -Location $this.ResourceGroupLocation -Tag @{ "AzSDKVersion" = $this.GetCurrentModuleVersion(); "CreationTime" = $this.RunIdentifier; "AzSDKFeature" = "Alerts" } -ErrorAction Stop | Out-Null } $messages += [MessageData]::new("All the alerts registered by this script will be placed in a resource group named: $($this.ResourceGroup)"); #Remove Resource Lock on Resource Group if any $messages += $this.RemoveAllResourceGroupLocks(); #Add-OutputLogEvent -OutputLogFilePath $outputLogFilePath -EventData ("A resource lock will be deployed on this resource group to protect from accidental deletion.") -RawOutput $isTargetResourceGroup = -not [string]::IsNullOrWhiteSpace($targetResourceGroup); # Accepting only first email address because of Azure issue in creating Alert rule with multiple emails $emailAction = New-AzureRmAlertRuleEmail -CustomEmails $allEmails[0] $errorCount = 0; $currentCount = 0; $enabledAlerts | ForEach-Object { $alertName = $_.Name; $currentCount += 1; # Add alert try { if($isTargetResourceGroup) { Add-AzureRmLogAlertRule -Name $_.Name -Location $this.ResourceGroupLocation -ResourceGroup $this.ResourceGroup ` -TargetResourceGroup $targetResourceGroup -OperationName $_.OperationName ` -Actions $emailAction -Description $_.Description ` -WarningAction SilentlyContinue } else { Add-AzureRmLogAlertRule -Name $_.Name -Location $this.ResourceGroupLocation -ResourceGroup $this.ResourceGroup ` -OperationName $_.OperationName ` -Actions $emailAction -Description $_.Description ` -WarningAction SilentlyContinue } } catch { $messages += [MessageData]::new("Error while adding alert [$alertName] to the subscription", $_, [MessageType]::Error); $errorCount += 1; } $this.CommandProgress($enabledAlerts.Count, $currentCount, 20); }; [MessageData[]] $resultMessages = @(); if($errorCount -eq 0) { $resultMessages += [MessageData]::new("All alerts have been added to the subscription successfully`r`n" + [Constants]::SingleDashLine, [MessageType]::Update); } elseif($errorCount -eq $enabledAlerts.Count) { $resultMessages += [MessageData]::new("No alerts have been added to the subscription due to error occured. Please add the alerts manually.`r`n" + [Constants]::SingleDashLine, [MessageType]::Error); } else { $resultMessages += [MessageData]::new("[$errorCount] alerts have not been added to the subscription. Please add the alerts manually.", [MessageType]::Error); $resultMessages += [MessageData]::new("[$($enabledAlerts.Count - $errorCount)] alerts have been added to the subscription successfully`r`n" + [Constants]::SingleDashLine, [MessageType]::Update); } $messages += $resultMessages; $this.PublishCustomMessage($resultMessages); # Create the lock $messages += $this.AddResourceGroupLock(); } } else { $this.PublishCustomMessage("No alerts have been found that matches the specified tags. Tags:[$([string]::Join(",", $this.FilterTags))].", [MessageType]::Warning); } } else { $this.PublishCustomMessage("No alerts found in the alert policy file", [MessageType]::Warning); } return $messages; } [MessageData[]] RemoveAlerts([bool] $deleteResourceGroup, [string] $alertNames) { [MessageData[]] $messages = @(); # Check for existence of resource group $existingRG = Get-AzureRmResourceGroup -Name $this.ResourceGroup -ErrorAction SilentlyContinue if($existingRG) { $startMessage = [MessageData]::new("Found AzSDK alerts resource group: $($this.ResourceGroup)"); $messages += $startMessage; $this.PublishCustomMessage($startMessage); # Remove all locks $messages += $this.RemoveAllResourceGroupLocks(); # Check if user wants to remove resource group if($deleteResourceGroup) { $messages += [MessageData]::new("Removing all AzSDK configred alerts by removing resource group: $($this.ResourceGroup)"); # Remove entire RG (containing all alerts). Remove-AzureRmResourceGroup -Name $this.ResourceGroup -Force $resultMessage = [MessageData]::new("All AzSDK configred alerts removed successfully"); $messages += $resultMessage; $this.PublishCustomMessage($resultMessage); } else { $alertNameArray = @(); if(-not [string]::IsNullOrWhiteSpace($alertNames)) { $alertNameArray += $this.ConvertToStringArray($alertNames); if($alertNameArray.Count -eq 0) { throw [System.ArgumentException] ("The argument 'alertNames' is null or empty"); } } # User wants to remove only specific alerts if(($this.Policy | Measure-Object).Count -ne 0) { if($this.GetApplicableAlerts($alertNameArray) -ne 0) { $startMessage = [MessageData]::new("Removing alerts. Tags:[$([string]::Join(",", $this.FilterTags))]. Total alerts: $($this.GetApplicableAlerts($alertNameArray).Count)"); $messages += $startMessage; $this.PublishCustomMessage($startMessage); $this.PublishCustomMessage("Note: Removing alerts can take few minutes depending on number of alerts to be processed...", [MessageType]::Warning); $disabledAlerts = $this.GetApplicableAlerts($alertNameArray) | Where-Object { -not $_.Enabled }; if(($disabledAlerts | Measure-Object).Count -ne 0) { $disabledMessage = "Found alerts which are disabled and will will not be removed. Total disabled alerts: $($disabledAlerts.Count)"; $messages += [MessageData]::new($disabledMessage, $disabledAlerts); $this.PublishCustomMessage($disabledMessage, [MessageType]::Warning); } $enabledAlerts = @(); $enabledAlerts += $this.GetApplicableAlerts($alertNameArray) | Where-Object { $_.Enabled }; if($enabledAlerts.Count -ne 0) { $messages += [MessageData]::new([Constants]::SingleDashLine + "`r`nRemoving following alerts from the subscription. Total alerts: $($enabledAlerts.Count)", $enabledAlerts); $errorCount = 0; $currentCount = 0; $enabledAlerts | ForEach-Object { $alertName = $_.Name; $currentCount += 1; # Remove alert try { Remove-AzureRmAlertRule -ResourceGroup $this.ResourceGroup -Name $alertName -WarningAction SilentlyContinue } catch { $messages += [MessageData]::new("Error while removing alert [$alertName] from the subscription", $_, [MessageType]::Error); $errorCount += 1; } $this.CommandProgress($enabledAlerts.Count, $currentCount, 20); }; [MessageData[]] $resultMessages = @(); if($errorCount -eq 0) { $resultMessages += [MessageData]::new("All alerts have been removed from the subscription successfully`r`n" + [Constants]::SingleDashLine, [MessageType]::Update); } elseif($errorCount -eq $enabledAlerts.Count) { $resultMessages += [MessageData]::new("No alerts have been removed from the subscription due to error occured. Please add the alerts manually.`r`n" + [Constants]::SingleDashLine, [MessageType]::Error); } else { $resultMessages += [MessageData]::new("[$errorCount] alerts have not been removed from the subscription. Please remove the alerts manually.", [MessageType]::Error); $resultMessages += [MessageData]::new("[$($enabledAlerts.Count - $errorCount)] alerts have been removed from the subscription successfully`r`n" + [Constants]::SingleDashLine, [MessageType]::Update); } $messages += $resultMessages; $this.PublishCustomMessage($resultMessages); # Create the lock $messages += $this.AddResourceGroupLock(); } } else { $this.PublishCustomMessage("No alerts have been found that matches the specified tags. Tags:[$([string]::Join(",", $this.FilterTags))].", [MessageType]::Warning); } } else { $this.PublishCustomMessage("No alerts found in the alert policy file", [MessageType]::Warning); } } } else { $this.PublishCustomMessage("No AzSDK configured alerts found in the subscription. Resource group not found: $($this.ResourceGroup)", [MessageType]::Warning); } return $messages; } hidden [MessageData[]] RemoveAllResourceGroupLocks() { $messages = @(); #Remove Resource Lock on Resource Group if any $locks = @(); $locks += Get-AzureRmResourceLock -ResourceGroupName $this.ResourceGroup if($locks.Count -ne 0) { $messages += [MessageData]::new("Removing following existing resource group locks so that alerts can be processed. Total: $($locks.Count)", $locks); $locks | ForEach-Object { Remove-AzureRmResourceLock -LockId $_.LockId -Force | Out-Null } Start-Sleep -Seconds 60 } return $messages; } hidden [MessageData[]] AddResourceGroupLock() { $messages = @(); # Create the lock $lockName = "AzSDKAlertLock"; $lockObject = New-AzureRmResourceLock -ResourceGroupName $this.ResourceGroup -LockName $lockName -LockLevel ReadOnly -LockNotes "Lock created by AzSDK to protect alert objects" -Force $messages += [MessageData]::new("Created ResourceGroup lock to protect the alert objects. Lock name: $lockName", $lockObject); return $messages; } }
PowerShellCorpus/PowerShellGallery/AzSDKPreview/2.2.0/Framework/Core/SubscriptionSecurity/SubscriptionSecurity.ps1
SubscriptionSecurity.ps1
using namespace System.Management.Automation Set-StrictMode -Version Latest # The class serves as an intermediate class to call multiple subscription security module classes class SubscriptionSecurity: CommandBase { [string] $Tags SubscriptionSecurity([string] $subscriptionId, [InvocationInfo] $invocationContext, [string] $tags): Base($subscriptionId, $invocationContext) { $this.Tags = $tags; } [MessageData[]] SetSubscriptionSecurity( # Inputs for Security Center [string] $securityContactEmails, [string] $securityPhoneNumber, # Inputs for Alerts [string] $targetResourceGroup, [string] $alertResourceGroupLocation ) { [MessageData[]] $messages = @(); # Set up Security Center try { $this.PublishCustomMessage([Constants]::DoubleDashLine + "`r`nSetting up Security Center`r`n" + [Constants]::DoubleDashLine); $secCenter = [SecurityCenter]::new($this.SubscriptionContext.SubscriptionId); if ($secCenter) { $messages += $secCenter.SetPolicies($securityContactEmails, $securityPhoneNumber); $this.PublishCustomMessage([Constants]::DoubleDashLine + "`r`nCompleted Security Center configuration`r`n" + [Constants]::DoubleDashLine, [MessageType]::Update); } } catch { $this.CommandError($_); } # Set up RBAC try { $this.PublishCustomMessage([Constants]::DoubleDashLine + "`r`nSetting up subscription RBAC`r`n" + [Constants]::DoubleDashLine); $rbac = [RBAC]::new($this.SubscriptionContext.SubscriptionId, $this.InvocationContext, $this.Tags); if ($rbac) { $messages += $rbac.SetRBACAccounts(); $this.PublishCustomMessage([Constants]::DoubleDashLine + "`r`nCompleted subscription RBAC configuration`r`n" + [Constants]::DoubleDashLine, [MessageType]::Update); } } catch { $this.CommandError($_); } # Set up ARM policies try { $this.PublishCustomMessage([Constants]::DoubleDashLine + "`r`nSetting up ARM policies`r`n" + [Constants]::DoubleDashLine); $armPolicy = [ARMPolicy]::new($this.SubscriptionContext.SubscriptionId, $this.InvocationContext, $this.Tags); if ($armPolicy) { $messages += $armPolicy.SetARMPolicy(); $this.PublishCustomMessage([Constants]::DoubleDashLine + "`r`nCompleted ARM policy configuration`r`n" + [Constants]::DoubleDashLine, [MessageType]::Update); } } catch { $this.CommandError($_); } # Set up Alerts try { $this.PublishCustomMessage([Constants]::DoubleDashLine + "`r`nSetting up Alerts`r`n" + [Constants]::DoubleDashLine); $alert = [Alerts]::new($this.SubscriptionContext.SubscriptionId, $this.InvocationContext, $this.Tags); if ($alert) { $messages += $alert.SetAlerts($targetResourceGroup, $securityContactEmails, $alertResourceGroupLocation); $this.PublishCustomMessage([Constants]::DoubleDashLine + "`r`nCompleted Alerts configuration`r`n" + [Constants]::DoubleDashLine, [MessageType]::Update); } } catch { $this.CommandError($_); } return $messages; } [MessageData[]] RemoveSubscriptionSecurity([bool] $deleteResourceGroup, [string] $alertNames) { [MessageData[]] $messages = @(); # Remove ARM policies try { $this.PublishCustomMessage([Constants]::DoubleDashLine + "`r`nRemoving ARM policies`r`n" + [Constants]::DoubleDashLine); $armPolicy = [ARMPolicy]::new($this.SubscriptionContext.SubscriptionId, $this.InvocationContext, $this.Tags); if ($armPolicy) { $messages += $armPolicy.RemoveARMPolicy(); $this.PublishCustomMessage([Constants]::DoubleDashLine + "`r`nRemoved ARM policies`r`n" + [Constants]::DoubleDashLine, [MessageType]::Update); } } catch { $this.CommandError($_); } # Remove Alerts try { $this.PublishCustomMessage([Constants]::DoubleDashLine + "`r`nRemoving Alerts`r`n" + [Constants]::DoubleDashLine); $alert = [Alerts]::new($this.SubscriptionContext.SubscriptionId, $this.InvocationContext, $this.Tags); if ($alert) { $messages += $alert.RemoveAlerts($deleteResourceGroup, $alertNames); $this.PublishCustomMessage([Constants]::DoubleDashLine + "`r`nRemoved Alerts configuration`r`n" + [Constants]::DoubleDashLine, [MessageType]::Update); } } catch { $this.CommandError($_); } return $messages; } }