Monthly Archives: April 2023

How to Convert DHCP Leases to Reservations Using PowerShell

As a system administrator, you might have to manage a Windows DHCP server and convert DHCP leases to reservations at some point. However, this can be a tedious task if you have many leases to convert. Fortunately, PowerShell can automate this process, making it much easier and faster. This post provides a step-by-step guide on how to convert DHCP leases to reservations using PowerShell.

Step 1: Open PowerShell

The first step is to open PowerShell with administrative privileges on the Windows DHCP server. You can do this by right-clicking on the PowerShell icon and selecting “Run as administrator.”

Step 2: Define the Functions

Copy and paste the following functions into PowerShell:

function Convert-DhcpLeasesToReservations
{
    param (
        [Parameter(Mandatory=$true)]
        [string]$ScopeId,

        [Parameter()]
        [switch]$WhatIf
    )

    $leases = Get-DhcpServerv4Lease -ComputerName localhost -ScopeId $ScopeId

    foreach ($lease in $leases)
    {
        $reservation = New-DhcpServerv4Reservation -IPAddress $lease.IPAddress -ClientId $lease.ClientId -ScopeId $lease.ScopeId -Description "Converted from DHCP lease"
        if (!$WhatIf) {
            Add-DhcpServerv4Reservation -ComputerName localhost -Reservation $reservation
        }
    }

    Write-Host "All DHCP leases within scope $ScopeId have been converted to reservations"
}

function Convert-DhcpLeasesToReservationsByFilter
{
    param (
        [Parameter(Mandatory=$true)]
        [string]$Filter,

        [Parameter()]
        [switch]$WhatIf
    )

    $scopes = Get-DhcpServerv4Scope -ComputerName localhost | Where-Object { $_.Name -like $Filter }

    foreach ($scope in $scopes)
    {
        Convert-DhcpLeasesToReservations -ScopeId $scope.ScopeId -WhatIf:$WhatIf
    }
}

Step 3: Run the Functions

To use these functions, you need to run Convert-DhcpLeasesToReservationsByFilter and specify the filter to select the DHCP scopes you want to convert DHCP leases to reservations. For instance, you can run:

Convert-DhcpLeasesToReservationsByFilter -Filter "192.168.*"

This command will convert all DHCP leases within the scopes that match the filter “192.168.*” to reservations.

You can also use the -WhatIf parameter to simulate the execution of the function without making any changes. This helps you to see what the function will do before actually running it. For instance, you can run:

Convert-DhcpLeasesToReservationsByFilter -Filter "192.168.*" -WhatIf

This command will display the details of the actions the function will perform, but it will not execute them.

Conclusion:

Using PowerShell to convert DHCP leases to reservations can save you time and effort. The functions provided in this blog post simplify the process, allowing you to automate the conversion of DHCP leases to reservations in a few simple steps. By following the steps outlined above, you can easily and quickly convert DHCP leases to reservations on your Windows DHCP server.

Advertisement

PowerShell Script to Audit User Permissions and Identify Users with High Permission

Managing permissions and ensuring proper access control is critical to maintain the security of your organization’s resources. In this blog post, we introduce a PowerShell script that can audit user permissions on file shares and directories, calculate a permission score for each user, and help you identify users with the most permissive rights.

Script

The PowerShell script consists of the following main parts:

  1. A hashtable that defines important rights and their corresponding scores.
  2. A list of excluded users and shares that should not be considered in the audit process.
  3. A function called Get-ImportantDirectoryACLs that retrieves the Access Control List (ACL) for a given directory, filters out excluded users, and calculates a permission score for each user.
  4. A main script block that connects to a target server, retrieves the file shares and directories, and invokes the Get-ImportantDirectoryACLs function.

The script calculates the permission scores for each user based on the importance of their rights. In this example, we assign a score of 100 to the ‘TakeOwnership’ right, 90 to the ‘FullControl’ right, and lower scores to other important rights. The resulting CSV file will display the users with the highest scores at the top, making it easy to identify users with the most permissive rights.

$ImportantRights = @{
    'FullControl' = 100
    'Modify' = 80
    'ReadAndExecute' = 60
    'Write' = 40
    'CreateFiles' = 20
    'CreateDirectories' = 20
    'Delete' = 10
    'TakeOwnership' = 100
}
$ExcludedUsers = @('NT AUTHORITY\SYSTEM', 'BUILTIN\Administrators', 'NT SERVICE\TrustedInstaller', 'BUILTIN\Users', 'APPLICATION PACKAGE AUTHORITY\ALL APPLICATION PACKAGES')
$ExcludedShares = @("IPC$", "ADMIN$")

function Get-ImportantDirectoryACLs {
    [CmdletBinding()]
    param(
        [Parameter(Mandatory, ValueFromPipeline)]
        [string]$DirectoryPath,
        [Parameter(Mandatory)]
        [string[]]$ExcludedUsers
    )

    process {
        $ACL = Get-Acl $DirectoryPath
        Foreach ($AccessRule in $ACL.Access) {
            If (!$AccessRule.IsInherited) {
                $User = $($AccessRule.IdentityReference)
                if ($User -notin $ExcludedUsers) {
                    $TotalScore = 0
                    $Rights = @($AccessRule.FileSystemRights -split ",") | Where-Object { $ImportantRights.ContainsKey($_) }
                    Foreach ($Right in $Rights) {
                        $TotalScore += $ImportantRights[$Right]
                    }
                    if ($TotalScore -gt 0) {
                        [pscustomobject]@{
                            DirectoryPath = $DirectoryPath
                            IdentityReference = $AccessRule.IdentityReference
                            AccessControlType = $AccessRule.AccessControlType
                            FileSystemRights = $AccessRule.FileSystemRights
                            Score = $TotalScore
                        }
                    }
                }
            }
        }
    }
}

$Server = "ServerName"

$Cim = New-CimSession -ComputerName $Server
if ($Cim) {
    $Shares = Get-SmbShare -CimSession $Cim | Where-Object { $ExcludedShares -notcontains $_.Name } | ForEach-Object {
        "\\$($_.PSComputerName)\$($_.Name)"
    }
    $Directories = $Shares | ForEach-Object { Get-ChildItem $_ -Directory } | Select-Object -ExpandProperty FullName

    $ShareRights = $Shares | Get-ImportantDirectoryACLs -ExcludedUsers $ExcludedUsers
    $DirectoryRights = $Directories | Get-ImportantDirectoryACLs -ExcludedUsers $ExcludedUsers

    $Results = @($ShareRights) + @($DirectoryRights)

    # Sort results by Score in descending order
    $SortedResults = $Results | Sort-Object -Property Score -Descending

    # Export the sorted results to a CSV file
    $SortedResults | Export-Csv -Path "$Server.csv" -NoTypeInformation
}

How to Use It

  1. Copy the script to your PowerShell environment and save it as a .ps1 file.
  2. Replace “ServerName” in the $Server variable with the name of the server you want to audit.
  3. Run the script. It will generate a CSV file named ServerName.csv that contains the audit results.
  4. Review the CSV file to identify users with the highest permission scores.

Conclusion

Using PowerShell to audit user permissions and identify users with the most permissive rights is an efficient and effective way to manage access control in your organization. By assigning permission scores to important rights, you can quickly identify the users that may require further investigation. Remember to adapt the script to your environment and adjust the scores as needed to suit your organization’s security requirements.