Thursday, December 31, 2020

Test website SSL with Windows PowerShell

How to test a website SSL certificate with Windows PowerShell





#-----------------------------------------------
#  Test Website SSL Certificate
#  by: Larry Billinghurst
#  date: 31 Dec 2020
#-----------------------------------------------

# Example:   .\test-ssl.ps1 -SiteURL https:\\dmv.utah.gov -ReportFile "C:\support\temp99.txt"


param(
    [parameter()]
    [string]$SiteURL = "https://www.facebook.com",
    [string]$ReportFile = $env:TEMP + "\sslreport.txt"
    )

$TempCerFile = $env:TEMP + "\sslchecktemp.cer"
$tempReportFile = "sslreport.txt"

#------------------------- Functions

function Get-WebsiteCertificate {
  [CmdletBinding()]
  param (
    [Parameter(Mandatory=$true)] [System.Uri]
      $Uri,
    [Parameter()] [System.IO.FileInfo]
      $OutputFile,
    [Parameter()] [Switch]
      $UseSystemProxy,  
    [Parameter()] [Switch]
      $UseDefaultCredentials,
    [Parameter()] [Switch]
      $TrustAllCertificates
  )
  try {
    $request = [System.Net.WebRequest]::Create($Uri)
    if ($UseSystemProxy) {
      $request.Proxy = [System.Net.WebRequest]::DefaultWebProxy
    }

    if ($UseSystemProxy -and $UseDefaultCredentials) {
      $request.Proxy.Credentials = [System.Net.CredentialCache]::DefaultNetworkCredentials
    }

    if ($TrustAllCertificates) {
      # Create a compilation environment
      $Provider=New-Object Microsoft.CSharp.CSharpCodeProvider
      $Compiler=$Provider.CreateCompiler()
      $Params=New-Object System.CodeDom.Compiler.CompilerParameters
      $Params.GenerateExecutable=$False
      $Params.GenerateInMemory=$True
      $Params.IncludeDebugInformation=$False
      $Params.ReferencedAssemblies.Add("System.DLL") > $null
      $TASource=@'
        namespace Local.ToolkitExtensions.Net.CertificatePolicy {
          public class TrustAll : System.Net.ICertificatePolicy {
            public TrustAll() { 
            }
            public bool CheckValidationResult(System.Net.ServicePoint sp,
              System.Security.Cryptography.X509Certificates.X509Certificate cert, 
              System.Net.WebRequest req, int problem) {
              return true;
            }
          }
        }
'@ 
      $TAResults=$Provider.CompileAssemblyFromSource($Params,$TASource)
      $TAAssembly=$TAResults.CompiledAssembly

      ## We now create an instance of the TrustAll and attach it to the ServicePointManager
      $TrustAll=$TAAssembly.CreateInstance("Local.ToolkitExtensions.Net.CertificatePolicy.TrustAll")
      [System.Net.ServicePointManager]::CertificatePolicy=$TrustAll
    }

    $response = $request.GetResponse()
    $servicePoint = $request.ServicePoint
    $certificate = $servicePoint.Certificate

    if ($OutputFile) {
      $certBytes = $certificate.Export(
          [System.Security.Cryptography.X509Certificates.X509ContentType]::Cert
        )
      [System.IO.File]::WriteAllBytes( $OutputFile$certBytes )
      $OutputFile.Refresh()
      return $OutputFile
    } else {
      return $certificate
    }
  } catch {
    Write-Error "Failed to get website certificate. The error was '$_'."
    return $null
  }

  <#
    .SYNOPSIS
      Retrieves the certificate used by a website.

    .DESCRIPTION
      Retrieves the certificate used by a website. Returns either an object or file.

    .PARAMETER  Uri
      The URL of the website. This should start with https.

    .PARAMETER  OutputFile
      Specifies what file to save the certificate as.

    .PARAMETER  UseSystemProxy
      Whether or not to use the system proxy settings.

    .PARAMETER  UseDefaultCredentials
      Whether or not to use the system logon credentials for the proxy.

    .PARAMETER  TrustAllCertificates
      Ignore certificate errors for certificates that are expired, have a mismatched common name or are self signed.

    .EXAMPLE
      PS C:\> Get-WebsiteCertificate "https://www.gmail.com" -UseSystemProxy -UseDefaultCredentials -TrustAllCertificates -OutputFile C:\gmail.cer

    .INPUTS
      Does not accept pipeline input.

    .OUTPUTS
      System.Security.Cryptography.X509Certificates.X509Certificate, System.IO.FileInfo
  #>
}


#-------------------- Main 


#Get Website SSL certificate and save to temp file
Get-WebsiteCertificate -Uri $SiteURL -OutputFile $TempCerFile
# Check Certifacate 
Write-Host
Write-Host "------------------------- SSL Report -------------------------"
Write-Host
certutil -f -urlfetch -verify $TempCerFile |Tee-Object $ReportFile


# Remove Report file if not requested
if ($tempReportFile -eq ($ReportFile|Split-Path -Leaf)) {Remove-Item $ReportFile}

# Remove Temp Cert File
Remove-Item $TempCerFile




Monday, December 21, 2020

Export SonicWALL config to text

Needed a way to export the SonicWALL config file to plane text.


It did not work correctly with Python3.

PS C:\support\fw> python.exe .\parser2.py .\sonicwall-NSA_2600.exp
  File ".\parser2.py", line 454
    print ""
          ^

I found the 2to3.exe tool in the Python tools directory.
 
