Framework/Core/PolicySetup/AzSKStaging-EasyInstaller.ps1

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
# version: 0.2.4

Param(
    [string] $OnlinePolicyStoreUrl = "#PolicyUrl#" ,
    [string] $RepoUrl = "https://dtlgalleryint.cloudapp.net/",
    [string] $RepoName = "AzSKStaging",
    [string] $DocumentationUrl = "http://aka.ms/AzSKOSSDocs",
    [string] $ControlDetailsUrl = "http://aka.ms/AzSKOSSTCP",
    [string] $FAQUrl = "",
    [string] $SupportUrl = ""
)
[string] $ModuleName = "#ModuleName#"
[string] $OrgName = "#OrgName#"
[string] $SupportEmail = "azsksupext@microsoft.com"
[string] $PrerequsitePassed = "Prerequisite Passed";
[string] $PrerequsiteFailed = "Prerequisite Failed";

function WritePrerequsiteMessage([String] $Status, [string] $Message){
    switch ($Status) {
        Passed { 
            Write-Host "$($PrerequsitePassed): $Message" -ForegroundColor Green
        }
        Failed {
            Write-Host "$($PrerequsiteFailed): $Message" -ForegroundColor Red
        }
        Default {
        }
    }
}

function CheckPSVersion {
    $prerequsite = "PowerShell version needs to be 5.0 or above."
    if($PSVersionTable.PSVersion.Major -lt 5){
        WritePrerequsiteMessage Failed "$prerequsite Please update PowerShell version to 5.0. For more details contact us at $SupportEmail" 
        break
    }
    WritePrerequsiteMessage Passed $prerequsite
}

function CheckNugetPackageProvider {
    $minimumRequiredVersion = "2.8.5.208"
    $prerequsite = "PowerShell Nuget PackageProvider version needs to be $minimumRequiredVersion or above."
    $nugetProvider = Get-PackageProvider -Name "Nuget" -ForceBootstrap -ErrorAction SilentlyContinue
    if($null -eq $nugetProvider -or $nugetProvider.Version -lt $minimumRequiredVersion){
        WritePrerequsiteMessage Failed $prerequsite
        try {
            Write-Host "Installing Nuget PackageProvider..." -ForegroundColor Yellow
            Install-PackageProvider "NuGet" -MinimumVersion $minimumRequiredVersion -Force -Scope CurrentUser -ErrorAction Stop
            WritePrerequsiteMessage Passed $prerequsite
        }
        catch {
            Write-Host "Failed to install Nuget PackageProvider. Error:" $_ -ForegroundColor Red
            break
        }
    }else{
        WritePrerequsiteMessage Passed $prerequsite
    }
}

function BootstrapRepo {
    Write-Host "Configuring $ModuleName repository..." -ForegroundColor Yellow
    $installationPolicy = "Trusted"
    $repository = Get-PSRepository -Name $RepoName -ErrorAction SilentlyContinue

    #Remove old repository names and server url different repo name
    if($repository)
    {
        Unregister-PSRepository -Name $RepoName
    }
    $repositoryWithUrl = Get-PSRepository | Where-Object { $_.SourceLocation -eq $RepoUrl } 
    if($repositoryWithUrl)
    {
        Unregister-PSRepository -Name $repositoryWithUrl.Name
    }

    Register-PSRepository -Name $RepoName -SourceLocation $RepoUrl -InstallationPolicy $installationPolicy
    Write-Host "Completed $ModuleName repository configuration." -ForegroundColor Green
}


