GithubHelp home page GithubHelp logo

evotecit / pswinreporting Goto Github PK

View Code? Open in Web Editor NEW
693.0 34.0 67.0 9.1 MB

This PowerShell Module has multiple functionalities, but one of the signature features of this module is the ability to parse Security logs on Domain Controllers providing easy to use access to AD Events.

License: MIT License

PowerShell 100.00%
powershell powershell-module windows reporting activedirectory hacktoberfest

pswinreporting's Introduction

PSWinReporting

PSWinReporting is a little PowerShell module that solves the problem of monitoring and reading Windows Events. It allows you to set up monitoring of Domain Controllers (and from 2.X any other servers) for events that happen on them. By default, it comes with built-in Active Directory events supports, but since 2.0 you can configure it to monitor anything. You can set up reporting on any types of events and have emails delivered with a summary of hourly, daily, weekly, monthly, or quarterly changes. It also supports sending notifications to Microsoft Teams, Slack, and Discord. Make sure to go thru related articles as they have all the KNOW HOW which is quite useful if you want to get everything from this module.

The full project description is available on my website - Full project description.

Currently, there are 2 branches of PSWinReporting.

  • Legacy branch - available in PS Gallery as PSWinReporting - Install-Module -Name 'PSWinReporting' -Force
  • Master branch - available in PS Gallery as PSWinReportingV2 - Install-Module -Name 'PSWinReportingV2' -Force

I've decided that both PowerShell modules can coexist together, especially for scenarios for people who want to switch, but don't want to do it right away. This way, you can keep using old version as is, and slowly fix your other stuff, or use new Find-Events command. I've slightly renamed the commands for V2 release.

PSWinReportingV2 - Master Edition

Master edition is a complete rewrite and a new beginning. It provides the same functionality as Legacy 1.X version and then some more.

  • Ability to translate report and have it suite your needs
  • Ability to completely modify events monitoring
  • Ability to monitor any servers, for any events using simple to use schema
  • Ability to target multiple servers, computers or files at the same time

At this moment there is no documentation for PSWinReportingV2 except for those articles below. Feel free to explore Examples if you're eager to try the new version — otherwise fallback to PSWinReporting Legacy Edition.

Built-in Active Directory Reports

PSWinReporting comes with predefined, built-in reports. Those are for Find-Events. Those also come defined in example configuration script which you can use straight away after verifying everything is as per your requirement.

  • ADComputerChangesDetailed
  • ADComputerCreatedChanged
  • ADComputerDeleted
  • ADGroupChanges
  • ADGroupChangesDetailed
  • ADGroupCreateDelete
  • ADGroupEnumeration
  • ADGroupMembershipChanges
  • ADGroupPolicyChanges
  • ADLogsClearedOther
  • ADLogsClearedSecurity
  • ADUserChanges
  • ADUserChangesDetailed
  • ADUserLockouts
  • ADUserLogon
  • ADUserLogonKerberos
  • ADUserStatus
  • ADUserUnlocked
  • ADOrganizationalUnitChangesDetailed (added in 2.0.10)
  • OSStartupShutdownCrash (added in 2.0.12) - covers startup, shutdown and crashes - probably needs some work on the engine later on to allow field merging
  • OSCrash (added in 2.0.12) - covers system crashes
  • NetworkAccessAuthenticationPolicy (added in 2.0.12) - covers authorizations approved/denied for WIFI and ETHERNET

Built-in Reporting Times

PSWinReporting comes with predefined report times. This means you can use True/False to enable/disable period. In case of Find-Events, you can use defined times (checked only) from DatesRange parameter.

  • CurrentDay
  • CurrentDayMinusDayX
  • CurrentDayMinuxDaysX
  • CurrentHour
  • CurrentMonth
  • CurrentQuarter
  • CustomDate
  • Everything
  • Last14days
  • Last3days
  • Last7days
  • OnDay
  • PastDay
  • PastHour
  • PastMonth
  • PastQuarter

Of course, you can also define DateFrom, DateTo parameters for custom use when using Find-Events command.

PSWinReporting - Legacy Edition

Legacy edition will continue it's life as 1.X.X. If you want to keep on using it, feel free, but it's highly encouraged to use 2.x.x when it's fully functional with all features. Code is available as Legacy Branch. Following links can help in understanding how it works and how to set it up:

Following AD Events are supported:

  • Group create, delete, modify (Who / When / What)
  • Group membership changes (Who / When / What)
  • User changes (Who / When / What)
  • User created / deleted (Who / When)
  • User password changes (Who / When)
  • User lockouts (Who / When / Where)
  • Computer Created / Modified (Who / When / Where)
  • Computer Deleted (Who / When / Where)
  • Event Log Backup (Who / When)
  • Event Log Clear (Who / When)

