' SummaryPage2_ConfigurationSecurityReport
Imports System.Net

Option Explicit On
Option Strict On

' #################################################################
' Configuration Security Report
'
' Copyright (C) Intersoft Systems Limited 2021
'
' Add the following text to KB articles related to this script:
' Note: This summary page is not currently accessible for customisation.
'
' Version: 2.11 (26/07/2024)
' #################################################################
' Version        Date  User     Job       Description
' -------  ----------  -------  --------  -------------------------
'    2.03  09/04/2021  ISS
'    2.04  31/05/2023  ISS      J030829   Allow for non-Administrators
'    2.05  15/08/2023  ISS      J030645   Add User login/ password expiry warnings
'    2.06  25/10/2023  ISS      J031881   Added UserPolicy auto-disable checks
'    2.07  08/11/2023  ISS      J032314   Using new finBL.Users.CountUserPolicy method
'    2.08  01/12/2023  ISS      J032519   Added auto-disable never-logged-in check
'    2.09  04/04/2024  ISS      J032546   Added warnings for integrated security
'    2.10  07/06/2024  ISS      J033447   Improved descriptions for Password History issues
'          07/06/2024  ISS      J033454   Added password-expiry message for never-logged-in Users
'          10/06/2024  ISS      J033449   Added message when lock-out log-in attempts is indefinite
'    2.11  05/07/2024  ISS      J033849   Typo correction
'          26/07/2024  ISS      J033969   User password warnings now report earlier, at lower priorities and escalate if required
' #################################################################

Private Const ICON_PRIORITY_LOW As String = "{{ICON|Outcome_Neutral}}"
Private Const ICON_PRIORITY_MEDIUM As String = "{{ICON|Outcome_Invalid}}"
Private Const ICON_PRIORITY_HIGH As String = "{{ICON|Outcome_Failed}}"

Public Function Main(source As Object,
                     eventId As String,
                     eventArgs As ISKeyValueList,
                     ByRef handled As Boolean,
                     ByRef returnValues As ISKeyValueList,
                     ByRef text As String) As Boolean

  ' Assume Success
  Main = True

  ' Handle Events
  Select Case eventId
    Case ""
      ' Main event, i.e., return main page content
      Main = CreatePage(text)
  End Select

End Function