function BootstrapSetup {
    $setupModuleName = "$ModuleName"
    Write-Host "Checking if a previous version of $ModuleName is present on your machine..." -ForegroundColor Yellow
    $setupModule = Get-Module -Name $setupModuleName -ListAvailable
    $setupLatestModule = (Find-Module -Name $setupModuleName -Repository $RepoName)
    #If module count is greater than 1 then filter module with current active directory
    if($null -ne $setupModule -and ($setupModule|Measure-Object).Count -gt 1  )
    {     
     $CurrentModulePath= (Get-Item -Path ($setupModule | Select-Object -First 1).ModuleBase).Parent.Parent.FullName
     $setupModule = $setupModule |  Where-Object { $_.ModuleBase.Contains($CurrentModulePath)}
    }

    if($null -ne $setupModule -and $null -ne $setupLatestModule -and $setupModule.Version -ge $setupLatestModule.Version )
    {
      Write-Host "Latest version of $ModuleName already exists." -ForegroundColor Green
      return
    }
    elseif($null -ne $setupModule){
        #Module is present

        Write-Host "Found $ModuleName version $($setupModule.Version). Uninstalling it..." -ForegroundColor Yellow
        try {
            $loadedModule = Get-Module -Name $setupModuleName 
            if($loadedModule)
            {
                Write-Host "$setupModuleName version $($loadedModule.Version) is currently loaded in this PS session.`nPlease close this session (and any other active PS sessions) and rerun the setup command in a fresh session."  -ForegroundColor Red
                break
            }
            
            Uninstall-Module -Name $setupModuleName -AllVersions -Force -ErrorAction Stop            
        }
        catch {
            Write-Host "Failed to remove previous version of $ModuleName. Error:" $_ -ForegroundColor Red
            $moduleLocation = $setupModule.ModuleBase.Substring(0, $setupModule.ModuleBase.LastIndexOf($setupModule.Name))
            Write-Host "Tip: Close all the instances of PowerShell (inclues ISE, Visual Studio (PMC), VS Code (Terminal), etc). Remove the folder '$setupModule' at '$moduleLocation' manually."
            break
        }
        Write-Host "Completed uninstallation." -ForegroundColor Green
    }

    if($setupModule -eq $null)
    {
        Write-Host "No previous version found." -ForegroundColor Green
    }
    try
    { 
        Write-Host "Installing $ModuleName version $($setupLatestModule.Version). This may take a few minutes..." -ForegroundColor Yellow
        if((GET-Command Install-Module).Parameters.ContainsKey("AllowClobber"))
        {
            Install-Module $setupModuleName -Scope CurrentUser -Repository $RepoName -AllowClobber -ErrorAction Stop     
        }
        else
        {
            Install-Module $setupModuleName -Scope CurrentUser -Repository $RepoName -Force -ErrorAction Stop     
        }        
        Write-Host "Completed installation." -ForegroundColor Green
    }
    catch
    {
        Write-Host "Failed to install $ModuleName. Error:" $_ -ForegroundColor Red
        
        break
    }
      
}

function BootstrapOrgPolicy{
    try
    {        
        Write-Host "`nConfiguring $OrgName policy... " -ForegroundColor Yellow
        #Check for execution policy settings
        $executionPolicy = Get-ExecutionPolicy -Scope CurrentUser
        if(($executionPolicy -eq [Microsoft.PowerShell.ExecutionPolicy]::Restricted) -or ($executionPolicy -eq [Microsoft.PowerShell.ExecutionPolicy]::Undefined) -or ($executionPolicy -eq [Microsoft.PowerShell.ExecutionPolicy]::AllSigned))
        {
            Write-Host "Currently PowerShell execution policy is set to '$executionPolicy' mode. `n$ModuleName will need policy to be set to 'RemoteSigned'. `nSelect Y to change policy for current user [Y/N]: " -ForegroundColor Yellow -NoNewline
            $executionPolicyAns = Read-Host 

            if($executionPolicyAns.Trim().ToLower() -eq "y")
            {
                Set-ExecutionPolicy -ExecutionPolicy RemoteSigned -Scope CurrentUser -Force
            }
            else {
                Write-Host "Not able to configure $OrgName policy. Please try re-running setup in new PS session or get support on $SupportUrl" -ForegroundColor Red
                break 
            }
        }
        $setupLatestModule = (Find-Module -Name $ModuleName -Repository $RepoName)
        Import-Module $ModuleName -RequiredVersion "$($setupLatestModule.Version)" -Force      
        Set-AzSKPolicySettings -OnlinePolicyStoreUrl $OnlinePolicyStoreUrl -ErrorAction Stop
        Write-Host "Completed $OrgName policy configuration." -ForegroundColor Green
    }
    catch
    {
        Write-Host "Failed to configure $OrgName policy. Error:" $_ -ForegroundColor Red
        if(-not [string]::IsNullOrWhiteSpace($FAQUrl))
        {
            Write-Host "Tip: Refer to the trobleshooting tips at: $DocumentationUrl, $FAQUrl" -ForegroundColor Red
        }
        break

    }
    

}

function BootstrapInstaller {
    BootstrapRepo
    BootstrapSetup
    BootstrapOrgPolicy

    Write-Host "`nThe DevSecOps Kit for Azure is now ready for your use!" -ForegroundColor Green
    Write-Host "`nImportant links:" -ForegroundColor Green;
    Write-Host "`tDocumentation: " -NoNewline -ForegroundColor Green; Write-Host $DocumentationUrl -ForegroundColor Cyan 
    Write-Host "`tControl details: " -NoNewline -ForegroundColor Green; Write-Host $ControlDetailsUrl -ForegroundColor Cyan
    if(-not [string]::IsNullOrWhiteSpace($FAQUrl))
    {
        Write-Host "`tFAQs: " -NoNewline -ForegroundColor Green; Write-Host $FAQUrl -ForegroundColor Cyan 
    }

    if(-not [string]::IsNullOrWhiteSpace($SupportUrl))
    {
        Write-Host "`tSupport: " -NoNewline -ForegroundColor Green; Write-Host $SupportUrl -ForegroundColor Cyan
    }

}

function CheckPrerequsites {
    Write-Host "Checking Prerequisites... " -ForegroundColor Yellow
    CheckPSVersion
    CheckNugetPackageProvider
}

function Init {
    CheckPrerequsites
    BootstrapInstaller    
}

Init