Features:

  • Support for Event Forwarding - monitoring one event log instead of scanning all domain controllers
  • Support for Microsoft Teams - Sending events as they happen to Microsoft Teams (only supported when forwarders are in use)
  • Support for Slack - Sending events as they happen to Slack (only supported when forwarders are in use)
  • Support for Microsoft SQL - Sending events directly to SQL (some people prefer it that way)
  • Support for backing up old archived logs (moves logs from Domain Controllers into chosen place)
  • Support for re-scanning logs from files - a way to recheck your logs for missing information

Example - Script running

image

Example - Email Report

image

Example - Microsoft Teams

image

Example - Slack

image

pswinreporting's People

Contributors

0xflotus avatar ferwe avatar przemyslawklys avatar snd3r avatar

Stargazers

 avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar

Watchers

 avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar

pswinreporting's Issues

Prerequisites for reporting

Hi,

This is very very nice script and thanks for this! Maybe I missed but is there a documentation what I need to configure in my DC logging settings before I start using this?

Group Policy Changes

Currently, Group Policy changes are not working. They actually cover a wide range of changes including modifications to fields. For example, when a user field such as Description is changed it's logged as part of User Changes Events, but also on a more granular level on Group Policy changes (hence naming is incorrect).

This needs to split into a couple of other "event group types".

Save to SQL

Ability to save report to SQL directly, as discussed in #3

Unable to run script

PSWordMain.ps1 is returning the below error when running.


"Exception calling "SaveAs" with "1" Argument(s): "Access to the path 'C:\Users%username%\Desktop' is denied." At C:\Program Files\WindowsPowerShell\Modules\PSWriteWord\0.4.8.1\Public\PSWordMain.ps1:49 char:9

  • $WordDocument.SaveAs($filepath)
  • CategoryInfo NotSpecified (:) [] MethodInvocationException
  • FullyQualifiedErrorId : UnauthorizedAccessException

Figured it was just a permissions issue, so I ran it through PsExec as system and that still returned the same error. Tried to edit PSWordMain to save instead of saveas, but I'm sure I did it wrong, because it still didn't work.

Documentation Update

Hi,

I'm not really new to PowerShell, I consider myself fairly knowledgeable, but have no idea how to configure this. Would it be possible to create a true getting started guide? I just want to monitor group membership, but could see many of these reporting components being helpful.

Unclear: how to start SQL export

Hi!
I have no clue how to start the SQL export after the reporting has finished.
"Start-AdReporting" generates my Excel sheet and sends me an email, but how do fill the event data to my SQL db?
I have added

