Tag Archives: Scripting

Get Report of Active Directory Locked Accounts and Machine they logged in from

Story:

I got some clients  that have reported some of their users being locked out and not able to discover how is this happening or which device its getting locked on.

Symptoms:

The user lock happens after you setup your GPO policy to get user locked after failing to login for X times with the correct password.

When user gets locked, they either can’t login or get prompted to re-enter their password in Outlook for example not knowing they have been locked. 

Hard to Find Out:

There’s no easy way to figure out what’s really happening and why the user got locked out specially if the account is being used on multiple devices e.g. (Phone, iPad, Desktop ..etc). Unless you have an auditing or an AD monitoring software that will log all auditing attempts to an external party and tell you where exactly the user is coming from, it’s a not an easy task to find out where is this taking place.  

Solution: 

1- Enabling Relevant Logs

In order for this to work, you’ll need to enable some Auditing logs on the Default Domain Controller Group Policy

Go to  >> Computer Configuration >> Windows Settings >> Security Settings >> Advanced Audit Policy Configuration >> Audit Policies >> Account Management >> Double Click on Audit User Account and enable both Success and Failure.

Once you applied this policy, you’ll need to force update your DCs , Sign out and back in and you’ll start noticing that in Event Viewer / Security the event 4740 and 4625 will start appearing .

The event 4740 will show you the locked user and the machine it tried to login from. 

The event 4625 will show you the path to the process/application that tried to login with your account. 

So to make this more benefitial I ended up writing a script that will get triggered by Task Scheduler in the case of Event 4740 being reported.

The script will search AD for any locked account. will scan the Logs for the user’s event and find the machine the user tried to login from and generate a report with all these details then send it to a target email in Excel forma after converting it using ImportExcel module.

Note that you must have a local SMTP Server for the email to be sent. If not you can just get the CSV and send it manually. 

 

2- Finding the relevant event

3- Finally The script

The script is simple so feel free to modify it, improve it or share it with others. 

Almost done
Script below 80%

#Report NTLM Authentication Failure for users
$ReportTime = ([datetime]::Today).ToString(“MM-dd-yyyy”)

#Generate report
$Report = [System.Collections.Generic.List[Object]]::new()

$LockedAccount = (Search-ADAccount -LockedOut -UsersOnly)
$i = 0
foreach ($User in $LockedAccount){

$i ++
Write-Progress -Activity “Gathering Logon info” -Status “Checking Login info for: $($User.Name)” -PercentComplete (($i / ($LockedAccount | Measure-Object).Count) * 100)
if($User.LockedOut){

$Event = Get-WinEvent -FilterHashtable @{ logname = ‘Security’; id = 4740 } -MaxEvents 500 | Select-Object TimeCreated,
@{ Name=’TargetUserName’; Expression={$_.Properties[0].value}},
@{ Name=’LogonMachine’; Expression={$_.Properties[1].value}} | Where {$_.TargetUserName -eq $User.SamAccountName}
}

$ReportLine = [PSCustomObject][Ordered]@{
Count = $i
ReportedUser = $User.Name
UPN = $User.UserPrincipalName
UserIsLocked = $User.LockedOut
LastLogonDate = $user.Lastlogondate
MachineName = $Event.LogonMachine -join ‘,’
‘Access Failure Time’ = $Event.TimeCreated -join ‘,’
‘Report Date’ = $ReportTime
}
$Report.Add($ReportLine)
}

$MailBody = “
<html><body>
<font color=’006400′> Dear Team, `
Please find attached a report of all locked out users including machine used for the login … `
If any issue you can report it via the ticketing system.</font>
<body><html>

#Eexport in CSV
$Report | Export-csv “C:\Reports\LockOutReport_$ReportTime.cscv” -NoTypeInformation

#Eexport in Excel Format
$Report | Export-Excel “C:\Reports\LockOutReport_$ReportTime.xlsx” -WorksheetName LogonFailure -TableName LogonFailure -AutoSize

$Exported = “C:\Reports\LockOutReport_$ReportTime.xlsx”

$CC = @(‘User2@domain.com’)
#
Get-ChildItem $Exported | send-mailmessage -from “system@domain.com” -to “user1@domain.com” -cc $cc -subject “Users LockOut Report $ReportTime” -body “$MailBody” -Priority High -smtpServer relay.domain.com -BodyAsHtml

Link to Github:

 

https://github.com/moh30ly/powershell/blob/main/ActiveDirectoryLockOutNotification

4- Attach Task to an Event

5- Get The Report

Use Group Based Licensing to Activate Office 365 Users

The Story

I got a request to place users into Security Groups for management purposes, The client have already users active but many of those users have left the work place and still have E3 or E1 Licenses which they should not have since this is pricey licenses and backing up users details is the easiest and most cost effective way of handling this.

So, To start (Prerequisites):

The Group based licensing management is a new feature, Was introduced in 2019 and not many people know that it is there however, This feature doesn’t come for free as you know (Since it’s Microsoft) and you must have a license for it or at least have users with E3 licensing model. So the requirements are:

  • – Azure AD Premium P1 or Higher
  • – Office 365 E3 or Higher.
  • – EMS or Higher.

