' SummaryPage2_PCIDSSComplianceReport
Option Explicit On
Option Strict On

' #################################################################
' PCI DSS Report
'
' Add the following text to KB articles related to this script:
' Note: This summary page is not currently accessible for customisation.
'
' Version: 1.00 (09/06/2021)
'
' Usage: Run from User Security
' #################################################################

' Objects

' Other
Private FormKey As String
Private FormPageKey As String
Private FormTabKey As String

' Constants
Private Const R8_1_4_INACTIVE_DAYS As Integer = 90
Private Const R8_1_6_LOGIN_ATTEMPTS As Integer = 6
Private Const R8_1_7_LOCKOUT_MINUTES As Integer = 30
Private Const R8_1_8_AUTOLOCK_IDLE_MINUTES As Integer = 15
Private Const R8_2_3_PASSWORD_MINIMUM_LENGTH As Integer = 7
Private Const R8_2_4_PASSWORD_CHANGE_DAYS As Integer = 90
Private Const R8_2_5_PASSWORD_HISTORY As Integer = 4

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

  ' Get Form Information
  FormKey = ScriptInfo.FormKey
  FormPageKey = ScriptInfo.FormPageKey
  FormTabKey = ScriptInfo.FormTabKey

  ' Handle Events
  Select Case eventId
    Case ""
      ' Main Event, i.e., Return main page content
      Main = GetPage(text)
  End Select

End Function

Public Function GetPage(ByRef html As String) As Boolean

  Dim ApplicationShortcut As ISApplicationShortcut
  Dim HeadingStyle As isefinSummaryPageBlockHeadingStyle
  Dim Ok As Boolean
  Dim sb As finHtmlSummaryPage2StringBuilder
  Dim SummaryTables As ISSummaryTables

  ' Assume Success
  Ok = True

  ' Initialise
  sb = finBL.CreateHtmlSummaryPage2StringBuilder()

  ' Build Application Shortcut to PCI DSS Website
  ApplicationShortcut = finBL.CreateApplicationShortcutExternal("https://www.pcisecuritystandards.org/")

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

  ' Administrator only report
  If finBL.CurrentUser.IsAdministrator Then
    ' Heading
    sb.AppendH1("finPOWER Connect PCI DSS Compliance Report")
    sb.AppendLine(String.Format("<p>Printed on {0}</p>", finBL.TimeZoneFunctions.GetCurrentLocalDateTime()))
    sb.AppendLine("<p>Generated in accordance with version 3.2.1 of the standards.</p>")
    sb.AppendLine("<p>For more information on the Payment Card Industry (PCI) Data Security Standard (DSS) see the PCI Security Standards website <a href='" & ApplicationShortcut.ToUrlString(True) & "'>www.pcisecuritystandards.org</a>.</p>")
    sb.AppendLine("<div style='background-color:#E7F3FD;border-radius:8px;padding:8px;margin-bottom:16px;'><h3 style='margin:0;'>Disclaimer</h3><p style='margin-bottom:0px; margin:0'>This report is provided without warranty of any kind, and Intersoft accepts no liability for any decisions made on the basis of this Report. You should seek your own advice on PCI DSS compliance.</p></div>")

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

    ' 8.1.4
    SummaryTables = GetSection_8_1_4(HeadingStyle)
    sb.BlockBegin("Section 8.1.4", String.Format("Remove / Disable inactive User accounts within {0} days.", R8_1_4_INACTIVE_DAYS), HeadingStyle, True)
    sb.SummaryTablesAppend(SummaryTables)
    sb.BlockEnd()

    ' 8.1.6
    SummaryTables = GetSection_8_1_6(HeadingStyle)
    sb.BlockBegin("Section 8.1.6", String.Format("Lock Users out after {0} failed login attempts.", R8_1_6_LOGIN_ATTEMPTS), HeadingStyle, True)
    sb.SummaryTablesAppend(SummaryTables)
    sb.BlockEnd()

    ' 8.1.7
    SummaryTables = GetSection_8_1_7(HeadingStyle)
    sb.BlockBegin("Section 8.1.7", String.Format("Lock Users out for a minimum of {0} minutes after {1} failed login attempts.", R8_1_7_LOCKOUT_MINUTES, R8_1_6_LOGIN_ATTEMPTS), HeadingStyle, True)
    sb.SummaryTablesAppend(SummaryTables)
    sb.BlockEnd()

    ' 8.1.8
    SummaryTables = GetSection_8_1_8(HeadingStyle)
    sb.BlockBegin("Section 8.1.8", String.Format("Automatically lock {0} if left idle for {1} minutes.", finBL.AppTitle, R8_1_8_AUTOLOCK_IDLE_MINUTES), HeadingStyle, True)
    sb.SummaryTablesAppend(SummaryTables)
    sb.BlockEnd()

    ' 8.2.3
    SummaryTables = GetSection_8_2_3(HeadingStyle)
    sb.BlockBegin("Section 8.2.3", String.Format("Minimum Password length must be at least {0} characters and must contain both numeric and alphabetic characters.", R8_2_3_PASSWORD_MINIMUM_LENGTH), HeadingStyle, True)
    sb.SummaryTablesAppend(SummaryTables)
    sb.BlockEnd()

    ' 8.2.4
    SummaryTables = GetSection_8_2_4(HeadingStyle)
    sb.BlockBegin("Section 8.2.4", String.Format("Passwords should be changed at least once every {0} days.", R8_2_4_PASSWORD_CHANGE_DAYS), HeadingStyle, True)
    sb.SummaryTablesAppend(SummaryTables)
    sb.BlockEnd()

    ' 8.2.5
    SummaryTables = GetSection_8_2_5(HeadingStyle)
    sb.BlockBegin("Section 8.2.5", String.Format("The last {0} Passwords cannot be reused.", R8_2_5_PASSWORD_HISTORY), HeadingStyle, True)
    sb.SummaryTablesAppend(SummaryTables)
    sb.BlockEnd()

    ' 8.2.6
    SummaryTables = GetSection_8_2_6(HeadingStyle)
    sb.BlockBegin("Section 8.2.6", "First-time use and reset passwords must be changed after first login.", HeadingStyle, True)
    sb.SummaryTablesAppend(SummaryTables)
    sb.BlockEnd()

    ' 8.3 / 8.3.1
    '#TODO: Requires finC change to support Multi-Factor

    ' 8.3.2
    If finBL.Settings.AddOns.WebAutomation AndAlso finBL.Settings.AddOns.WebInterface Then
      SummaryTables = GetSection_8_3_2(HeadingStyle)
      sb.BlockBegin("Section 8.3.2", "Enforce Multi-Factor Authentication for finPOWER Connect Cloud.", HeadingStyle, True)
      sb.SummaryTablesAppend(SummaryTables)
      sb.BlockEnd()
    End If

    ' 8.7
    SummaryTables = GetSection_8_7_0(HeadingStyle)
    sb.BlockBegin("Section 8.7.0", "Only database Administrators should have access to directly query the Database.", HeadingStyle, True)
    sb.SummaryTablesAppend(SummaryTables)
    sb.BlockEnd()

    ' Columns
    sb.ColumnEnd()
    sb.SectionColumnsEnd()
  Else
    sb.SectionColumnsAddQuickBlock("Summary", "{{warning|You do not have permission to view the PCI DSS Compliance Report.}}", "100%")
  End If

  ' Finalise HTML
  sb.HtmlFinalise()

  ' Resolve Templates
  html = sb.ToString(True)

  Return Ok