''' <summary>
'''  Creates the page.
''' </summary>
Private Function CreatePage(ByRef html As String) As Boolean

  Dim sb As finHtmlSummaryPage2StringBuilder
  Dim HighAlerts As Boolean
  Dim Success As Boolean
  Dim SummaryTables As ISSummaryTables

  ' Assume Success
  Success = True

  ' Initialise
  sb = finBL.CreateHtmlSummaryPage2StringBuilder()

  ' Initialise HTML
  With sb
    .Initialise(ScriptInfo)
    .HtmlHeaderBegin("", isefinSummaryPageStyle.Document)
    .HtmlHeaderEnd()
  End With

  ' Heading
  sb.AppendH1("finPOWER Connect Configuration Security Report")
  sb.AppendLine(String.Format("Printed on {0}", finBL.TimeZoneFunctions.GetCurrentLocalDateTime()))
  sb.AppendLine(" ")

  ' Columns
  sb.SectionColumnsBegin("100%")
  sb.ColumnBegin()

  ' Warnings
  SummaryTables = ConfigurationSecurityReport_Information()
  If SummaryTables.Count <> 0 Then
    sb.BlockBegin("Information")
    sb.SummaryTablesAppend(SummaryTables)
    sb.BlockEnd()
  End If

  ' General
  SummaryTables = ConfigurationSecurityReport_General(HighAlerts)
  If SummaryTables.Count <> 0 Then
    If HighAlerts Then
      sb.BlockBegin("General", "", isefinSummaryPageBlockHeadingStyle.Warning)
    Else
      sb.BlockBegin("General")
    End If
    sb.SummaryTablesAppend(SummaryTables)
    sb.BlockEnd()
  End If

  ' Clients
  SummaryTables = ConfigurationSecurityReport_Clients(HighAlerts)
  If SummaryTables.Count <> 0 Then
    If HighAlerts Then
      sb.BlockBegin("Clients", "", isefinSummaryPageBlockHeadingStyle.Warning)
    Else
      sb.BlockBegin("Clients")
    End If
    sb.SummaryTablesAppend(SummaryTables)
    sb.BlockEnd()
  End If

  ' Users
  SummaryTables = ConfigurationSecurityReport_Users(HighAlerts)
  If SummaryTables.Count <> 0 Then
    If HighAlerts Then
      sb.BlockBegin("Users", "", isefinSummaryPageBlockHeadingStyle.Warning)
    Else
      sb.BlockBegin("Users")
    End If
    sb.SummaryTablesAppend(SummaryTables)
    sb.BlockEnd()
  End If

  ' User Policies
  SummaryTables = ConfigurationSecurityReport_UserPolicies(HighAlerts)
  If SummaryTables.Count <> 0 Then
    If HighAlerts Then
      sb.BlockBegin("User Policies", "", isefinSummaryPageBlockHeadingStyle.Warning)
    Else
      sb.BlockBegin("User Policies")
    End If
    sb.SummaryTablesAppend(SummaryTables)
    sb.BlockEnd()
  End If

  ' Bank Transaction
  SummaryTables = ConfigurationSecurityReport_BankTransactions()
  If SummaryTables.Count <> 0 Then
    sb.BlockBegin("Bank Transactions")
    sb.SummaryTablesAppend(SummaryTables)
    sb.BlockEnd()
  End If

  ' Columns
  sb.ColumnEnd()
  sb.SectionColumnsEnd()

  ' Finalise HTML
  sb.HtmlFinalise()

  ' Resolve Templates
  html = sb.ToString(True)

  Return Success

End Function

''' <summary>
'''  Configuration Security Report General.
''' </summary>
Private Function ConfigurationSecurityReport_General(ByRef hasHighAlerts As Boolean) As ISSummaryTables

  Dim IntegratedSecurityTxt As String
  Dim LatestVersion As String
  Dim SummaryTableHigh As ISSummaryTable
  Dim SummaryTableLow As ISSummaryTable
  Dim SummaryTables As ISSummaryTables

  ' Initialise ByRef
  hasHighAlerts = False
  

  ' Create Objects
  SummaryTableHigh = finBL.CreateSummaryTable()
  SummaryTableLow = finBL.CreateSummaryTable()
  SummaryTables = finBL.CreateSummaryTables()

  ' Get Latest Business Layer Version
  GetLatestVersion(LatestVersion)

  ' Initialise Summary Table High
  With SummaryTableHigh
    ' Initialise
    .TableClass = iseSummaryTableClass.TabularData
    .Caption = ICON_PRIORITY_HIGH & " High"
    .AutoStripe = True

    ' Columns
    With .Columns
      .AddText("Code", 12)
      .AddText("Warning")
    End With
  End With
  
  ' Integrated Security
  If finBL.AllowIntegratedSecurity AndAlso finBL.Users.CountIntegratedSecurity <> 0 Then
    With SummaryTableHigh.Rows.Add().Cells
      .AddText("")
      
      ' Build up the integrated security text.
      IntegratedSecurityTxt = "Integrated Security is enabled. This allows users to access finPOWER Connect without logging in. "
      
      If finBL.Users.CountIntegratedSecurity = 1 Then
        IntegratedSecurityTxt &= String.Format("There is {0} user using Integrated Security.", finBL.Users.CountIntegratedSecurity)
      Else
        IntegratedSecurityTxt &= String.Format("There are {0} users using Integrated Security.", finBL.Users.CountIntegratedSecurity)
      End If
      
      .AddText(IntegratedSecurityTxt)
    End With
  End If

  ' User Credentials
  With SummaryTableLow
    ' Initialise
    .TableClass = iseSummaryTableClass.TabularData
    .Caption = ICON_PRIORITY_LOW & " Low"
    .AutoStripe = True

    ' Columns
    With .Columns
      .AddText("Code", 12)
      .AddText("Warning")
    End With

    ' Rows
    With .Rows.Add().Cells
      .AddText("")
      .AddText("If user credentials are passed via a command line parameter in the shortcut for finPOWER Connect then this could result in unauthorised users logging in to finPOWER Connect.")
    End With
  End With

  ' Version
  Select Case CompareVersions(LatestVersion)
    Case -2
      With SummaryTableLow.Rows.Add().Cells
        .AddText("")
        .AddWiki(String.Format("You are using version **{0}** of the finPOWER Connect Business Layer. Visit the [[https://www.intersoft.co.nz/Support/ReleaseHistory.aspx|Intersoft Website]] to see the latest version.", finBL.VersionMajorMinorBuild))
      End With

    Case -1
      With SummaryTableHigh.Rows.Add().Cells
        .AddText("")
        .AddWiki(String.Format("You are using an older version of finPOWER Connect. You are using version: **{0}** and the latest is **{1}**.", finBL.VersionMajorMinorBuild, LatestVersion))
      End With

    Case 0
      With SummaryTableLow.Rows.Add().Cells
        .AddText("")
        .AddWiki(String.Format("You are using the latest version of the finPOWER Connect (Version: **{0}**).", finBL.VersionMajorMinorBuild))
      End With

    Case 1
      With SummaryTableHigh.Rows.Add().Cells
        .AddText("")
        .AddText("You are using an unreleased version of finPOWER Connect.")
      End With
  End Select

  ' Add Summary Tables
  If SummaryTableHigh.HasData(True) Then SummaryTables.Add("High", SummaryTableHigh)
  If SummaryTableLow.HasData(True) Then SummaryTables.Add("Low", SummaryTableLow)

  ' Has high alerts?
  hasHighAlerts = SummaryTableHigh.HasData(True)

  Return SummaryTables

