Install-SecureMFA_DEV_Code.ps1

#Requires -RunAsAdministrator

<#
     .SYNOPSIS
        Installs SecureMFA DEV Project Samples.
    .DESCRIPTION
        Installs sample projects into DEV Environment for quick start.
 
        Dependencies:
            * System must be connected to the Internet to download dependancies.
  
    .NOTES
        Version: 1.0.1.4
        Author: SecureMfa.com
        Creation Date: 21/03/2021
        Purpose/Change:
   
    .EXAMPLE
        C:\PS> Install-SecureMFA_DEV_Code -Sample SpringBootSAML
 
        This command will install SecureMFA Spring Security Simple SAML2 Example project and components configuration.
    
#>



#Check if windows events source for application log exist, if not create one.
if ([System.Diagnostics.EventLog]::SourceExists("SecureMFA_SupportTools") -eq $False) {New-EventLog -LogName "Application" -Source "SecureMFA_SupportTools" ; Write-Host "SecureMFA_SupportTools Log Source Created."}


Function Install-SecureMFA_DEV_Code {
Param
(
    [Parameter(Mandatory=$false)][ValidateSet('SpringBootSAML','None')][string]$Sample='SpringBootSAML'
)
    
    #Static Variables
    $AppsPath = "c:\Apps"
    $DistributionSource = $null; 
    $DistributionSite = $null;
    $ADFS_CER = ($AppsPath + "\adfs.cer")
    $ADFS_PEM = ($AppsPath + "\adfs.pem")
    $JavaCertsDB = ($env:JAVA_HOME + "\lib\security\cacerts")    
    
    #SecureMFA Spring Security Simple SAML2 Example
    $SpringBootSAML_uri = 'https://github.com/SecureMFA/adfs-spring-simple-saml/releases/download/1.0.0.0/adfs-spring-simple-saml.zip';
    $SpringBootSAML_name = 'adfs-spring-simple-saml.zip'
    $SpringBootSAML_site = 'https://github.com/SecureMFA/adfs-spring-simple-saml/'
    $SpringBootSAML_path = ($AppsPath + "\" + $SpringBootSAML_name) 
    $SpringBootSAML_testpath = ($AppsPath + "\adfs-spring-simple-saml") 
    $SpringBootSAML_appconfig = ($SpringBootSAML_testpath + "\src\main\resources\application.yml")
    $SpringBootSAML_samlconfig = ($SpringBootSAML_testpath + "\src\main\java\com\example\saml\controller\IndexController.java")
  
    try
    {
        $Error.Clear() 

        if($Sample -eq 'SpringBootSAML') {

            write-host "Installing SecureMFA DEV sample $Sample" -ForegroundColor Cyan

            Do{$ADFS_Metadata = Read-Host 'Please enter ADFS Federation Metadata Endpoint'}While (($ADFS_Metadata  -eq $null) -or ($ADFS_Metadata  -eq ""))
            Do{$ADFS_Identifier = Read-Host 'Please enter ADFS Identifier'}While (($ADFS_Identifier  -eq $null) -or ($ADFS_Identifier  -eq ""))

            #Create Apps folder
            If(!(test-path $AppsPath)) {New-Item -ItemType Directory -Force -Path $AppsPath}
            
            #SecureMFA Spring Security Simple SAML2 Example
            $DistributionSource = $SpringBootSAML_uri; 
            $DistributionSite = $SpringBootSAML_site;
            If(test-path $SpringBootSAML_path) {write-host "SecureMFA Spring Security Simple SAML2 Example $SpringBootSAML_path exist - skipping... " -ForegroundColor Yellow} else {write-host "SecureMFA Spring Security Simple SAML2 Example $openjdk_path download started... " -ForegroundColor Green; Invoke-WebRequest -Uri $SpringBootSAML_uri -OutFile $SpringBootSAML_path}
        
            $DistributionSource = $null; 
            $DistributionSite = $null;

            #Retrieve ADFS public cert
            Write-Host Checking $ADFS_Metadata -f Green
            [Net.ServicePointManager]::ServerCertificateValidationCallback = {$true}
            $req = [Net.HttpWebRequest]::Create($ADFS_Metadata)
            $req.Timeout = $timeoutMilliseconds
            try {$req.GetResponse() |Out-Null} catch {}
            $oMyCert=New-Object System.Security.Cryptography.X509Certificates.X509Certificate2($req.ServicePoint.Certificate)
            Export-Certificate -Cert $oMyCert -FilePath $ADFS_CER -Force
            openssl x509 -inform der -in $ADFS_CER -out $ADFS_PEM  

            #Installation Apache Maven
            $message  = "Do you want to reinstall existing SecureMFA Spring Security Simple SAML2 Example " + $SpringBootSAML_name + " ?";            
            $question = 'Please confirm?'
            $choices = New-Object Collections.ObjectModel.Collection[Management.Automation.Host.ChoiceDescription]
            $choices.Add((New-Object Management.Automation.Host.ChoiceDescription -ArgumentList '&Yes'))
            $choices.Add((New-Object Management.Automation.Host.ChoiceDescription -ArgumentList '&No'))
            #Found existing installation
            if(Test-Path $SpringBootSAML_testpath) {   
            $decision_Validation = $Host.UI.PromptForChoice($message, $question, $choices, 0)
            if ($decision_Validation -eq 1 ) {Write-Host "SecureMFA Spring Security Simple SAML2 Example installation has been cancelled, skipping!" -ForegroundColor Yellow ;} 
            else {
                    Remove-Item -Recurse -Force $SpringBootSAML_testpath
                    Expand-Archive -LiteralPath $SpringBootSAML_path -DestinationPath $SpringBootSAML_testpath -Force
                    (Get-Content -path ($SpringBootSAML_appconfig) -Raw) -replace 'ADFS-METADATA-PLACEHOLDER',$ADFS_Metadata | Set-Content -Path ($SpringBootSAML_appconfig)
                    (Get-Content -path ($SpringBootSAML_samlconfig) -Raw) -replace 'ADFS-ID-PLACEHOLDER',$ADFS_Identifier | Set-Content -Path ($SpringBootSAML_samlconfig) 
                 }
            }
            #No existing installation
            else {
                    Expand-Archive -LiteralPath $SpringBootSAML_path -DestinationPath $SpringBootSAML_testpath -Force
                    (Get-Content -path ($SpringBootSAML_appconfig) -Raw) -replace 'ADFS-METADATA-PLACEHOLDER',$ADFS_Metadata | Set-Content -Path ($SpringBootSAML_appconfig)
                    (Get-Content -path ($SpringBootSAML_samlconfig) -Raw) -replace 'ADFS-ID-PLACEHOLDER',$ADFS_Identifier | Set-Content -Path ($SpringBootSAML_samlconfig) 
                 }
        
            
            #Import public adfs cert into java keystore
            write-host "Importing $ADFS_PEM into JAVA keystore $JavaCertsDB" -ForegroundColor Green
            keytool -import -v -trustcacerts -alias 'adfspubliccert' -keystore $JavaCertsDB -file $ADFS_PEM -keypass changeit -storepass changeit -noprompt

            #End
            write-host "SecureMFA DEV sample $Sample deployment completed. Project path: $SpringBootSAML_testpath" -ForegroundColor Cyan
            write-host "To start a project execute: mvn spring-boot:run"
        }

        else {write-host "No DEV sample selected for deployment." -ForegroundColor Cyan}
    }
    catch
    {
        if(!([string]::IsNullOrEmpty($DistributionSource))) { Write-Host "Failed to download $DistributionSource , please update source location from $DistributionSite and try again." -ForegroundColor red }
        Write-Host "$($MyInvocation.InvocationName): $_" -ForegroundColor red 
        
    }

}