End Function

''' <summary>
'''  Section 8.1.4.
''' </summary>
Private Function GetSection_8_1_4(ByRef headingStyle As isefinSummaryPageBlockHeadingStyle) As ISSummaryTables

  Dim LastLogin As String
  Dim row As DataRow
  Dim SummaryTable As ISSummaryTable
  Dim SummaryTables As ISSummaryTables
  Dim UserId As String
  Dim UsersDt As DataTable

  ' Initialise ByRef Parameters
  headingStyle = isefinSummaryPageBlockHeadingStyle.Normal

  ' Initialise
  SummaryTables = finBL.CreateSummaryTables()

  ' Get Users
  If GetSection_8_1_4_GetUsers(UsersDt) Then
    If UsersDt.Rows.Count = 0 Then
      SummaryTables.AddSummaryTableBlank("8.1.4", "{{icon|ok}} No Inactive Users", String.Format("All 'Active' Users have logged in at least once within the last {0} days.", R8_1_4_INACTIVE_DAYS))
    Else
      headingStyle = isefinSummaryPageBlockHeadingStyle.Warning
      SummaryTable = SummaryTables.CreateSummaryTableBlank("{{icon|cross}} Inactive Users found", String.Format("The following 'Active' Users have not logged in during the last {0} days.", R8_1_4_INACTIVE_DAYS))
      SummaryTable.TableClass = iseSummaryTableClass.TabularData

      ' Heading
      With SummaryTable.Rows.Add()
        .RowClass = iseSummaryTableRowClass.Header
        With .Cells
          .Add("User Id")
          .Add("Name")
          .Add("Last Login")
          .Add("Days ago")
        End With
      End With

      ' Users
      For Each row In UsersDt.Rows
        LastLogin = finBL.Database.GetFieldString(row!LastLogin)
        UserId = finBL.Database.GetFieldString(row!UserId)

        With SummaryTable.Rows.Add()
          If LastLogin = "Never" Then
            .RowClass = iseSummaryTableRowClass.Negative
          End If

          With .Cells
            .AddWiki("[[app://FormShow?form=Users&page=Login&id=" & UserId & "|" & UserId & "]]")
            .Add(finBL.Database.GetFieldString(row!Name))
            .AddText(LastLogin).TextAlign = iseSummaryTableCellTextAlign.Right
            .AddInteger(finBL.Database.GetFieldInteger(row!DaysSince), True).TextAlign = iseSummaryTableCellTextAlign.Right
          End With
        End With
      Next

      SummaryTables.Add("814_Users", SummaryTable)
    End If
  Else
    ' Ignore error
  End If

  Return SummaryTables

End Function

''' <summary>
'''  Retrieve List of Active Users without any login for the last 90 days
''' </summary>
Private Function GetSection_8_1_4_GetUsers(ByRef users As DataTable) As Boolean

  Dim DateToday As Date
  Dim LastLoginDate As Date
  Dim Success As Boolean
  Dim UserRO As finUserRO

  ' Assume Success
  Success = True

  ' Initialise
  users = New DataTable()

  ' Setup DataTable
  With users.Columns
    .Add("UserId", GetType(String))
    .Add("Name", GetType(String))
    .Add("LastLogin", GetType(String))
    .Add("DaysSince", GetType(Integer))
  End With

  ' Today
  DateToday = finBL.TimeZoneFunctions.GetCurrentDatabaseDate()

  ' Get Users
  For Each UserRO In finBL.Users
    With UserRO
      If .Active AndAlso Not .Deleted Then
        If .GetLastLoginDate(LastLoginDate) Then
          If LastLoginDate = Nothing Then
            users.Rows.Add(.UserId, .Name, "Never", 0)
          ElseIf LastLoginDate.AddDays(R8_1_4_INACTIVE_DAYS) < DateToday Then
            users.Rows.Add(.UserId, .Name, finBL.FormatDateLong(LastLoginDate), CInt(DateDiff(DateInterval.Day, LastLoginDate, DateToday)))
          End If
        Else
          Success = False
        End If
      End If
    End With

    ' Exit if error
    If Not Success Then Exit For
  Next

  ' Sort
  If Success Then
    users.DefaultView.Sort = "LastLogin ASC"
    users = users.DefaultView.ToTable()
  End If

  Return Success