End Function

''' <summary>
'''  Configuration Security Report Clients.
''' </summary>
Private Function ConfigurationSecurityReport_Clients(ByRef hasHighAlerts As Boolean) As ISSummaryTables

  Dim SummaryTableHigh As ISSummaryTable
  Dim SummaryTableLow As ISSummaryTable
  Dim SummaryTables As ISSummaryTables
  Dim WebAccessClientList As ISList
  Dim WebClientCount As Integer

  ' Initialise ByRef
  hasHighAlerts = False

  ' Create Objects
  SummaryTableHigh = finBL.CreateSummaryTable()
  SummaryTableLow = finBL.CreateSummaryTable()
  SummaryTables = finBL.CreateSummaryTables()

  ' Web Client Count
  If finBL.ClientFunctions.GetWebAccessClientIds(WebAccessClientList) Then
    WebClientCount = WebAccessClientList.Count
  End If

  ' Initialise Summary Table High
  With SummaryTableHigh
    ' Initialise
    .TableClass = iseSummaryTableClass.TabularData
    .Caption = ICON_PRIORITY_HIGH & " High"
    .AutoStripe = True

    ' Columns
    With .Columns
      .AddText("Code", 12)
      .AddText("Warning")
    End With
  End With

  ' Initialise Summary Table Low
  With SummaryTableLow
    .TableClass = iseSummaryTableClass.TabularData
    .Caption = ICON_PRIORITY_LOW & " Low"
    .AutoStripe = True

    ' Columns
    With .Columns
      .AddText("Code", 12)
      .AddText("Warning")
    End With
  End With

  If WebClientCount > 0 Then
    ' Force Strong Web Passwords
    If Not finBL.Settings.ClientWebPasswordStrong Then
      With SummaryTableHigh.Rows.Add().Cells()
        .AddText("")
        .AddText("Web Access Passwords for Clients are not enforced as strong.")
      End With
    End If

    ' Minimum length Web Passwords
    If finBL.Settings.ClientWebPasswordMinLength < 8 Then
      With SummaryTableHigh.Rows.Add().Cells()
        .AddText("")
        .AddText(String.Format("Minimum Client Web Access Password length less than 8 characters ({0} characters).", finBL.Settings.ClientWebPasswordMinLength))
      End With
    End If

    ' Client Count
    With SummaryTableLow.Rows.Add().Cells()
      .AddText("")

      If WebClientCount = 1 Then
        .AddText(String.Format("{0} Client is configured for Web Access.", WebClientCount))
      Else
        .AddText(String.Format("{0} Clients are configured for Web Access.", WebClientCount))
      End If
    End With
  End If

  ' Add Summary Tables
  If SummaryTableHigh.HasData(True) Then SummaryTables.Add("High", SummaryTableHigh)
  If SummaryTableLow.HasData(True) Then SummaryTables.Add("Low", SummaryTableLow)

  ' Has high alerts?
  hasHighAlerts = SummaryTableHigh.HasData(True)

  Return SummaryTables

End Function

''' <summary>
'''  Configuration Security Report Users.
''' </summary>
Private Function ConfigurationSecurityReport_Users(ByRef hasHighAlerts As Boolean) As ISSummaryTables

  Dim Days As Long
  Dim dr As IDataReader
  Dim sqb As ISSelectQueryBuilder
  Dim SummaryTableHigh As ISSummaryTable
  Dim SummaryTableLow As ISSummaryTable
  Dim SummaryTableMedium As ISSummaryTable
  Dim SummaryTables As ISSummaryTables
  Dim User As finUser
  Dim UserRO As finUserRO
  Dim WebAccessCount As Integer

  ' Initialise ByRef
  hasHighAlerts = False

  ' Create Objects
  sqb = finBL.Database.CreateSelectQueryBuilder()
  SummaryTableHigh = finBL.CreateSummaryTable()
  SummaryTableLow = finBL.CreateSummaryTable()
  SummaryTableMedium = finBL.CreateSummaryTable()
  SummaryTables = finBL.CreateSummaryTables()
  User = finBL.CreateUser()

  ' Default Values
  WebAccessCount = 0

  ' Initialise Summary Table High
  With SummaryTableHigh
    ' Initialise
    .TableClass = iseSummaryTableClass.TabularData
    .Caption = ICON_PRIORITY_HIGH & " High"
    .AutoStripe = True

    ' Columns
    With .Columns
      .AddText("Code", 12)
      .AddText("Warning")
    End With
  End With

  ' Initialise Summary Table Medium
  With SummaryTableMedium
    ' Initialise
    .TableClass = iseSummaryTableClass.TabularData
    .Caption = ICON_PRIORITY_MEDIUM & " Medium"
    .AutoStripe = True

    ' Columns
    With .Columns
      .AddText("Code", 12)
      .AddText("Warning")
    End With
  End With

  ' Initialise Summary Table Low
  With SummaryTableLow
    .TableClass = iseSummaryTableClass.TabularData
    .Caption = ICON_PRIORITY_LOW & " Low"
    .AutoStripe = True

    ' Columns
    With .Columns
      .AddText("Code", 12)
      .AddText("Warning")
    End With
  End With

  ' Admin User
  If finBL.Security.VerifyUserCredentials("admin/admin") Then
    With SummaryTableHigh.Rows.Add().Cells()
      .AddText("ADMIN").HyperlinkSetFormShow("Users", "Admin")
      .AddText("Default login of admin/admin can be used to access this database.")
    End With
  End If

  ' User User
  If finBL.Security.VerifyUserCredentials("user/password") Then
    With SummaryTableHigh.Rows.Add().Cells()
      .AddText("USER").HyperlinkSetFormShow("Users", "User")
      .AddText("Default login of user/password can be used to access this database.")
    End With
  End If

  ' Users
  For Each UserRO In finBL.Users
    If UserRO.Active AndAlso Not UserRO.Deleted Then
      If User.Load(UserRO.UserId) Then
        ' Email missing
        If User.UserPolicy.EmailMandatory AndAlso Len(User.Email) = 0 Then
          With SummaryTableMedium.Rows.Add().Cells()
            .AddText(User.UserId).HyperlinkSetFormShow("Users", User.UserId)
            .AddText("An email address is required for this User.")
          End With
        End If
        
        ' Integrated Security - users using integrated security, but integrated security is not enabled.
        If User.UseIntegratedSecurity AndAlso Not finBL.AllowIntegratedSecurity Then
          With SummaryTableMedium.Rows.Add().Cells()
            .AddText(User.UserId).HyperlinkSetFormShow("Users", User.UserId)
            .AddText("This user is setup to use integrated security, but integrated security is not enabled.")
          End With
        End If        

        ' Password force change
        If User.PasswordForceChange Then
          With SummaryTableLow.Rows.Add().Cells()
            .AddText(User.UserId).HyperlinkSetFormShow("Users", User.UserId)
            .AddText("Force change of password is set and password not changed.")
          End With
        End If

        ' Locked out
        If User.IsLockedOut Then
          With SummaryTableHigh.Rows.Add().Cells()
            .AddText(User.UserId).HyperlinkSetFormShow("Users", User.UserId)
            .AddText(String.Format("This User has been locked out since {0}.", finBL.FormatDateLong(User.LockedOutDate)))
          End With
        End If
        
        ' Login 
        If User.LastLoginUtcDate = Nothing Then
          ' Report if never logged in
          Days = DateDiff(DateInterval.Day, User.CreatedUtcDate, finBL.TimeZoneFunctions.GetCurrentUtcDateTime)
          With SummaryTableHigh.Rows.Add().Cells()
            .AddText(User.UserId).HyperlinkSetFormShow("Users", User.UserId)
            .AddText(String.Format("User has never logged in. User was created {0} days ago.", Days))
          End With
        Else
          ' Report if hasn't logged in for more than X days
          Days = DateDiff(DateInterval.Day, User.LastLoginUtcDate, finBL.TimeZoneFunctions.GetCurrentUtcDateTime)
          If Days > 90 Then
            With SummaryTableHigh.Rows.Add().Cells()
              .AddText(User.UserId).HyperlinkSetFormShow("Users", User.UserId)
              .AddText(String.Format("User has not logged in for {0} days.", Days))
            End With
          ElseIf Days > 60 Then
            With SummaryTableMedium.Rows.Add().Cells()
              .AddText(User.UserId).HyperlinkSetFormShow("Users", User.UserId)
              .AddText(String.Format("User has not logged in for {0} days.", Days))
            End With
          ElseIf Days > 30 Then
            With SummaryTableLow.Rows.Add().Cells()
              .AddText(User.UserId).HyperlinkSetFormShow("Users", User.UserId)
              .AddText(String.Format("User has not logged in for {0} days.", Days))
            End With
          End If
        End If  

        ' Password Expiry
        If User.PasswordExpiryUtcDate <> Nothing Then
          Days = DateDiff(DateInterval.Day, User.PasswordExpiryUtcDate, finBL.TimeZoneFunctions.GetCurrentUtcDateTime)
          If Days > 30 Then
            With SummaryTableHigh.Rows.Add().Cells()
              .AddText(User.UserId).HyperlinkSetFormShow("Users", User.UserId)
              .AddText(String.Format("User's password expired {0} days ago.", Days))
            End With
          ElseIf Days > 15 Then
            With SummaryTableMedium.Rows.Add().Cells()
              .AddText(User.UserId).HyperlinkSetFormShow("Users", User.UserId)
              .AddText(String.Format("User's password expired {0} days ago.", Days))
            End With
          ElseIf Days > 1 Then
            With SummaryTableLow.Rows.Add().Cells()
              .AddText(User.UserId).HyperlinkSetFormShow("Users", User.UserId)
              .AddText(String.Format("User's password expired {0} days ago.", Days))
            End With
          ElseIf Days = 1 Then
            With SummaryTableLow.Rows.Add().Cells()
              .AddText(User.UserId).HyperlinkSetFormShow("Users", User.UserId)
              .AddText("User's password expired yesterday.")
            End With
          End If
        End If  

        ' Web Access
        If User.WebAccess AndAlso User.Active AndAlso Not User.Deleted Then
          WebAccessCount += 1
        End If
      End If
    End If
  Next

  ' Build query
  With sqb
    .Clear()
    .Table = "User"
    .Fields.AddList("Pk,UserId")

    With .SqlWhere
      .AppendComparisonDate("PasswordUtcDate", "<", finBL.TimeZoneFunctions.GetCurrentUtcDateTime.AddDays(-365))
      .AppendComparisonIntegerBoolean("Active", "=", True)
      .AppendComparisonIntegerBoolean("Deleted", "=", False)
    End With
  End With

  ' Load Users
  If sqb.ExecuteDisconnectedDataReader(dr, 0,finBL.Settings.DatabaseTimeoutSecondsLong) Then
    With dr
      ' Loop through Users
      Do While .Read()
        With SummaryTableLow.Rows.Add().Cells()
          .AddText(finBL.Database.GetFieldString(dr!UserId)).HyperlinkSetFormShow("Users", finBL.Database.GetFieldString(dr!UserId))
          .AddText("This User's password has not been changed in the last year.")
        End With
      Loop
    End With

    ' Close Datareader
    finBL.Database.DataReaderClose(dr)
  End If

  ' Web Access
  If WebAccessCount > 0 Then
    With SummaryTableLow.Rows.Add().Cells()
      .AddText("")

      If WebAccessCount = 1 Then
        .AddText(String.Format("{0} User is configured for Web Access.", WebAccessCount))
      Else
        .AddText(String.Format("{0} Users are configured for Web Access.", WebAccessCount))
      End If
    End With
  End If

  ' Add Summary Tables
  If SummaryTableHigh.HasData(True) Then SummaryTables.Add("High", SummaryTableHigh)
  If SummaryTableMedium.HasData(True) Then SummaryTables.Add("Medium", SummaryTableMedium)
  If SummaryTableLow.HasData(True) Then SummaryTables.Add("Low", SummaryTableLow)

  ' Has high alerts?
  hasHighAlerts = SummaryTableHigh.HasData(True)

  Return SummaryTables