How does it work?

In order for you to get this to work  you need to make sure you have planned from where you want to manage those groups and their licenses, Online? Or On-Premises?

IF Online

If you’re going to do this online, then you need to create a group for each Licensing Model which represents the intended License and its users e.g. Office365-E1 is going to be created as a security group and dedicated to E1 License users.

Office365-E3 will also be created the same way and users of License type E3 will be added to it.

If On-Premises

If you’re going to manage those groups on-premises, Then you must have ADConnect (Azure AD Sync) tool to sync those groups after creating them.

In my case I have created those groups in the following manner:

image

After creating those groups, You will need to sync them to Office 365 using ADConnect. To force this to sync immediately fire up Powershell on Azure Connect Server and type

Start-ADSyncSyncCycle -PolicyType delta

image

image

What If I have users already assigned with License?

If you have users already assigned licenses and want to manage them using Group Based licensing then you’re going to have to get a list of all your users with their Licenses information into a CSV file and Import those users to the groups you created base on the license they have.

I created a PowerShell that would match user’s names and based on the license mentioned in the CSV file would add them to the relevant group but first you need to export Users from Office 365.

Export Users and their license from Office 365

First of all we’ll connect to Office 365 MSOL Service using Online Powershell

image

Get-MsolUser -All |Where {$_.IsLicensed -eq $true } |Select DisplayName,UsageLocation,@{n="Licenses Type";e={$_.Licenses.AccountSKUid}},SignInName,UserPrincipalName,@{n="ProxyAddresses";e={$_.ProxyAddresses}}| Export-csv -Path C:ExportlicenseUsage.csv -notype

image

So this is how my CSV look right after I exported the users, We need to do some tuning on this CSV file to clean it and get it ready for our PowerShell.

image

There are total of 6 columns in this folder, If for whatever reason you wanted to use the ProxyAddress to distinguish users feel free to keep them in the script but in my case I didn’t need them so I deleted the entire column.

So I will keep the following (Remove Spacing between License Type)

  • DisplayName
  • UsageLocation
  • LicenseType
  • SignInName
  • UserPrincipalName

The Value of the License Type is usually formatted like this “TenantName: License” and in order to make this column useful I am going to remove the Tenant name from all the cells.

Find and Replace can easily remove and clean these values for you.

image

After cleaning the column, this is how it looks

image

This should be useful for us now along with the PowerShell to add the users to their relevant groups.

On Active Directory from an elevated PowerShell

Run PowerShell ISE  from a privileged account and copy + paste this script in ISE,

$ImportedUsers = Import-csv "C:\Users\AD\Desktop\ExportlicenseUsage.csv"

Foreach ($ImportedUser in $ImportedUsers){
$License = $ImportedUser.LicensesType
$E3 = "E3-Office365"
$E1 = "E1-Office365"
$EMS = "EMS-Office365"
$Sam = $ImportedUser.SamAccountName
$ImportedUPN = $ImportedUser.UserPrincipalName

$AllUsers = Get-ADUser -Filter * -Properties *
Foreach ($User in $AllUsers)
{
$UPN = $User.UserPrincipalName

if($user.UserPrincipalName -eq $ImportedUPN -and $License -match "EMS")
{
Add-ADGroupMember -Identity $EMS -Members $Sam
Write-Host $($UPN) "User has EMS License and has been added to the Group EMS" -ForegroundColor DarkGreen -BackgroundColor White
}
ElseIf ($user.UserPrincipalName -eq $ImportedUPN -and $License -Contains "STANDARDPACK")
{
Add-ADGroupMember -Identity $E1 -Members $Sam
Write-Host $($UPN) "User has E1 License and has been added to the Group E1" -ForegroundColor black -BackgroundColor green
}
ElseIf ($user.UserPrincipalName -eq $ImportedUPN -and $License -Contains "ENTERPRISEPACK")
{
Add-ADGroupMember -Identity $E3 -Members $Sam
Write-Host $($UPN) "User has E3 License and has been added to the Group E3" -ForegroundColor Blue -BackgroundColor White
}
}
}

image

Enabling Group Based License from Azure Portal

After this script finishes, I can open Azure Portal

From Azure Active Directory > Licenses > All Products

image   image    image

I will choose the license which I want to assign to a group of which I have created on my on-premises AD

image

Click on the License (Office 365 E1)  and choose Assign from top menu

image

Make sure you select assignment options and customize the license according to the products you want your group members to use then click on Users and Groups and select the relevant Group which you’ve created (In my case it’s E1-Office365)

image

Here, The group has been assigned

image

Click assign and you should be done

image

We will do the same for E3 Users

image

image

NOTE

From now on, Removing any user from this group will revoke their license and any service connected to it, You must be very careful when removing users from this group.

Microsoft has done great job covering this thoroughly and in a great detail including Scripts to be able to do many things like grabbing users who have an inherited license from a group or manually assigned. I am writing down the references if you’re more curious into these.

References:

https://docs.microsoft.com/en-us/azure/active-directory/users-groups-roles/licensing-groups-assign

https://docs.microsoft.com/en-us/azure/active-directory/users-groups-roles/licensing-ps-examples