Notifications = @{ MicrosoftTeams = @{ Use = $false TeamsID = '' } Slack = @{ Use = $false Channel = '#general' Uri = "" } MSSQL = @{ Use = $true SqlServer = 'DBSERVERNAME' SqlDatabase = 'SLM-Test' SqlTable = 'dbo.[Events]' # Left side is data in PSWinReporting. Right Side is ColumnName in SQL # Changing makes sense only for right side... SqlTableCreate = $true SqlTableAlterIfNeeded = $true SqlTableMapping = [ordered] @{ 'Event ID' = 'EventID,[int]' 'Who' = 'EventWho' 'When' = 'EventWhen,[datetime]' 'Record ID' = 'EventRecordID,[bigint]' 'Domain Controller' = 'DomainController' 'Action' = 'Action' 'Group Name' = 'GroupName' 'User Affected' = 'UserAffected' 'Member Name' = 'MemberName' 'Computer Lockout On' = 'ComputerLockoutOn' 'Reported By' = 'ReportedBy' 'SamAccountName' = 'SamAccountName' 'Display Name' = 'DisplayName' 'UserPrincipalName' = 'UserPrincipalName' 'Home Directory' = 'HomeDirectory' 'Home Path' = 'HomePath' 'Script Path' = 'ScriptPath' 'Profile Path' = 'ProfilePath' 'User Workstation' = 'UserWorkstation' 'Password Last Set' = 'PasswordLastSet,[datetime]' 'Account Expires' = 'AccountExpires,[datetime]' 'Primary Group Id' = 'PrimaryGroupId' 'Allowed To Delegate To' = 'AllowedToDelegateTo' 'Old Uac Value' = 'OldUacValue' 'New Uac Value' = 'NewUacValue' 'User Account Control' = 'UserAccountControl' 'User Parameters' = 'UserParameters' 'Sid History' = 'SidHistory' 'Logon Hours' = 'LogonHours' 'OperationType' = 'OperationType' 'Message' = 'Message' 'Backup Path' = 'BackupPath' 'Log Type' = 'LogType' 'AddedWhen' = 'EventAdded,[datetime],null' # ColumnsToTrack when it was added to database and by who / not part of event 'AddedWho' = 'EventAddedWho' # ColumnsToTrack when it was added to database and by who / not part of event } } }

to my script, but how do I trigger this?

Regards
Robert

Events for Lockouts are duplicated on PDC and other DC's

When lockout happens it often happens that lockout is reported on one DC and then transferred to PDC. This means 2 events for 1 real event.

Maybe some kind of duplicate checking - if Event ID, User, Computer, Action, and only RecordID/Controller doesn't match merge events.

DCs still being scanned even when using forwarding server

I've gone through the effort to set up Event Forwarding and have verified that it's working. I have a ton of events coming in, all is well there.

However, when I set the script to use forwarding by adjusting the $false variable to $true, I'm noticing that my DCs are still being scanned and thus the script is still taking a good amount of time to run.

 Servers           = @{
            UseForwarders   = $true # if $true skips Automatic/OnlyPDC/DC for reading logs. However it uses Automatic to deliver size of logs so keep Automatic to $true
            ForwardServer   = $ENV:COMPUTERNAME
            ForwardEventLog = 'ForwardedEvents'

            UseDirectScan   = $true
            Automatic       = $true
            OnlyPDC         = $false
            DC              = ''
        }

Any ideas what might be happening here?

I apologize if this is the wrong way to report this, this is my first time using GitHub.

Thanks very much

SQL Credentials

Possible to pass through credentials to save to SQL server?
I have a sql server not on domain, and in another domain that would need its own credentials passed.

Old $ReportTimes would error out on Test-Key checks.

Following is old setup

$ReportTimes = @{
    # Report Per Hour
    PastHour             = $false # if it's 23:22 it will report 22:00 till 23:00
    CurrentHour          = $false # if it's 23:22 it will report 23:00 till 00:00
    # Report Per Day
    PastDay              = $false # if it's 1.04.2018 it will report 31.03.2018 00:00:00 till 01.04.2018 00:00:00
    CurrentDay           = $false # if it's 1.04.2018 05:22 it will report 1.04.2018 00:00:00 till 01.04.2018 00:00:00
    # Report Per Week
    OnDay                = @{
        Enabled = $false
        Days    = 'Monday'#, 'Tuesday'
    }
    # Report Per Month
    PastMonth            = @{
        Enabled = $true # checks for 1st day of the month - won't run on any other day unless used force
        Force   = $true  # if true - runs always ...
    }
    CurrentMonth         = $true

    # Report Per Quarter
    PastQuarter          = @{
        Enabled = $false # checks for 1st day fo the quarter - won't run on any other day
        Force   = $false
    }
    CurrentQuarter       = $false
    # Report Custom
    CurrentDayMinusDayX  = @{
        Enabled = $false
        Days    = 7    # goes back X days and shows just 1 day
    }
    CurrentDayMinuxDaysX = @{
        Enabled = $false
        Days    = 3 # goes back X days and shows X number of days till Today
    }
    CustomDate           = @{
        Enabled  = $false
        DateFrom = get-date -Year 2018 -Month 03 -Day 19
        DateTo   = get-date -Year 2018 -Month 03 -Day 23
    }
}

Empty worksheets in Excel export

Hi @PrzemyslawKlys ,

great project! Just one issue occured to us during importing the Excel export into MSSQL. There are empty Excel worksheets for for reporting regions, where no events happened. Changing the following code in "PSWinReportingHelper.ps1"

function Export-ReportToXLSX ($Report, $ReportOptions, $ReportFilePath, $ReportName, $ReportTable) { if ($Report -eq $true) { $ReportTable | Export-Excel -Path $ReportFilePath -WorkSheetname $ReportName -AutoSize -FreezeTopRow -AutoFilter return } else { return } }

to

function Export-ReportToXLSX ($Report, $ReportOptions, $ReportFilePath, $ReportName, $ReportTable) { if (($Report -eq $true) -and ($($ReportTable | Measure-Object).Count -gt 0)) { $ReportTable | Export-Excel -Path $ReportFilePath -WorkSheetname $ReportName -AutoSize -FreezeTopRow -AutoFilter return } else { return } }

got rid of the empty worksheets. Maybe this can be added to the next version?

Kind Regards
Robert

Error handling

Hi @PrzemyslawKlys, I have a question about error handling.

In the powershell, the error handler only works if the ErrorAction flag is set, or the global variable ErrorActionPreference is set to 'Stop'.

In this cases, error code handling doesn't work.:

$result = Get-WinEvent -ListLog $LogName -ComputerName $server | Select-Object MaximumSizeInBytes, FileSize, IsLogFul, LastAccessTime, LastWriteTime, OldestRecordNumber, RecordCount, LogName, LogType, LogIsolation, IsEnabled, LogMode

$TestActiveDirectory = get-addomain

I think the good way is to remove all the 'ErrorAction' arguments and set the global variable ErrorActionPreference.

This way will help us catch two birds with one stone:

  • No need to remember about ErrorAction
  • Any other error in runtime will stop the script

"happend" and "occured" misspelled in reports

In multiple locations in at least the email-based reporting, the word "happened" is misspelled as "happend", and in at least one location "occurred" is misspelled as "occured"

Examples:
No changes happend during that period.
The membership of those groups below has changed
No changes happend during that period.
Following group creation/deletion occured
No changes happend during that period.
Following GPOs were modified
No changes happend during that period.

ErrorAction Stop stopping on non-critical errors

@snd3r

image

Your setting did this. I guess one must go now thru every possible scenario and fix Try/Catch errors with this one. Get-WinEvent is very weird in that if there's no events found it will throw error (I would expect it to not do that). Please add some logic to it then.

Report for - Create / Delete / Modify Organizational Units

Needs work:

    ADOrganizationalUnitChangesDetailed = [ordered] @{
        Enabled = $false
        Events  = @{
            Enabled     = $true
            Events      = 5136, 5137, 5139, 5141
            LogName     = 'Security'
            Filter      = @{
                'ObjectClass' = 'organizationalUnit'
            }
            Functions   = @{
                'OperationType' = 'ConvertFrom-OperationType'
            }
            <#
            Fields      = [ordered] @{
                'Computer'                 = 'Domain Controller'
                'Action'                   = 'Action'
                'OperationType'            = 'Action Detail'
                'Who'                      = 'Who'
                'Date'                     = 'When'
                'ObjectDN'                 = 'Computer Object'
                'AttributeLDAPDisplayName' = 'Field Changed'
                'AttributeValue'           = 'Field Value'
                # Common Fields
                'RecordID'                 = 'Record ID'
                'ID'                       = 'Event ID'
                'GatheredFrom'             = 'Gathered From'
                'GatheredLogName'          = 'Gathered LogName'
            }
            #>
            SortBy      = 'Record ID'
            Descending  = $false
            IgnoreWords = @{}
        }
    }

Outlook does not display a logo in the header

Great project guys, thank you very much for it! I really like the coding style. You are great.

I have one improvement: by default Outlook does not display a logo in the header

"To help protect your privacy, Outlook prevented automatic download of some pictures in this message"

default

I solved this problem by adding images inlining:
snd3r/PSSharedGoods@95d8017
snd3r@8bc74b7

Can I send a pull request?

Domain Controller requirements?

Hi, sorry if I missed this but what is the method your module uses to access the domain controllers? I could not find the requirements for the domain controllers. Is something like psremoting required? The domain controllers in our environment do not have psremoting and we cannot install anything on them so I wanted to verify before trying it out. Thanks

Generalize creating of reports for Events

Currently, Reports for Events are hard coded. It means anytime you need to add a new report, modify it you have to go into the code, add it, finally modify the config file to use.

What would be great is the ability to define reports on Config file only. Since 90% of reports are looking almost identical it should be fairly easy to create a matching hash between what PSEventViewer returns and what actually needs to be shown in the report.

DateTime/DateFrom doesn't work properly for Find-Events

The module needs more complete documentation to disambiguate what DateTime format the module is expecting. Supplying a DateTime object is not recognized by the function and results in an output of
[Info] Getting events for dates to
and no output is produced.

Add 'credentials' switch

It would be helpful to have the option to specify credentials when running the module so as to gather logs from domain controllers while running the module as a standard user.

One function per file

Move to one function per file approach
Move some of the functions that are in other modules to PSSharedGoods

Sometimes Subevents have fields within fields

Sometimes SubEvents can have fields within fields.

image

image

Log Name:      Application
Source:        ADSync
Date:          22.02.2019 16:33:55
Event ID:      6946
Task Category: Management Agent Run Profile
Level:         Information
Keywords:      Classic
User:          N/A
Computer:      ADConnect.ad.evotec.xyz
Description:
Internal Connector run settings: 
Connector name: ad.evotec.xyz
Domain (partition): DC=ad,DC=evotec,DC=xyz
Login User domain: ad.evotec.xyz
Login User name: MSOL_6f0d1d4965ec
Whistler mode: Yes
2008R2 mode: Yes
IsRecycleBinEnabled: No
ACL Security: Yes
Deleted Objects Container: CN=Deleted Objects,DC=ad,DC=evotec,DC=xyz

Event Xml:
<Event xmlns="http://schemas.microsoft.com/win/2004/08/events/event">
  <System>
    <Provider Name="ADSync" />
    <EventID Qualifiers="16384">6946</EventID>
    <Level>4</Level>
    <Task>1</Task>
    <Keywords>0x80000000000000</Keywords>
    <TimeCreated SystemTime="2019-02-22T15:33:55.913603600Z" />
    <EventRecordID>244689</EventRecordID>
    <Channel>Application</Channel>
    <Computer>ADConnect.ad.evotec.xyz</Computer>
    <Security />
  </System>
  <EventData>
    <Data>Internal Connector run settings: 
Connector name: ad.evotec.xyz
Domain (partition): DC=ad,DC=evotec,DC=xyz
Login User domain: ad.evotec.xyz
Login User name: MSOL_6f0d1d4965ec
Whistler mode: Yes
2008R2 mode: Yes
IsRecycleBinEnabled: No
ACL Security: Yes
Deleted Objects Container: CN=Deleted Objects,DC=ad,DC=evotec,DC=xyz
</Data>
  </EventData>
</Event>

While Data property was extracted by Get-Events and split using new line there is still question whether we should try and split that data based on: into a separate hash and put it as properties into Event. Same could be done with Message just in case.

Send-Email - needs rewrite

Send-Email (even thou it's in PSSharedGoods) needs rewrite to support ability to provide passwords in secure string form.

Send-MailMessage

Should be able to delivers. Link to docs

There is Request-Credentials function in PSSharedGoods that will be used to create SecureString.

Other projects such as: PSAutomator, PSWinDocumentation define credentials in this way:

                Credentials = [ordered] @{
                    Username         = ''
                    Password         = ''
                    PasswordAsSecure = $true
                    PasswordFromFile = $true
                }

Send-Email needs to support this way.

Issue with sending email "Error sending message: Email Server Host is not set."

I'm using version 2.0.11, and have set up event forwarding.
Events are coming through and I've set up the task to trigger RunMe-TriggerOnEvents.ps1.
I've configured my email settings in RunMe-TriggerOnEvents.ps1:
From = '[email protected]'
To = '[email protected]'
CC = ''
BCC = ''
ReplyTo = ''
Server = "smtp.XXXX.local"
Password = ''
PasswordAsSecure = $false
PasswordFromFile = $false
Port = '25'
Login = ''
EnableSSL = 1
Encoding = 'Unicode'
Subject = 'Event Changes for period <> to <>'
Priority = 'Low'

smtp.XXXX.local is a working internal SMTP relay, which does not require authentication.

When the script gets triggered, nothing happens. I've tried manually running it with the same parameters and get the following errors:

[18/06/2019 11:27:15][Info] Prepare email head and body
You cannot call a method on a null-valued expression.
At C:\Program Files\WindowsPowerShell\Modules\PSSharedGoods\0.0.78\PSSharedGoods.psm1:3561 char:24
+ ...    foreach ($style in $FormattingParameters.Styles.GetEnumerator()) {
+                           ~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~
    + CategoryInfo          : InvalidOperation: (:) [], RuntimeException
    + FullyQualifiedErrorId : InvokeMethodOnNull

You cannot call a method on a null-valued expression.
At C:\Program Files\WindowsPowerShell\Modules\PSSharedGoods\0.0.78\PSSharedGoods.psm1:3568 char:24
+ ...    foreach ($color in $FormattingParameters.Colors.GetEnumerator()) {
+                           ~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~
    + CategoryInfo          : InvalidOperation: (:) [], RuntimeException
    + FullyQualifiedErrorId : InvokeMethodOnNull

You cannot call a method on a null-valued expression.
At C:\Program Files\WindowsPowerShell\Modules\PSSharedGoods\0.0.78\PSSharedGoods.psm1:3575 char:24
+     foreach ($links in $FormattingParameters.Links.GetEnumerator()) {
+                        ~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~
    + CategoryInfo          : InvalidOperation: (:) [], RuntimeException
    + FullyQualifiedErrorId : InvokeMethodOnNull

[18/06/2019 11:27:15][Info] Saving report to file: C:\Users\admin.XX\AppData\Local\Temp\PSWinReporting.html
[18/06/2019 11:27:16][Info] Sending email with reports
[18/06/2019 11:27:16][Info] Error sending message: Email Server Host is not set.
Remove-ReportFiles : The term 'Remove-ReportFiles' is not recognized as the name of a cmdlet, function, script file, or operable program. Check the spelling of the name, or if a path was included, verify that the path is correct and try again.
At C:\Program Files\WindowsPowerShell\Modules\PSWinReportingV2\2.0.11\PSWinReportingV2.psm1:1563 char:21
+                     Remove-ReportFiles -KeepReports $false -ReportFil ...
+                     ~~~~~~~~~~~~~~~~~~
    + CategoryInfo          : ObjectNotFound: (Remove-ReportFiles:String) [], CommandNotFoundException
    + FullyQualifiedErrorId : CommandNotFoundException

I have also tried connecting to office 365 with a login name and password, but get the same error.

Unable to get Security Log Size

Thank you for probably the most useful Powershell scripts I've ever used.

The following errors are seen when the script goes to pull the log size for the Security log on just one of the servers. The log sizes for other logs on the same server are reported successfully, and the security logs on other servers are reported on successfully.

`get-WinEvent : Could not retrieve information about the Security log. Error: Attempted to perform an unauthorized operation..
At C:\Program Files\WindowsPowerShell\Modules\PSWinReporting\1.7.3\Private\Get-EventLogSize.ps1:5 char:23

  • ... $result = get-WinEvent -ListLog $LogName -ComputerName $server | Se ...
  •             ~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~
    
    • CategoryInfo : NotSpecified: (:) [Get-WinEvent], Exception
    • FullyQualifiedErrorId : LogInfoUnavailable,Microsoft.PowerShell.Commands.GetWinEventCommand

get-WinEvent : There is not an event log on the DC1.local.domain.com computer that matches "Security".
At C:\Program Files\WindowsPowerShell\Modules\PSWinReporting\1.7.3\Private\Get-EventLogSize.ps1:5 char:23

  • ... $result = get-WinEvent -ListLog $LogName -ComputerName $server | Se ...
  •             ~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~
    
    • CategoryInfo : ObjectNotFound: (:) [Get-WinEvent], Exception
    • FullyQualifiedErrorId : NoMatchingLogsFound,Microsoft.PowerShell.Commands.GetWinEventCommand
      `

Any idea what I should look at to see if we can get that working?

Getting error when I specify a different time

If i run something like this:

Find-Events -Report ADGroupMembershipChanges -DatesRange Last3days -Servers 'SRV01', SRV02' | Format-Table -AutoSize

And then run it like:

Find-Events -Report ADGroupMembershipChanges -DatesRange Last7days -Servers 'SRV01', SRV02' | Format-Table -AutoSize

I get an error

Get-ServersList : Cannot process argument transformation on parameter 'Dates'. Cannot convert the "System.Object[]" value of type "System.Object[]" to type "System.Collections.IDictionary".
At C:\Program Files\WindowsPowerShell\Modules\PSWinReportingV2\2.0.6\PSWinReportingV2.psm1:261 char:312
+ ... sList -Definitions $Definitions -Target $Target -Dates $Dates -Quiet: ...
+                                                            ~~~~~~
    + CategoryInfo          : InvalidData: (:) [Get-ServersList], ParameterBindingArgumentTransformationException
    + FullyQualifiedErrorId : ParameterArgumentTransformationError,Get-ServersList

When Events have subevents fields needs to be rescaned

When Events have subevents fields needs to be rescaned and merged together

    AzureSynchronizationObjects = @{
        Enabled                 = $true
        EventsRunProfile        = @{
            Enabled     = $true
            Events      = 6946
            LogName     = 'Application'
            IgnoreWords = @{}

            Fields      = [ordered] @{
                'Computer'           = 'AD Connect Server'
                'Action'             = 'Action'
                #'Who'                = 'Who'
                'Date'               = 'When'
                #'ObjectAffected'     = 'User Affected'
                'LevelDisplayName'   = 'Level'
                'TaskDisplayName'    = 'Task'

                'NoNameA1'           = 'Profile Run'

                'KeywordDisplayName' = 'Keywords1'
                # Common Fields
                'ID'                 = 'Event ID'
                'RecordID'           = 'Record ID'
                'GatheredFrom'       = 'Gathered From'
                'GatheredLogName'    = 'Gathered LogName'
            }

            SortBy      = 'When'
        }
        EventsInternalConnector = @{
            Enabled     = $true
            Events      = 6946
            LogName     = 'Application'
            IgnoreWords = @{}
            Filter      = @{
                'Action' = 'Internal Connector run settings:'
            }
            Fields      = [ordered] @{
                'Computer'           = 'AD Connect Server'
                'Action'             = 'Action'
                #'Who'                = 'Who'
                'Date'               = 'When'
                #'ObjectAffected'     = 'User Affected'
                'LevelDisplayName'   = 'Level'
                'TaskDisplayName'    = 'Task'

                'NoNameB1'           = 'NoNameB1'
                'NoNameB2'           = 'NoNameB2'
                'NoNameB3'           = 'NoNameB3'
                'NoNameB4'           = 'NoNameB4'
                'NoNameB5'           = 'NoNameB5'
                'NoNameB6'           = 'NoNameB6'
                'NoNameB7'           = 'NoNameB7'
                'NoNameB8'           = 'NoNameB8'
                'KeywordDisplayName' = 'Keywords1'
                # Common Fields
                'ID'                 = 'Event ID'
                'RecordID'           = 'Record ID'
                'GatheredFrom'       = 'Gathered From'
                'GatheredLogName'    = 'Gathered LogName'
            }

            SortBy      = 'When'
        }
    }

This will only show fields from Subevents first, and not the other.

RAM issue

Hi,

Your script is amazing but i've some memory issue. After script execution, RAM on DC is full at 98%

I used RAM MAP and it shows that security.evtx is still in active memory (as mapped file)
RoyalTS_7mMpbgO67L

your help would be appreciated.

best regards

PSWinReportingV1 - Error if log path doesn't exists

[2020-08-02 20:56:20] [i] Parameter in configuration of FormattingParameters.FontHeadingSize exists.
Write-Color : Could not find a part of the path 'C:\Support\Logs\PSWinReporting.log'.
At C:\Program Files\WindowsPowerShell\Modules\PSWinReporting\1.8.1.5\PSWinReporting.psm1:1433 char:43
+ ... eq $true) { Write-Color @script:WriteParameters -Text "[i] ", "Parame ...
+                 ~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~
    + CategoryInfo          : OpenError: (:) [Write-Color], DirectoryNotFoundException
    + FullyQualifiedErrorId : FileOpenFailure,Write-Color

Verification if Required Modules are in their required versions

first use after module install:

Get-Logger : The term 'Get-Logger' is not recognized as the name of a cmdlet, function, script file, or operable program. Check the spelling of the name, or if a path was included, verify that the path is correct a
nd try again.
At C:\Program Files\WindowsPowerShell\Modules\PSWinReportingV2\2.0.8\PSWinReportingV2.psm1:239 char:19
+         $Logger = Get-Logger @LoggerParameters
+                   ~~~~~~~~~~
    + CategoryInfo          : ObjectNotFound: (Get-Logger:String) [], CommandNotFoundException
    + FullyQualifiedErrorId : CommandNotFoundException

is module dependency missing?

Include Parameter

Is there a way to include only specific accounts and groups in monitoring? I know there is an ignore type parameter, but didn't see anyway to specify sensitive groups and accounts only.

Set-EmailFormatting breaks CSS

In the HTML report generation code, the first step is adding css by Set-EmailHead:

$EmailBody = Set-EmailHead -FormattingOptions $FormattingParameters

The next stage is html post-processing by Set-EmailFormatting cmdlet.
In one of the stages, tag is added to each line:

    foreach ($t in $Template) {
        $Body += "$t<br>"
    }

https://github.com/EvotecIT/PSSharedGoods/blob/d53ed6be933b307651a44c32362917056aae0f5d/Public/Email/Set-EmailFormatting.ps1#L18

After this, the style sheet code becomes broken:
default

I think we should skip the styles section as a workaround.

Send notifications to Teams Channels based on priority

Needs definition in config file with things like 'Domain Admins','Enterprise Admins' and additional definition for Teams ID. Based on that changes to settings in here based on -like * would be sent to priority channel while other standard changes to Notifications channel.

odd results without adequate description in report.

so I've modified PSWinReporting/Examples/RunMe-Reporting.ps1 to fit my needs, and am getting strange results.

First, because I'm not sure how pertinent it is, here's the output of auditpol on my domain controllers:

C:\Windows\system32>auditpol.exe /get /category:*
System audit policy
Category/Subcategory                      Setting
System
  Security System Extension               Success and Failure
  System Integrity                        Success and Failure
  IPsec Driver                            Success and Failure
  Other System Events                     No Auditing
  Security State Change                   Success and Failure
Logon/Logoff
  Logon                                   Success and Failure
  Logoff                                  Success and Failure
  Account Lockout                         Success and Failure
  IPsec Main Mode                         No Auditing
  IPsec Quick Mode                        No Auditing
  IPsec Extended Mode                     No Auditing
  Special Logon                           Success and Failure
  Other Logon/Logoff Events               Success and Failure
  Network Policy Server                   Success and Failure
  User / Device Claims                    No Auditing
Object Access
  File System                             Success and Failure
  Registry                                Success and Failure
  Kernel Object                           No Auditing
  SAM                                     No Auditing
  Certification Services                  No Auditing
  Application Generated                   No Auditing
  Handle Manipulation                     Success and Failure
  File Share                              Success and Failure
  Filtering Platform Packet Drop          No Auditing
  Filtering Platform Connection           No Auditing
  Other Object Access Events              No Auditing
  Detailed File Share                     Success and Failure
  Removable Storage                       No Auditing
  Central Policy Staging                  No Auditing
Privilege Use
  Non Sensitive Privilege Use             No Auditing
  Other Privilege Use Events              No Auditing
  Sensitive Privilege Use                 Success and Failure
Detailed Tracking
  Process Creation                        Success and Failure
  Process Termination                     No Auditing
  DPAPI Activity                          Success and Failure
  RPC Events                              No Auditing
  Plug and Play Events                    No Auditing
Policy Change
  Authentication Policy Change            Success and Failure
  Authorization Policy Change             No Auditing
  MPSSVC Rule-Level Policy Change         Success
  Filtering Platform Policy Change        No Auditing
  Other Policy Change Events              No Auditing
  Audit Policy Change                     Success and Failure
Account Management
  User Account Management                 Success and Failure
  Computer Account Management             Success and Failure
  Security Group Management               Success and Failure
  Distribution Group Management           Success and Failure
  Application Group Management            Success and Failure
  Other Account Management Events         Success and Failure
DS Access
  Directory Service Changes               Success
  Directory Service Replication           No Auditing
  Detailed Directory Service Replication  No Auditing
  Directory Service Access                Success
Account Logon
  Kerberos Service Ticket Operations      Success and Failure
  Other Account Logon Events              Success and Failure
  Kerberos Authentication Service         Success and Failure
  Credential Validation                   Success and Failure

Under the section for "AD Computer Changes Detailed" happened, I have results that show these things, but I wish there was a more adequate explanation listed:

under Field Value:
TERMSRV/<PC Name> -- Terminal Server?
CmRcService/<PC Name> (directly followed by CmRcService/<PC FQDN>) -- Config Manager Remote Service?
WSMAN/<PC Name> -- Web Services for Management?

even if I add those to ignore, I'm still left with unclear results:
Action: A directory service object was modified
Field Changed: objectClass
Field Value: 1.2.840.113556.1.3.30 -- Computer?

Action: A directory service object was modified
Field Changed: userAccountControl
Field Value: 4096 (and another for 4098)

Action: A directory service object was modified
Action Details: Value Deleted (followed by another entry that says "Value Added")
Who: NT AUTHORITY\SYSTEM
Field Changed: userCertificate
Field Value: %%14672 -- DNS changes?

Here is my sterilized copy with my modifications (I added a ton of notes to keep track of the windows events and what they mean.

The last thing I would request is to somehow consolidate all changes that occur when a user is created or deleted. Having a dozen lines to show all the things that were created/modified when a user is created is a little cumbersome to read. I should emphasize I AM NOT COMPLAINING I love the tool and its potential, just a humble request.

New configuration for Servers

@snd3r What do you think on approach like this? Since the new version of PSWinReporting will be basically able to scan any Event Log and allow building your own reports I need to provide a good way to pass Servers to define.

$Target = @{
    Servers    = @{
        Use     = $false
        Servers = @{
            Server1 = @{ ComputerName = 'EVO1', LogName = 'ForwardedEvents' }
            Server2 = 'AD1','AD2'
        }
        Automatic = @{
            DC = 'All' # PDC
        }
    }
    LocalFiles      = @{
        Use         = $true
        Directories = [ordered] @{
            #MyEvents = 'C:\MyEvents' #
            #MyOtherEvent = 'C:\MyEvent1'
        }
        Files       = [ordered] @{
            #File1 = 'C:\MyEvents\Archive-Security-2018-09-14-22-13-07-710.evtx'
        }
    }
}

Old version:

        Servers           = @{
            UseForwarders   = $true # if $true skips Automatic/OnlyPDC/DC for reading logs. However it uses Automatic to deliver size of logs so keep Automatic to $true
            ForwardServer   = 'EVO1'
            ForwardEventLog = 'ForwardedEvents'

            UseDirectScan   = $true
            Automatic       = $true # will use all DCs for a forest
            OnlyPDC         = $false # will use PDC of current domain returned by Get-ADDomain
            DC              = ''
        }
        ArchiveProcessing = @{
            Use         = $true
            Directories = [ordered] @{
                #MyEvents = 'C:\MyEvents' #
                #MyOtherEvent = 'C:\MyEvent1'
            }
            Files       = [ordered] @{
                #File1 = 'C:\MyEvents\Archive-Security-2018-09-14-22-13-07-710.evtx'
            }
        }

Recommend Projects

  • React photo React

    A declarative, efficient, and flexible JavaScript library for building user interfaces.

  • Vue.js photo Vue.js

    🖖 Vue.js is a progressive, incrementally-adoptable JavaScript framework for building UI on the web.

  • Typescript photo Typescript

    TypeScript is a superset of JavaScript that compiles to clean JavaScript output.

  • TensorFlow photo TensorFlow

    An Open Source Machine Learning Framework for Everyone

  • Django photo Django

    The Web framework for perfectionists with deadlines.

  • D3 photo D3

    Bring data to life with SVG, Canvas and HTML. 📊📈🎉

Recommend Topics

  • javascript

    JavaScript (JS) is a lightweight interpreted programming language with first-class functions.

  • web

    Some thing interesting about web. New door for the world.

  • server

    A server is a program made to process requests and deliver data to clients.

  • Machine learning

    Machine learning is a way of modeling and interpreting data that allows a piece of software to respond intelligently.

  • Game

    Some thing interesting about game, make everyone happy.

Recommend Org

  • Facebook photo Facebook

    We are working to build community through open source technology. NB: members must have two-factor auth.

  • Microsoft photo Microsoft

    Open source projects and samples from Microsoft.

  • Google photo Google

    Google ❤️ Open Source for everyone.

  • D3 photo D3

    Data-Driven Documents codes.