End Function

''' <summary>
'''  Section 8.1.6.
''' </summary>
Private Function GetSection_8_1_6(ByRef headingStyle As isefinSummaryPageBlockHeadingStyle) As ISSummaryTables

  Dim AllowedLoginAttempts As Integer
  Dim dt As DataTable
  Dim row As DataRow
  Dim SummaryTable As ISSummaryTable
  Dim SummaryTables As ISSummaryTables
  Dim UserPolicyId As String
  Dim UserPolicyRO As ISUserPolicyRO

  ' Initialise ByRef Parameters
  headingStyle = isefinSummaryPageBlockHeadingStyle.Normal

  ' Initialise
  dt = New DataTable()
  SummaryTables = finBL.CreateSummaryTables()

  ' Columns
  With dt.Columns
    .Add("UserPolicyId", GetType(String))
    .Add("Description", GetType(String))
    .Add("AllowedLoginAttempts", GetType(Integer))
  End With

  ' Determine User Policies which do not meet the critieria
  For Each UserPolicyRO In finBL.UserPolicies
    With UserPolicyRO
      If .Active AndAlso .LoginLockoutAttempts > R8_1_6_LOGIN_ATTEMPTS OrElse .LoginLockoutAttempts = 0 Then
        dt.Rows.Add(.UserPolicyId, .Description, .LoginLockoutAttempts)
      End If
    End With
  Next

  ' Sort
  dt.DefaultView.Sort = "AllowedLoginAttempts"
  dt = dt.DefaultView.ToTable()

  ' Summary
  If dt.Rows.Count = 0 Then
    SummaryTables.AddSummaryTableBlank("8.1.6", "{{icon|ok}} No Invalid User Policies", String.Format("All 'Active' User Policies will lockout the User after {0} (or less) failed login attempts.", R8_1_6_LOGIN_ATTEMPTS))
  Else
    headingStyle = isefinSummaryPageBlockHeadingStyle.Warning
    SummaryTable = SummaryTables.CreateSummaryTableBlank("{{icon|cross}} Invalid User Policies found", String.Format("The following 'Active' User Policies allow more than {0} login attempts before locking the User out.", R8_1_6_LOGIN_ATTEMPTS))
    SummaryTable.TableClass = iseSummaryTableClass.TabularData

    ' Heading
    With SummaryTable.Rows.Add()
      .RowClass = iseSummaryTableRowClass.Header
      With .Cells
        .Add("User Policy Id")
        .Add("Description")
        .Add("Allowed Login Attempts")
      End With
    End With

    ' User Policies
    For Each row In dt.Rows
      AllowedLoginAttempts = finBL.Database.GetFieldInteger(row!AllowedLoginAttempts)
      UserPolicyId = finBL.Database.GetFieldString(row!UserPolicyId)

      With SummaryTable.Rows.Add()
        If AllowedLoginAttempts = 0 Then
          .RowClass = iseSummaryTableRowClass.Negative
        End If

        With .Cells
          .AddWiki("[[app://FormShow?form=UserPolicies&page=Password Policy&id=" & UserPolicyId & "|" & UserPolicyId & "]]")
          .Add(finBL.Database.GetFieldString(row!Description))

          If AllowedLoginAttempts = 0 Then
            .AddText("Not Restricted").TextAlign = iseSummaryTableCellTextAlign.Right
          Else
            .AddInteger(AllowedLoginAttempts)
          End If
        End With
      End With
    Next

    SummaryTables.Add("816_UserPolicies", SummaryTable)
  End If

  Return SummaryTables

End Function

''' <summary>
'''  Section 8.1.7.
''' </summary>
Private Function GetSection_8_1_7(ByRef headingStyle As isefinSummaryPageBlockHeadingStyle) As ISSummaryTables

  Dim dt As DataTable
  Dim LockoutMinutes As Integer
  Dim row As DataRow
  Dim SummaryTable As ISSummaryTable
  Dim SummaryTables As ISSummaryTables
  Dim UserPolicyId As String
  Dim UserPolicyRO As ISUserPolicyRO

  ' Initialise ByRef Parameters
  headingStyle = isefinSummaryPageBlockHeadingStyle.Normal

  ' Initialise
  dt = New DataTable()
  SummaryTables = finBL.CreateSummaryTables()

  ' Columns
  With dt.Columns
    .Add("UserPolicyId", GetType(String))
    .Add("Description", GetType(String))
    .Add("LockoutMinutes", GetType(Integer))
  End With

  ' Determine User Policies which do not meet the critieria
  For Each UserPolicyRO In finBL.UserPolicies
    With UserPolicyRO
      If .Active AndAlso .LoginLockoutMinutes < R8_1_7_LOCKOUT_MINUTES Then
        dt.Rows.Add(.UserPolicyId, .Description, .LoginLockoutMinutes)
      End If
    End With
  Next

  ' Summary
  If dt.Rows.Count = 0 Then
    SummaryTables.AddSummaryTableBlank("8.1.7", "{{icon|ok}} No Invalid User Policies", String.Format("All 'Active' User Policies have a minimum lockout period of at least {0} minutes.", R8_1_7_LOCKOUT_MINUTES))
  Else
    headingStyle = isefinSummaryPageBlockHeadingStyle.Warning
    SummaryTable = SummaryTables.CreateSummaryTableBlank("{{icon|cross}} Invalid User Policies found", String.Format("The following 'Active' User Policies allow a lockout period of less than {0} minutes.", R8_1_7_LOCKOUT_MINUTES))
    SummaryTable.TableClass = iseSummaryTableClass.TabularData

    ' Heading
    With SummaryTable.Rows.Add()
      .RowClass = iseSummaryTableRowClass.Header
      With .Cells
        .Add("User Policy Id")
        .Add("Description")
        .Add("Lockout Minutes")
      End With
    End With

    ' User Policies
    For Each row In dt.Rows
      UserPolicyId = finBL.Database.GetFieldString(row!UserPolicyId)
      LockoutMinutes = finBL.Database.GetFieldInteger(row!LockoutMinutes)

      With SummaryTable.Rows.Add()
        If LockoutMinutes = 0 Then
          .RowClass = iseSummaryTableRowClass.Negative
        End If

        With .Cells
          .AddWiki("[[app://FormShow?form=UserPolicies&page=Password Policy&id=" & UserPolicyId & "|" & UserPolicyId & "]]")
          .Add(finBL.Database.GetFieldString(row!Description))

          If LockoutMinutes = 0 Then
            .AddText("Not Used").TextAlign = iseSummaryTableCellTextAlign.Right
          Else
            .AddInteger(LockoutMinutes)
          End If
        End With
      End With
    Next

    SummaryTables.Add("817_UserPolicies", SummaryTable)
  End If

  Return SummaryTables