End Function

''' <summary>
'''  Information which should always be displayed.
''' </summary>
Private Function ConfigurationSecurityReport_Information() As ISSummaryTables

  Dim SummaryTable As ISSummaryTable
  Dim SummaryTables As ISSummaryTables

  ' Initialise
  SummaryTable = finBL.CreateSummaryTable()
  SummaryTables = finBL.CreateSummaryTables()

  ' Add Warnings
  With SummaryTable
    .TextAfter = "{{info|This report cannot determine if a Users' current Password meets current User Policy strength and length requirements. This is because they cannot be retrieved and reverse-engineered to check.}}"
  End With

  ' Add
  SummaryTables.Add("Information", SummaryTable)

  Return SummaryTables

End Function

''' <summary>
'''  Configuration Security Report User Policies.
''' </summary>
Private Function ConfigurationSecurityReport_UserPolicies(ByRef hasHighAlerts As Boolean) As ISSummaryTables

  Dim SummaryTableHigh As ISSummaryTable
  Dim SummaryTableLow As ISSummaryTable
  Dim SummaryTableMedium As ISSummaryTable
  Dim SummaryTables As ISSummaryTables
  Dim UserPolicy As ISUserPolicy
  Dim UserPolicyRO As ISUserPolicyRO

  ' Initialise ByRef
  hasHighAlerts = False

  ' Create Objects
  SummaryTableHigh = finBL.CreateSummaryTable()
  SummaryTableLow = finBL.CreateSummaryTable()
  SummaryTableMedium = finBL.CreateSummaryTable()
  SummaryTables = finBL.CreateSummaryTables()
  UserPolicy = finBL.CreateUserPolicy()

  With SummaryTableHigh
    ' Initialise
    .TableClass = iseSummaryTableClass.TabularData
    .Caption = ICON_PRIORITY_HIGH & " High"
    .AutoStripe = True

    ' Columns
    With .Columns
      .AddText("Code", 12)
      .AddText("Warning")
    End With
  End With

  With SummaryTableMedium
    ' Initialise
    .TableClass = iseSummaryTableClass.TabularData
    .Caption = ICON_PRIORITY_MEDIUM & " Medium"
    .AutoStripe = True

    ' Columns
    With .Columns
      .AddText("Code", 12)
      .AddText("Warning")
    End With
  End With

  With SummaryTableLow
    ' Initialise
    .TableClass = iseSummaryTableClass.TabularData
    .Caption = ICON_PRIORITY_LOW & " Low"
    .AutoStripe = True

    ' Columns
    With .Columns
      .AddText("Code", 12)
      .AddText("Warning")
    End With
  End With

  ' Check
  For Each UserPolicyRO In finBL.UserPolicies
    ' Load User Policy (global collection only stores a sub-set of properties)
    UserPolicy.LoadPk(UserPolicyRO.Pk)

    ' Strong Password
    If Not UserPolicy.PasswordStrong Then
      With SummaryTableHigh.Rows.Add().Cells()
        .AddText(UserPolicy.UserPolicyId).HyperlinkSetFormShow("UserPolicies", UserPolicy.UserPolicyId)
        .AddText("Does not force strong passwords.")
      End With
    End If

    ' Login Failed Delay
    If UserPolicy.LoginFailedDelaySeconds = 0 Then
      With SummaryTableMedium.Rows.Add().Cells()
        .AddText(UserPolicy.UserPolicyId).HyperlinkSetFormShow("UserPolicies", UserPolicy.UserPolicyId)
        .AddText("'Invalid login delay' is set to zero. This allows brute-force attacks to work at full-speed. Consider setting to at least 0.1 seconds.")
      End With
    End If

    ' Password Length
    If UserPolicy.PasswordMinLength < 6 Then
      With SummaryTableHigh.Rows.Add().Cells()
        .AddText(UserPolicy.UserPolicyId).HyperlinkSetFormShow("UserPolicies", UserPolicy.UserPolicyId)
        .AddText(String.Format("Minimum password length less than 6 characters ({0} characters). We recommend 8 characters.", UserPolicy.PasswordMinLength))
      End With
    ElseIf UserPolicy.PasswordMinLength < 8 Then
      With SummaryTableMedium.Rows.Add().Cells()
        .AddText(UserPolicy.UserPolicyId).HyperlinkSetFormShow("UserPolicies", UserPolicy.UserPolicyId)
        .AddText(String.Format("Minimum password length less than 8 characters ({0} characters). We recommend 8 characters.", UserPolicy.PasswordMinLength))
      End With
    End If

    ' Password Age
    If UserPolicy.PasswordMaxAgeDays = 0 Then
      With SummaryTableLow.Rows.Add().Cells()
        .AddText(UserPolicy.UserPolicyId).HyperlinkSetFormShow("UserPolicies", UserPolicy.UserPolicyId)
        .AddText("User passwords never expire. The longer a user retains their password, the greater the likelihood of it being discovered.")
      End With
    End If

    ' Password History
    If UserPolicy.PasswordHistoryLength < 2 Then
      With SummaryTableLow.Rows.Add().Cells()
        .AddText(UserPolicy.UserPolicyId).HyperlinkSetFormShow("UserPolicies", UserPolicy.UserPolicyId)
        Select Case UserPolicy.PasswordHistoryLength
        Case 0
          .AddText("User password history is set to 0. That means the user will be able to reuse a previous password any time.")
        Case 1
          .AddText("User password history is set to 1. That means the user will be able to reuse a password after it has been updated only once. ")        
        End Select
      End With
    End If

    ' Web Access
    If finBL.Users.CountUserPolicy(UserPolicy.Pk, False, False, True) <> 0 Then
      With SummaryTableLow.Rows.Add().Cells()
        .AddText(UserPolicy.UserPolicyId).HyperlinkSetFormShow("UserPolicies", UserPolicy.UserPolicyId)
        .AddText("Has Active Users with Web Access.")
      End With
    End If
    
    ' Auto disable not enabled
    If Not UserPolicy.DisableAutomatic Then
      With SummaryTableMedium.Rows.Add().Cells()
        .AddText(UserPolicy.UserPolicyId).HyperlinkSetFormShow("UserPolicies", UserPolicy.UserPolicyId)
        .AddText("Automatic User disabling is not enabled.")
      End With
    End If
    
    ' Days not logged in setting above recommended value
    If UserPolicy.DisableDaysSinceLogin  > 90 Then
      With SummaryTableMedium.Rows.Add().Cells()
        .AddText(UserPolicy.UserPolicyId).HyperlinkSetFormShow("UserPolicies", UserPolicy.UserPolicyId)
        .AddText(String.Format("The number of days without logging in before automatic disabling is set to {0} days. We recommend no more than 90 days.", UserPolicy.DisableDaysSinceLogin))
      End With
    End If
      
    ' Days since password expiry setting above recommended value
    If UserPolicy.DisableDaysSincePasswordExpired  > 30 Then
      With SummaryTableMedium.Rows.Add().Cells()
        .AddText(UserPolicy.UserPolicyId).HyperlinkSetFormShow("UserPolicies", UserPolicy.UserPolicyId)
        .AddText(String.Format("The number of days after password expiry before automatic disabling is set to {0} days. We recommend no more than 30 days.", UserPolicy.DisableDaysSincePasswordExpired))
      End With
    End If

    ' Days never logged in setting above recommended value
    If UserPolicy.DisableDaysNeverLoggedIn  > 7 Then
      With SummaryTableMedium.Rows.Add().Cells()
        .AddText(UserPolicy.UserPolicyId).HyperlinkSetFormShow("UserPolicies", UserPolicy.UserPolicyId)
        .AddText(String.Format("The number of days a new user never logs in before automatic disabling is set to {0} days. We recommend no more than 7 days.", UserPolicy.DisableDaysNeverLoggedIn))
      End With
    End If

    ' Lock-Out Log-In Attempts set indefinite
    If UserPolicy.LoginLockoutAttempts = 0 Then
      With SummaryTableHigh.Rows.Add().Cells()
        .AddText(UserPolicy.UserPolicyId).HyperlinkSetFormShow("UserPolicies", UserPolicy.UserPolicyId)
        .AddText("The number of incorrect login attempts before locking out a User is set to 0 (indefinite). We recommend 1-3 attempts.")
      End With
    End If
  Next

  ' Add Summary Tables
  If SummaryTableHigh.HasData(True) Then SummaryTables.Add("High", SummaryTableHigh)
  If SummaryTableMedium.HasData(True) Then SummaryTables.Add("Medium", SummaryTableMedium)
  If SummaryTableLow.HasData(True) Then SummaryTables.Add("Low", SummaryTableLow)

  ' Has high alerts?
  hasHighAlerts = SummaryTableHigh.HasData(True)

  Return SummaryTables