C:\Users\"user-name"\AppData\Local\Packages\PythonSoftwareFoundation.Python.3.8_qbz5n2kfra8p0\LocalCache\local-packages\Python38\Scripts

Made a copy of the file
.\copy C:\temp\parser2.py C:\temp\parser2-3.py 

Ran the tool
.\2to3.exe C:\temp\parser2-3.py -w


After converting with 2to3.exe tool still received a error

python.exe .\parser2-3.py .\sonicwall-NSA_2600.exp

Traceback (most recent call last):
  File ".\parser2-3.py", line 14, in <module>
    decoded_data =  decoded_data.split("&")
TypeError: a bytes-like object is required, not 'str'


A little research found we needed to convert the byte-like object to string
decoded_data = decoded_data.decode(encoding="utf-8"# Python 3

After the update the parser worked without issue.
python.exe .\parser3.py .\sonicwall-NSA_2600.exp  >test.txt

I posted the updated files on GitHub

Tuesday, September 15, 2020

Hide Mailbox form GAL in O365 Powershell

 When using mailboxes in O365 and using Directory Sync you can only hid a mailbox using the extended attributes in AD.

Get-ADUser test5|Set-ADObject -replace @{msExchHideFromAddressLists=$true}


Ref: https://medium.com/gitbit/hide-user-from-address-lists-ad-connect-ee67f2369bc1


Monday, March 23, 2020

Delete files older than 30 days but not the first of the month

# Delete files older than 30 days that are not day 1 (fist of the month)

Get-ChildItem -path \\big-nas\Data\Backup\Database -r | Where-Object {($_.LastWriteTime -lt (Get-Date).AddDays(-30)) -and (($_.LastWriteTime).day -ne 1 )} |remove-item

Monday, March 16, 2020

TP-Link AC750 replacement USB charging cable issues


Finding a compatible USB charging cable on a TP-link AC750 can be difficult because not all USB cables with Micro-USB B-Plugs are the same. 

This issue arises when the USB B-Plug’s latch head is not at least 5.8mm in length.  Latch heads shorter than 5.8mm will not lock into place.




Saturday, February 22, 2020

Spawn powershell app from cmd

Is it possible to create a powershell script from cmd or bat file?

Compress powershell script
expand and save to ps1 files
run files

Friday, January 24, 2020

Update DICOM tags with PowerShell



Using the dicom PowerShell Module



Get the DICOM Powershell Module
https://www.powershellgallery.com/packages/Dicom/1.0.10.0


Powershell Script
================================================
# Update DICOM file TAGS

# Use this command to install Dicom Module - Install-Module -Name Dicom


$curpath = $(Get-Location).Path
$targetFolder = $curpath + "\*.dcm"
$dcmfiles = Get-ChildItem $targetFolder

# Series Description Tag Names Hash table
        $seriesDescriptionS = @{
            LAP='Leg Full Left AP (Stitched)'
            LL='Leg Full Left Lat (Stitched)'
            RAP='Leg Full Right AP (Stitched)'
            RL='Leg Full Right Lat (Stitched)'
        }



#Process targeted dicom files

ForEach ($dcmfile in $dcmfiles) {

$dicomfile = Import-dicom -Filename $dcmfile
$dicom = Read-Dicom -DicomFile $dicomfile
$dicom.SeriesDescription
$PatientID=$dicom.PatientID
$newseriesDescription = $seriesDescriptionS.($dcmfile.BaseName.ToUpper())
$tempfolder = "c:\support\dcmtemp"
# Look for file names with ll,rl,rap, or rl to processs and insert tags
    if ($newseriesDescription) {


    edit-dicom -DicomFile $dicomfile -Tag "0018,1164" -Value '0.150000\0.150000'
    edit-dicom -DicomFile $dicomfile -Tag "0008,103e" -Value $newseriesDescription
    Export-Dicom -DicomFile $dicomfile -DestinationPath $tempfolder
    $tempfile = $tempfolder + "\DICOM\0000001"
    $targetFile = $curpath + "\" + $PatientID + "-" +$dcmfile.BaseName.ToUpper() + "s.dcm"
    $targetFile
    Copy-Item -Path $tempfile -Destination $targetFile


    }
}

Remove-Item $tempfolder -Force  -Recurse -ErrorAction SilentlyContinue

Thursday, January 23, 2020

Check if LLMNR is disabled with PowerShell

Check if LLMNR Is disabled with PowerShell

Get-ItemProperty -Path "HKLM:\Software\Policies\Microsoft\Windows NT\DNSClient" -name EnableMulticast


If it returns an error then it is not set.



example

PS C:\support\scripts> Get-ItemProperty -Path "HKLM:\Software\Policies\Microsoft\Windows NT\DNSClient" -name EnableMulticast


EnableMulticast : 0
PSPath          : Microsoft.PowerShell.Core\Registry::HKEY_LOCAL_MACHINE\Software\Policies\Microsoft\Windows
                  NT\DNSClient
PSParentPath    : Microsoft.PowerShell.Core\Registry::HKEY_LOCAL_MACHINE\Software\Policies\Microsoft\Windows NT
PSChildName     : DNSClient
PSDrive         : HKLM
PSProvider      : Microsoft.PowerShell.Core\Registry


Get Just the value

$(Get-ItemProperty -Path "HKLM:\Software\Policies\Microsoft\Windows NT\DNSClient" -name EnableMulticast).EnableMulticast

Returns 0 if disabled.