End Function

''' <summary>
'''  Section 8.1.8.
''' </summary>
Private Function GetSection_8_1_8(ByRef headingStyle As isefinSummaryPageBlockHeadingStyle) As ISSummaryTables

  Dim AutolockMinutes As Integer
  Dim dt As DataTable
  Dim row As DataRow
  Dim SummaryTable As ISSummaryTable
  Dim SummaryTables As ISSummaryTables
  Dim UserPolicyId As String
  Dim UserPolicyRO As ISUserPolicyRO

  ' Initialise ByRef Parameters
  headingStyle = isefinSummaryPageBlockHeadingStyle.Normal

  ' Initialise
  dt = New DataTable()
  SummaryTables = finBL.CreateSummaryTables()

  ' Columns
  With dt.Columns
    .Add("UserPolicyId", GetType(String))
    .Add("Description", GetType(String))
    .Add("AutolockMinutes", GetType(Integer))
  End With

  ' Determine User Policies which do not meet the critieria
  For Each UserPolicyRO In finBL.UserPolicies
    With UserPolicyRO
      If .Active AndAlso (.AutoLockMinutes = 0 OrElse .AutoLockMinutes > R8_1_8_AUTOLOCK_IDLE_MINUTES) Then
        dt.Rows.Add(.UserPolicyId, .Description, .AutoLockMinutes)
      End If
    End With
  Next

  ' Summary
  If dt.Rows.Count = 0 Then
    SummaryTables.AddSummaryTableBlank("8.1.8", "{{icon|ok}} No Invalid User Policies", String.Format("All 'Active' User Policies are using automatic application lock, and have it set to {0} minutes or less.", R8_1_8_AUTOLOCK_IDLE_MINUTES))
  Else
    headingStyle = isefinSummaryPageBlockHeadingStyle.Warning
    SummaryTable = SummaryTables.CreateSummaryTableBlank("{{icon|cross}} Invalid User Policies found", String.Format("The following 'Active' User Policies are either not using automatic application lock, or have it set to longer than {0} minutes.", R8_1_8_AUTOLOCK_IDLE_MINUTES))
    SummaryTable.TableClass = iseSummaryTableClass.TabularData

    ' Heading
    With SummaryTable.Rows.Add()
      .RowClass = iseSummaryTableRowClass.Header
      With .Cells
        .Add("User Policy Id")
        .Add("Description")
        .Add("Auto-Lock Minutes")
      End With
    End With

    ' User Policies
    For Each row In dt.Rows
      AutolockMinutes = finBL.Database.GetFieldInteger(row!AutolockMinutes)
      UserPolicyId = finBL.Database.GetFieldString(row!UserPolicyId)

      With SummaryTable.Rows.Add()
        If AutolockMinutes = 0 Then
          .RowClass = iseSummaryTableRowClass.Negative
        End If

        With .Cells
          .AddWiki("[[app://FormShow?form=UserPolicies&id=" & UserPolicyId & "|" & UserPolicyId & "]]")
          .Add(finBL.Database.GetFieldString(row!Description))

          If AutolockMinutes = 0 Then
            .AddText("Not Used").TextAlign = iseSummaryTableCellTextAlign.Right
          Else
            .AddInteger(AutolockMinutes)
          End If
        End With
      End With
    Next

    SummaryTables.Add("818_UserPolicies", SummaryTable)
  End If

  Return SummaryTables

End Function

''' <summary>
'''  Section 8.2.3.
''' </summary>
Private Function GetSection_8_2_3(ByRef headingStyle As isefinSummaryPageBlockHeadingStyle) As ISSummaryTables

  Dim dt As DataTable
  Dim row As DataRow
  Dim SummaryTable As ISSummaryTable
  Dim SummaryTables As ISSummaryTables
  Dim UserPolicyId As String
  Dim UserPolicyRO As ISUserPolicyRO

  ' Initialise ByRef Parameters
  headingStyle = isefinSummaryPageBlockHeadingStyle.Normal

  ' Initialise
  dt = New DataTable()
  SummaryTables = finBL.CreateSummaryTables()

  ' Columns
  With dt.Columns
    .Add("UserPolicyId", GetType(String))
    .Add("Description", GetType(String))
    .Add("MinimumPasswordLength", GetType(Integer))
    .Add("ForceStrongPasswords", GetType(Boolean))
  End With

  ' Determine User Policies which do not meet the critieria
  For Each UserPolicyRO In finBL.UserPolicies
    With UserPolicyRO
      If .Active AndAlso (.PasswordMinLength < 7 OrElse False) Then
        dt.Rows.Add(.UserPolicyId, .Description, .PasswordMinLength, False)
      End If
    End With
  Next

  ' Summary
  If dt.Rows.Count = 0 Then
    SummaryTables.AddSummaryTableBlank("8.2.3", "{{icon|ok}} No Invalid User Policies", String.Format("All 'Active' User Policies have a minimum Password length of {0} (or more) and are enforcing strong passwords.", R8_2_3_PASSWORD_MINIMUM_LENGTH))
  Else
    headingStyle = isefinSummaryPageBlockHeadingStyle.Warning
    SummaryTable = SummaryTables.CreateSummaryTableBlank("{{icon|cross}} Invalid User Policies found", String.Format("The following 'Active' User Policies have a minimum Password length less than {0} characters, or do not enforce strong passwords.", R8_2_3_PASSWORD_MINIMUM_LENGTH))
    SummaryTable.TableClass = iseSummaryTableClass.TabularData

    ' Heading
    With SummaryTable.Rows.Add()
      .RowClass = iseSummaryTableRowClass.Header
      With .Cells
        .Add("User Policy Id")
        .Add("Description")
        .Add("Minimum Length")
        .Add("Enforcing Strong?")
      End With
    End With

    ' User Policies
    For Each row In dt.Rows
      UserPolicyId = finBL.Database.GetFieldString(row!UserPolicyId)

      With SummaryTable.Rows.Add().Cells
        .AddWiki("[[app://FormShow?form=UserPolicies&page=Password Policy&id=" & UserPolicyId & "|" & UserPolicyId & "]]")
        .Add(finBL.Database.GetFieldString(row!Description))
        .AddInteger(finBL.Database.GetFieldInteger(row!MinimumPasswordLength))
        .AddTick(finBL.Database.GetFieldIntegerBoolean(row!ForceStrongPasswords), True, True)
      End With
    Next

    SummaryTables.Add("823_UserPolicies", SummaryTable)
  End If

  Return SummaryTables