End Function

''' <summary>
'''  Configuration Security Report Bank Transactions.
''' </summary>
Private Function ConfigurationSecurityReport_BankTransactions() As ISSummaryTables

  Dim BankingDetails As finBankingDetails
  Dim BankingDetailsCleared As Boolean
  Dim dr As IDataReader
  Dim PaymentMethodPks As String
  Dim sqb As ISSelectQueryBuilder
  Dim SummaryTableMedium As ISSummaryTable
  Dim SummaryTables As ISSummaryTables

  ' Create Objects
  BankingDetails = finBL.CreateBankingDetails()
  sqb = finBL.Database.CreateSelectQueryBuilder()
  SummaryTableMedium = finBL.CreateSummaryTable()
  SummaryTables = finBL.CreateSummaryTables()

  ' Initialise Summary Table Medium
  With SummaryTableMedium
    ' Initialise
    .TableClass = iseSummaryTableClass.TabularData
    .Caption = ICON_PRIORITY_MEDIUM & " Medium"
    .AutoStripe = True

    ' Columns
    With .Columns
      .AddText("Code", 12)
      .AddText("Warning")
    End With
  End With

  ' Are payment details purged from Bank Transactions - Credit Cards only
  PaymentMethodPks = finBL.PaymentMethods.GetPaymentMethodPksListCreditCards.ToCsvString()

  If Len(PaymentMethodPks) <> 0 Then
    ' Initialise
    BankingDetailsCleared = True

    ' Build query
    With sqb
      .Clear()
      .Table = "BankTransaction"
      .Fields.AddList("Pk,BankingDetails,Timestamp")

      With .SqlWhere
        .AppendComparisonDate("Date", "<", finBL.TimeZoneFunctions.GetCurrentDatabaseDate().AddDays(-14))
        .AppendComparisonNotNull("BankingDetails")
        .AppendComparisonInteger("PrintedStatus", "<>", isefinBankTransactionPrintedStatus.NotPrinted)
        .AppendRange("PaymentMethodPk", PaymentMethodPks, iseRangeDataType.Integer)
      End With
    End With

    ' Load Bank Transactions
    If sqb.ExecuteDisconnectedDataReader(dr, 0, finBL.Settings.DatabaseTimeoutSecondsLong) Then
      With dr
        ' Loop through Bank Transactions
        Do While .Read()
          ' Get Banking Details
          If BankingDetails.FromXmlString(finBL.Database.GetFieldString(!BankingDetails)) Then
            ' Check Expiry Date and Card Security Code have been cleared
            If BankingDetails.CardExpiryDate <> Nothing OrElse Len(BankingDetails.CardSecurityCode) <> 0 Then
              BankingDetailsCleared = False
              Exit Do
            End If
          Else
            ' Ignore (failed to get details from XML)
          End If
        Loop
      End With

      ' Close Datareader
      finBL.Database.DataReaderClose(dr)

      If Not BankingDetailsCleared Then
        With SummaryTableMedium.Rows.Add().Cells()
          .AddText("")
          .AddText("Banking details more than 14 days old have not had their Credit Card Expiry and CSC details purged. This can be done via 'Tools -> Database -> Database Purge', selecting 'Purge Bank Accounts', and 'Clear Credit Card Expiry and CSC Details'.")
        End With
      End If
    End If
  End If

  ' Add Summary Tables
  If SummaryTableMedium.HasData(True) Then SummaryTables.Add("Medium", SummaryTableMedium)

  Return SummaryTables

End Function

''' <summary>
'''  Compares finPOWER Connect versions.
''' </summary>
Private Function CompareVersions(latestVersion As String) As Integer

  Dim Current As Integer
  Dim CurrentVersionParts As ISList
  Dim i As Integer
  Dim Latest As Integer
  Dim LatestVersionParts As ISList

  ' Initialise
  CurrentVersionParts = finBL.Runtime.CreateList()
  LatestVersionParts = finBL.Runtime.CreateList()

  ' Load
  CurrentVersionParts.Delimiter = "."
  CurrentVersionParts.FromDelimitedString(finBL.VersionMajorMinorBuild)
  LatestVersionParts.Delimiter = "."
  LatestVersionParts.FromDelimitedString(latestVersion)

  ' Compare
  If CurrentVersionParts.Count = LatestVersionParts.Count Then
    For i = 0 To currentVersionParts.Count - 1
      Current = CInt(CurrentVersionParts(i))
      Latest = CInt(LatestVersionParts(i))

      If Current > Latest Then
        Return 1
      ElseIf Current < Latest Then
        Return -1
      End If
    Next

    ' Versions match
    Return 0
  Else
    Return -2
  End If

End Function

''' <summary>
'''  Retrieves the latest version number of the finPOWER Connect Business Layer.
''' </summary>
Private Function GetLatestVersion(ByRef version As String) As Boolean

  Dim Success As Boolean
  Dim Url As String

  ' Assume Success
  Success = True

  ' Initialise ByRef Parameters
  version = ""

  ' Url
  Url = "https://www.intersoft.co.nz/Api/ISInfo/GetCurrentReleaseVersion?productId=finPOWER Connect"

  ' Get Version
  Try
    With New WebClient()
      version = .DownloadString(Url)
      .Dispose()
    End With

    ' Strip out surrounding quotes from version
    If Left(version, 1) = Chr(34) Then version = Mid(version, 2, Len(version) - 2)

    ' Remove leading zeros
    version = Replace(version, ".0", ".")
  Catch ex As Exception
    Success = False
  End Try

  Return Success

End Function