End Function

''' <summary>
'''  Section 8.2.4.
''' </summary>
Private Function GetSection_8_2_4(ByRef headingStyle As isefinSummaryPageBlockHeadingStyle) As ISSummaryTables

  Dim DaysSinceChange As Integer
  Dim dt As DataTable
  Dim PasswordUtcDate As Date
  Dim row As DataRow
  Dim sqb As ISSelectQueryBuilder
  Dim SummaryTable As ISSummaryTable
  Dim SummaryTables As ISSummaryTables
  Dim UserId As String
  Dim UserLevel As String

  ' Initialise ByRef Parameters
  headingStyle = isefinSummaryPageBlockHeadingStyle.Normal

  ' Initialise
  SummaryTables = finBL.CreateSummaryTables()
  sqb = finBL.Database.CreateSelectQueryBuilder()

  ' Build Query
  With sqb
    .Table = "User"
    .Fields.AddList("UserId,PasswordUtcDate")

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

    ' Order By
    With .OrderByFields
      .Add("PasswordUtcDate")
    End With
  End With

  ' Execute
  If sqb.ExecuteDataTable(dt) Then
    If dt.Rows.Count = 0 Then
      SummaryTables.AddSummaryTableBlank("8.2.4", "{{icon|ok}} No old Passwords", String.Format("All 'Active' Users have had their Passwords changed within the last {0} days.", R8_2_4_PASSWORD_CHANGE_DAYS))
    Else
      headingStyle = isefinSummaryPageBlockHeadingStyle.Warning
      SummaryTable = SummaryTables.CreateSummaryTableBlank("{{icon|cross}} Old Passwords found", String.Format("The following 'Active' Users have not changed their Password in over {0} days.", R8_2_4_PASSWORD_CHANGE_DAYS))
      SummaryTable.TableClass = iseSummaryTableClass.TabularData

      ' Heading
      With SummaryTable.Rows.Add()
        .RowClass = iseSummaryTableRowClass.Header
        With .Cells
          .Add("User Id")
          .Add("Name")
          .Add("Level")
          .Add("Days since Password change")
        End With
      End With

      ' Users
      For Each row In dt.Rows
        UserId = finBL.Database.GetFieldString(row!UserId)
        PasswordUtcDate = finBL.Database.GetFieldUtcDate(row!PasswordUtcDate)

        ' User Level
        Select Case finBL.Users(UserId).Level
          Case iseUserLevel.Administrator: UserLevel = "Administrator"
          Case iseUserLevel.UserAdministrator: UserLevel = "User Administrator"
          Case Else: UserLevel = ""
        End Select

        ' Get Days since Password change
        DaysSinceChange = CInt(DateDiff(DateInterval.Day, finBL.TimeZoneFunctions.ConvertUtcToDatabaseDateTime(PasswordUtcDate), finBL.TimeZoneFunctions.GetCurrentDatabaseDate()))

        With SummaryTable.Rows.Add()
          If Len(UserLevel) <> 0 Then
            .RowClass = iseSummaryTableRowClass.Negative
          End If

          With .Cells
            .AddWiki("[[app://FormShow?form=Users&page=Login&id=" & UserId & "|" & UserId & "]]")
            .AddText(finBL.Users(UserId).Name)
            .AddText(UserLevel)
            .AddInteger(DaysSinceChange)
          End With
        End With
      Next

      SummaryTables.Add("824_Users", SummaryTable)
    End If
  End If

  Return SummaryTables

End Function

''' <summary>
'''  Section 8.2.5.
''' </summary>
Private Function GetSection_8_2_5(ByRef headingStyle As isefinSummaryPageBlockHeadingStyle) As ISSummaryTables

  Dim dt As DataTable
  Dim row As DataRow
  Dim SummaryTable As ISSummaryTable
  Dim SummaryTables As ISSummaryTables
  Dim UserPolicyId As String
  Dim UserPolicyRO As ISUserPolicyRO

  ' Initialise ByRef Parameters
  headingStyle = isefinSummaryPageBlockHeadingStyle.Normal

  ' Initialise
  dt = New DataTable()
  SummaryTables = finBL.CreateSummaryTables()

  ' Columns
  With dt.Columns
    .Add("UserPolicyId", GetType(String))
    .Add("Description", GetType(String))
    .Add("PasswordReuse", GetType(Integer))
  End With

  ' Determine User Policies which do not meet the critieria
  For Each UserPolicyRO In finBL.UserPolicies
    With UserPolicyRO
      If .Active AndAlso .PasswordHistoryLength < R8_2_5_PASSWORD_HISTORY Then
        dt.Rows.Add(.UserPolicyId, .Description, .PasswordHistoryLength)
      End If
    End With
  Next

  ' Summary
  If dt.Rows.Count = 0 Then
    SummaryTables.AddSummaryTableBlank("8.2.5", "{{icon|ok}} No Invalid User Policies", String.Format("All 'Active' User Policies do not allow the last {0} Passwords to be reused.", R8_2_5_PASSWORD_HISTORY))
  Else
    headingStyle = isefinSummaryPageBlockHeadingStyle.Warning
    SummaryTable = SummaryTables.CreateSummaryTableBlank("{{icon|cross}} Invalid User Policies found", String.Format("The following 'Active' User Policies allow less than the last {0} Passwords to be reused.", R8_2_5_PASSWORD_HISTORY))
    SummaryTable.TableClass = iseSummaryTableClass.TabularData

    ' Heading
    With SummaryTable.Rows.Add()
      .RowClass = iseSummaryTableRowClass.Header
      With .Cells
        .Add("User Policy Id")
        .Add("Description")
        .Add("Password History")
      End With
    End With

    ' User Policies
    For Each row In dt.Rows
      UserPolicyId = finBL.Database.GetFieldString(row!UserPolicyId)

      With SummaryTable.Rows.Add().Cells
        .AddWiki("[[app://FormShow?form=UserPolicies&page=Password Policy&id=" & UserPolicyId & "|" & UserPolicyId & "]]")
        .Add(finBL.Database.GetFieldString(row!Description))
        .AddInteger(finBL.Database.GetFieldInteger(row!PasswordReuse))
      End With
    Next

    SummaryTables.Add("825_UserPolicies", SummaryTable)
  End If

  Return SummaryTables

End Function

''' <summary>
'''  Section 8.2.6.
''' </summary>
Private Function GetSection_8_2_6(ByRef headingStyle As isefinSummaryPageBlockHeadingStyle) As ISSummaryTables

  Dim SummaryTable As ISSummaryTable
  Dim SummaryTables As ISSummaryTables
  Dim UsersDt As DataTable
  Dim LastPasswordChange As Date
  Dim UserId As String
  Dim row As DataRow

  ' Initialise
  SummaryTables = finBL.CreateSummaryTables()

  ' Initialise ByRef Parameters
  headingStyle = isefinSummaryPageBlockHeadingStyle.Normal

  ' Get Users
  If GetSection_8_2_6_GetUsers(UsersDt) Then
    If UsersDt.Rows.Count = 0 Then
      SummaryTables.AddSummaryTableBlank("8.2.6", "{{icon|ok}} No Password changes required", "All 'Active' Users have valid Passwords which have been changed since an Administrator reset them.")
    Else
      headingStyle = isefinSummaryPageBlockHeadingStyle.Warning
      SummaryTable = SummaryTables.CreateSummaryTableBlank("{{icon|cross}} Password changes Required", "The following 'Active' Users have Passwords which have not been updated since an Administrator has reset them.")
      SummaryTable.TableClass = iseSummaryTableClass.TabularData

      ' Heading
      With SummaryTable.Rows.Add()
        .RowClass = iseSummaryTableRowClass.Header
        With .Cells
          .Add("User Id")
          .Add("Name")
          .Add("Last Login")
          .Add("Last Password Change")
          .Add("Force Change")
          .Add("Details")
        End With
      End With

      ' Users
      For Each row In UsersDt.Rows
        UserId = finBL.Database.GetFieldString(row!UserId)
        LastPasswordChange = finBL.Database.GetFieldDate(row!LastPasswordChange)

        With SummaryTable.Rows.Add()
          If LastPasswordChange = Nothing Then
            .RowClass = iseSummaryTableRowClass.Negative
          End If

          With .Cells
            .AddWiki("[[app://FormShow?form=Users&page=Login&id=" & UserId & "|" & UserId & "]]")
            .Add(finBL.Database.GetFieldString(row!Name))
            .AddDate(finBL.Database.GetFieldDate(row!LastLogin))
            .AddDate(LastPasswordChange)
            .AddTick(finBL.Database.GetFieldIntegerBoolean(row!ForcePasswordChange), True, True)
            .AddText(finBL.Database.GetFieldString(row!Details))
          End With
        End With
      Next

      SummaryTables.Add("826_Users", SummaryTable)
    End If
  End If

  Return SummaryTables

End Function

Private Function GetSection_8_2_6_GetUsers(ByRef users As DataTable) As Boolean

  Dim AdminPasswordChangeDate As Date
  Dim AuditLogs As DataTable
  Dim AuditLogType As iseAuditLogType
  Dim Details As String
  Dim LastLoginDate As Date
  Dim PasswordChangedByAdmin As Boolean
  Dim PasswordChangedByUser As Boolean
  Dim Row As DataRow
  Dim Success As Boolean
  Dim UserLoggedIn As Boolean
  Dim UserRO As finUserRO
  Dim Warning As String

  ' Assume Success
  Success = True

  ' Initialise
  users = New DataTable()

  ' Setup DataTable
  With users.Columns
    .Add("UserId", GetType(String))
    .Add("Name", GetType(String))
    .Add("LastLogin", GetType(Date))
    .Add("LastPasswordChange", GetType(Date))
    .Add("ForcePasswordChange", GetType(Boolean))
    .Add("Details", GetType(String))
  End With

  ' Find all Users with Admin password changes not flagged for immediate change
  For Each UserRO In finBL.Users
    ' Reset
    AdminPasswordChangeDate = Nothing
    LastLoginDate = Nothing
    PasswordChangedByAdmin = False
    PasswordChangedByUser = False
    UserLoggedIn = False
    Warning = ""

    If UserRO.Active AndAlso Not UserRO.Deleted Then
      ' Get Audit
      Success = GetSection_8_2_6_GetAuditForUser(UserRO.Pk, AuditLogs)

      If Success Then
        If AuditLogs.Rows.Count = 0 Then
          Warning = "User has never logged in."
        Else
          For Each Row In AuditLogs.Rows
            AuditLogType = DirectCast(finBL.Database.GetFieldEnum(Row!AuditLogType, GetType(iseAuditLogType)), iseAuditLogType)
            Details = finBL.Database.GetFieldString(Row!Details)

            ' An Administrator has updated the password
            If AuditLogType = iseAuditLogType.UserPasswordChanged AndAlso Len(Details) <> 0 Then
              AdminPasswordChangeDate = finBL.TimeZoneFunctions.ConvertUtcToDatabaseDateTime(finBL.Database.GetFieldUtcDate(Row!UtcDate))
              PasswordChangedByAdmin = True
            End If

            ' Check that the User has updated their password since an Admin changed it
            If AuditLogType = iseAuditLogType.UserPasswordChanged AndAlso PasswordChangedByAdmin AndAlso Len(Details) = 0 Then
              PasswordChangedByUser = True
            End If

            ' User Login
            If AuditLogType = iseAuditLogType.UserLogin Then
              LastLoginDate = finBL.TimeZoneFunctions.ConvertUtcToDatabaseDateTime(finBL.Database.GetFieldUtcDate(Row!UtcDate))

              ' Check if the User has logged in since an Admin changed their password
              If PasswordChangedByAdmin Then
                UserLoggedIn = True
              End If
            End If
          Next

          ' Validate
          If PasswordChangedByAdmin AndAlso Not PasswordChangedByUser AndAlso Not UserLoggedIn Then
            Warning = "User has not changed their password, nor logged in since an Administrator had reset their password."
          ElseIf PasswordChangedByAdmin AndAlso Not PasswordChangedByUser AndAlso UserLoggedIn Then
            Warning = "User has not changed their password, but has logged in since an Administrator had reset their password."
          End If
        End If
      End If

      ' Add to collection
      If Success AndAlso Len(Warning) <> 0 Then
        users.Rows.Add(UserRO.UserId, UserRO.Name, LastLoginDate, AdminPasswordChangeDate, UserRO.PasswordForceChange, Warning)
      End If
    End If

    ' Exit if error
    If Not Success Then Exit For
  Next

  Return Success

End Function

Private Function GetSection_8_2_6_GetAuditForUser(sourcePk As Integer,
                                                  ByRef dt As DataTable) As Boolean

  Dim Success As Boolean
  Dim sqb As ISSelectQueryBuilder

  ' Assume Success
  Success = True

  ' Initialise
  sqb = finBL.Database.CreateSelectQueryBuilder()

  ' Initialise ByRef Parameters
  dt = Nothing

  ' Build Query
  With sqb
    .Table = "ISAuditLog"
    .Fields.AddList("AuditLogType,UtcDate,Details")

    ' SQL Where
    With .SqlWhere
      .AppendComparisonInteger("SourcePk", "=", sourcePk)
      .AppendComparisonInteger("AuditLogClass", "=", iseAuditLogClass.Security)

      .BlockBegin(iseSqlWhereBuilderNestedBlockType.OrBlock)
      .AppendComparisonInteger("AuditLogType", "=", iseAuditLogType.UserLogin)
      .AppendComparisonInteger("AuditLogType", "=", iseAuditLogType.UserPasswordChanged)
      .BlockEnd()
    End With

    ' Order By
    .OrderByFields.Add("Pk", False)
  End With

  ' Execute
  Success = sqb.ExecuteDataTable(dt)

  Return Success

End Function

''' <summary>
'''  Section 8.3.2.
''' </summary>
Private Function GetSection_8_3_2(ByRef headingStyle As isefinSummaryPageBlockHeadingStyle) As ISSummaryTables

  Dim AuthMethod As isefinMultiFactorAuthenticationMethod
  Dim AuthMethodText As String
  Dim ExcludedRoles As String
  Dim List As ISList
  Dim RoleId As String
  Dim SummaryTable As ISSummaryTable
  Dim SummaryTables As ISSummaryTables

  ' Initialise ByRef Parameters
  headingStyle = isefinSummaryPageBlockHeadingStyle.Normal

  ' Initialise
  SummaryTables = finBL.CreateSummaryTables()

  ' Determine Rules
  With finBL.CloudConnectFunctions.CloudConnectSettings
    AuthMethod = .TwoFactorAuthenticationMethod
    AuthMethodText = .TwoFactorAuthenticationMethodText
    ExcludedRoles = .TwoFactorAuthenticationRolesExclude
  End With

  ' Summary
  If AuthMethod = isefinMultiFactorAuthenticationMethod.None Then
    headingStyle = isefinSummaryPageBlockHeadingStyle.Warning
    SummaryTables.AddSummaryTableBlank("8.3.2", "{{icon|cross}} Invalid finPOWER Connect Cloud Settings found", "This database is configured for finPOWER Connect Cloud access, but does not enforce Multi-Factor Authentication.")
  Else
    If Len(ExcludedRoles) = 0 Then
      SummaryTables.AddSummaryTableBlank("8.3.2", "{{icon|ok}} finPOWER Connect Cloud Settings valid", String.Format("This database is using the '{0}' method of Multi-Factor Authentication.", AuthMethodText))
    Else
      headingStyle = isefinSummaryPageBlockHeadingStyle.Warning
      SummaryTable = SummaryTables.CreateSummaryTableBlank("{{icon|cross}} Invalid finPOWER Connect Cloud Settings found", String.Format("This database is using the '{0}' method of Multi-Factor Authentication, however the following User Roles have been excluded.", AuthMethodText))
      SummaryTable.TableClass = iseSummaryTableClass.TabularData

      ' Heading
      With SummaryTable.Rows.Add()
        .RowClass = iseSummaryTableRowClass.Header
        With .Cells
          .Add("User Role Id")
          .Add("Description")
        End With
      End With

      ' Get Roles
      List = finBL.Runtime.CreateList()
      List.FromRangeString(ExcludedRoles)

      ' Populate Summary Table
      For Each RoleId In List
        With SummaryTable.Rows.Add().Cells
          .AddWiki("[[app://FormShow?form=Roles&id=" & RoleId & "|" & RoleId & "]]")
          .Add(finBL.Roles(RoleId).Description)
        End With
      Next

      SummaryTables.Add("832_UserRoles", SummaryTable)
    End If
  End If

  Return SummaryTables

End Function

''' <summary>
'''  Section 8.7.0.
''' </summary>
Private Function GetSection_8_7_0(ByRef headingStyle As isefinSummaryPageBlockHeadingStyle) As ISSummaryTables

  Dim Allowed As Boolean
  Dim dt As DataTable
  Dim row As DataRow
  Dim SummaryTable As ISSummaryTable
  Dim SummaryTables As ISSummaryTables
  Dim UserId As String
  Dim UserRO As finUserRO

  ' Initialise ByRef Parameters
  headingStyle = isefinSummaryPageBlockHeadingStyle.Normal

  ' Initialise
  dt = New DataTable()
  SummaryTables = finBL.CreateSummaryTables()

  ' Columns
  With dt.Columns
    .Add("UserId", GetType(String))
    .Add("Name", GetType(String))
  End With

  ' Find Users
  For Each UserRO In finBL.Users
    With UserRO
      If .Active AndAlso .Level <> iseUserLevel.Administrator Then
        If .PermissionAllow("Menu.Report.QueryExecute", Allowed) Then
          If Allowed Then
            dt.Rows.Add(.UserId, .Name)
          End If
        End If
      End If
    End With
  Next

  ' Summary
  If dt.Rows.Count = 0 Then
    SummaryTables.AddSummaryTableBlank("8.7.0", "{{icon|ok}} No Invalid Database access", "Only Administrators have access to directly query the database using the 'Run Query' wizard.")
  Else
    headingStyle = isefinSummaryPageBlockHeadingStyle.Warning
    SummaryTable = SummaryTables.CreateSummaryTableBlank("{{icon|cross}} Invalid Database access found", "The following non-Administrator Users have Permission to directly query the database using the 'Run Query' wizard.")
    SummaryTable.TableClass = iseSummaryTableClass.TabularData

    ' Heading
    With SummaryTable.Rows.Add()
      .RowClass = iseSummaryTableRowClass.Header
      With .Cells
        .Add("User Id")
        .Add("Name")
      End With
    End With

    ' Users
    For Each row In dt.Rows
      UserId = finBL.Database.GetFieldString(row!UserId)

      With SummaryTable.Rows.Add().Cells
        .AddWiki("[[app://FormShow?form=Users&page=Effective Permissions&id=" & UserId & "|" & UserId & "]]")
        .Add(finBL.Database.GetFieldString(row!Name))
      End With
    Next

    SummaryTables.Add("870_Users", SummaryTable)
  End If

  Return SummaryTables

End Function