Get-Quotation: Something For Your Powershell Profile

I was playing around with my Powershell profile (again,) and I wanted to put a message-of-the-day style gizmo in there.  Now, a random quotation greets me every time I open Powershell:

  • Where do the quotes come from?

The function downloads them from www.quotationspage.com using Invoke-WebRequest.

  • What if I am not connected to the internet?

The function locally stores each unique quotation that it downloads. In the event that you are disconnected from the internet, the function will simply draw one of the locally cached quotes at random.

  • Where is my Powershell profile stored?

$Env:HOMEPATH\Documents\WindowsPowershell\Microsoft.Powershell_profile.ps1

  • Can I use this outside of my Powershell profile?

Sure.  It is just a function named Get-Quotation.

Here it is:

(Edit: A couple hours later, added wordwrap)

#
Function Get-Quotation
{
    Set-StrictMode -Version Latest

    $Form = @{'number'='1'; 
              'collection[0]'  = 'devils';
              'collection[1]'  = 'mgm';
              'collection[2]'  = 'motivate';
              'collection[3]'  = 'classic';
              'collection[4]'  = 'coles';
              'collection[5]'  = 'lindsly';
              'collection[6]'  = 'poorc';
              'collection[7]'  = 'altq';
              'collection[8]'  = '20thcent';
              'collection[9]'  = 'bywomen';
              'collection[10]' = 'contrib'}
    
    [String[]]$FormattedQuote = @()
    [Int]$MaxWidth = 0
    If ($Host.Name -EQ 'ConsoleHost')
    {
        $MaxWidth = $Host.UI.RawUI.WindowSize.Width
    }
    Else
    {
        $MaxWidth = 80
    }

    Try
    {
        $Page = Invoke-WebRequest http://www.quotationspage.com/random.php3 -Method Post -ContentType 'application/x-www-form-urlencoded' -Body $Form -ErrorAction Stop -TimeoutSec 5 -MaximumRedirection 0

        Foreach ($Element In $Page.AllElements)
        {
            If ($Element.tagName -EQ 'DL')
            {
                [String[]]$PreFormattedQuote = $Element.outerText -Split [Environment]::NewLine                

                For ($Index = 0; $Index -LT $PreFormattedQuote.Count; $Index++)
                {
                    If (($PreFormattedQuote[$Index].Length -GT 0) -AND -Not($PreFormattedQuote[$Index].Contains('More quotations on:')))
                    {
                        $FormattedQuote += $PreFormattedQuote[$Index]
                    }                    
                }
                $FormattedQuote[-1] = "`t-- $($FormattedQuote[-1])"                
            }
        }

        $Hasher = New-Object System.Security.Cryptography.SHA1CryptoServiceProvider
        $Hashed = $Hasher.ComputeHash([System.Text.Encoding]::UTF8.GetBytes($FormattedQuote[0]))
        [String]$HashString = [BitConverter]::ToString($Hashed).Replace('-', $Null)

        If (-Not(Test-Path (Join-Path $Env:LOCALAPPDATA 'Get-Quotation') -PathType Container))
        {
            New-Item (Join-Path $Env:LOCALAPPDATA 'Get-Quotation') -ItemType Directory | Out-Null
        }

        If (-Not(Test-Path (Join-Path (Join-Path $Env:LOCALAPPDATA 'Get-Quotation') $HashString) -PathType Leaf))
        {            
            $FormattedQuote | Out-File (Join-Path (Join-Path $Env:LOCALAPPDATA 'Get-Quotation') $HashString)
        }
    }
    Catch
    {
        Write-Warning "Failed to get quotation from www.quotationspage.com. ($($_.Exception.Message))"

        $FormattedQuote = Get-Content ((Get-ChildItem (Join-Path $Env:LOCALAPPDATA 'Get-Quotation') | Get-Random).FullName)
    }

    # Word wrap!
    [Int]$Column = 0
    Foreach ($Line in $FormattedQuote)
    {
        If ($FormattedQuote.IndexOf($Line) -EQ ($FormattedQuote.Count -1))
        {
            Write-Host "`n$Line" -ForegroundColor DarkGray
            Continue
        }
        
        [String[]]$Words = $Line -Split ' '
        Foreach ($Word In $Words)
        {
            # Strip any control characters from the word.
            $Word = $Word.Replace('`r', $Null).Replace('`n', $Null).Replace('`t', $Null)

            $Column += $Word.Length + 1   
            If ($Column -GT ($MaxWidth - 8))
            {
                Write-Host
                $Column = 0
            }
            Write-Host "$Word " -NoNewline -ForegroundColor DarkCyan            
        }
        
    }
    Write-Host
}

Get-Quotation

Bulk Modification of Active Directory ACLs with Powershell

The other day, I encountered an Active Directory-related problem.  The security model on the organizational units in this particular domain was quite complicated, arising from the multi-tenant nature of this domain and its "List Object Mode" configuration. (I've talked about List Object Mode before.)

First, a little background.  Imagine you're looking at the OUs in Active Directory Users & Computers:

CONTOSO.COM
   |
   + Builtin
   + Computers
   - Customers_OU
        |
        + Customer1_OU
        + Customer2_OU
        + Customer3_OU
        + Customer4_OU
        + ...

To cut to the chase, there was a problem with the ACL on each individual OU beneath Customers_OU (and there were hundreds!) where an access control entry (ACE) had been applied directly to each OU that allowed "Authenticated Users" the generic read permission.  This was essentially undermining the inheritance of permissions from parent object to child object, and allowing an account in Customer1_OU to view the contents of Customer2_OU, and vice versa.

*The siren noise from Kill Bill plays here.*

I'm glossing over some of the details, but basically what needed to happen, was for me to enumerate over each and every one of those hundreds of individual customer OUs, and remove those <not inherited> ACEs.

There was no way I was going to do that by hand, through the GUI.

So I scripted it.

Import-Module ActiveDirectory
Set-Location AD:\
$AllOUs = Get-ADOrganizationalUnit -Filter * `
             -SearchBase 'OU=CUSTOMERS_OU,DC=CONTOSO,DC=COM' `
             -Properties * -SearchScope OneLevel

Foreach ($OU In $AllOUs)
{
    $ACL = Get-ACL $OU.DistinguishedName
    
    Foreach ($ACE In $ACL.Access)
    {
        If (($ACE.IdentityReference -EQ 'NT AUTHORITY\Authenticated Users') -AND `
            ($ACE.IsInherited -EQ $False))
        {            
            $ACL.RemoveAccessRule($ACE)
            Set-ACL -AclObject $ACL $OU.DistinguishedName -Verbose
        }
    }
} 

That would have taken hours if done manually.  Hours that I'd rather spend playing GTA V.

Keeping My Sysinternals Tools Up To Date

Microsoft Sysinternals (primarily Mark Russinovich, but with occasional help from his buddies like Andrew Richards, Thomas Garnier, etc.,) has put out a ton of very useful Windows tools and utilities over the years. If you spend any time at all on Windows computers, you undoubtedly know and love these tools.

The tools are updated quite regularly, too.  And I hate having out of date stuff.  So, I wrote a little bit of Powershell this morning that will automatically scan my local folder to see which Sysinternals tools I have in that folder (like C:\Program Files\Sysinternals\,) then compare them with the latest and greatest versions of the executables on the internet (it's WebDAV,) and update my local copy if necessary.  I just run this script as a scheduled task once a week.

Set-StrictMode -Version Latest

[String]$EventSource    = 'UpdateSysinternals'
[String]$LocalDirectory = 'C:\Program Files\SysInternals\*.exe'
[String]$WebDAVShare    = '\\live.sysinternals.com\Tools'
[Int]$FilesUpdated      = 0

If (-Not([System.Diagnostics.EventLog]::SourceExists($EventSource)))
{
    Try
    {
        New-EventLog -LogName Application -Source $EventSource -ErrorAction Stop
        # MSDN says you shouldn't immediately use a new source after creating it.
        Start-Sleep -Seconds 10
        Write-EventLog -LogName Application -Source $EventSource -EntryType Information ` 
             -EventId 1 -Message 'Event source created.'
    }
    Catch
    {
        Exit
    }
}

$LocalFiles = Get-ChildItem $LocalDirectory

Try
{
    New-PSDrive -Name S -PSProvider FileSystem `
           -Root $WebDAVShare -ErrorAction Stop | Out-Null
}
Catch
{
    Write-EventLog -LogName Application -Source $EventSource -EntryType Error `
          -EventId 2 -Message "Failed to connect to $WebDAVShare!"
    Exit
}

Foreach ($LocalFile In $LocalFiles)
{    
    $RemoteFile = Get-ChildItem "S:\$($LocalFile.Name)"
    If ([Version]$RemoteFile.VersionInfo.ProductVersion -NE [Version]$LocalFile.VersionInfo.ProductVersion)
    {
        Write-EventLog -LogName Application -Source $EventSource -EntryType Information `
             -EventId 3 -Message "Remote file $($RemoteFile.Name) has version $($RemoteFile.VersionInfo.ProductVersion), which does not match local version $($LocalFile.VersionInfo.ProductVersion)."
        Copy-Item $RemoteFile.FullName $LocalFile.FullName -Force
        $FilesUpdated++
    }
}

Remove-PSDrive S

Write-EventLog -LogName Application -Source $EventSource -EntryType Information `
     -EventId 4 -Message "$FilesUpdated file(s) were updated."

Removing the 'Protect object from accidental deletion' Flag From A Bunch of OUs

I was recently conducting an experiment that involved creating a ton of Organizational Units in Active Directory.  Typically, when new OUs are created, they have a flag set on them that says "Protect object from accidental deletion."

This is normally fine, as you wouldn't want an admin to accidentally delete an entire OU full of users and computers.  But I had created a large hierarchy of OUs to conduct an experiment, and now that it was done, I wanted to get rid of all the OUs.  Like, immediately.  And I didn't want to sit in the AD Users & Computers GUI and uncheck that box on every OU, one at a time, so that it would let me delete them.

$AllOUs = Get-ADObject -Filter "ObjectClass -EQ 'organizationalUnit'" `
          -SearchBase 'OU=TestOUs,DC=CONTOSO,DC=COM' -Properties *

Foreach ($OU In $AllOUs)
{
    Set-ADOrganizationalUnit $OU.DistinguishedName `
          -ProtectedFromAccidentalDeletion $False
}

Now I can just delete the base of the tree and they'll all vanish.

Local Admin Password Maintainer

Active Directory is great for robust, centralized management of a large amount of I.T. assets.  But even once you have Active Directory, you're still left with that problem of what to do with local administrator accounts on all of the domain members.  You probably don't want to disable the local admin account, because you'll need it in case the computer is ever in a situation where it can't contact a domain controller.  But you don't have a good way of updating and maintaining the local Administrator password across your entire environment, either.  Everyone knows better than to use Group Policy Preferences to update the local administrator password on domain members, as it is completely unsecure.  Most other solutions involve sending the administrator passwords across the network in clear-text, require an admin to manually run some scripts or software every time that may not work well in complicated networks, and they still leave you with the same local administrator password on every machine... so if an attacker knocks over any one computer in your entire domain, he or she now has access to everything.

This is the situation Local Admin Password Maintainer seeks to alleviate.  LAPM easily integrates into your Active Directory domain and fully automates the creation of random local administrator passwords on every domain member.  The updated password is then transmitted securely to a domain controller and stored in Active Directory.  Only users who have been given the appropriate permissions (Domain Administrators and Account Operators, by default) may view any password.

The solution is comprised of two files: Install.ps1, which is the one-time install script, and LAPM.exe, an agent that will periodically (e.g., once a month,) execute on all domain members.  Please note that these two files will always be digitally signed by me.

Minimum Requirements

  • Active Directory. You need to be a member of both Domain Admins and Schema Admins to perform the install. You must perform the installation on the forest schema master.
  • Forest and domain functional levels of 2008 or better. This software relies on a feature of Active Directory (confidential attributes) that doesn't technically require any certain forest or domain functional level, but enforcing this requirement is an easy way of ensuring that all domain controllers in your forest are running a modern version of Windows.
  • I do not plan on doing any testing of either the install or the agent on Windows XP or Server 2003.  I could hypothetically make this work on XP/2003 SP1, but I don't want to.  If you're still using those operating systems, you aren't that concerned with security anyway.
  • A Public Key Infrastructure (PKI,) such as Active Directory Certificate Services, or otherwise have SSL certificates installed on your domain controllers that enable LDAP over SSL on port 636.  This is because LAPM does not allow transmission of data over the network in an unsecure manner.  It is possible to just bang out some self-signed certificates on your domain controllers, and then distribute those to your clients via Group Policy, but I do not recommend it.
  • The installer requires Powershell 4. Which means you need Powershell 4 on your schema master. Which means it needs to be 2008 R2 or greater.  I could port the install script to an older version of Powershell, but I haven't done it yet.
  • The Active Directory Powershell module. This should already be present if you've met the requirements thus far.
  • The Active Directory Web Service should be running on your DCs. This should already be present if you've met the requirements thus far.
  • LAPM.exe (the "agent") will run on anything Windows Vista/Server 2008 or better, 32 or 64 bit.  I just don't feel like porting it back to XP/2003 yet.

COPYRIGHT AND DISCLAIMER NOTICE:

Copyright ©2015 Joseph Ryan Ries. All Rights Reserved.

IN NO EVENT SHALL JOSEPH RYAN RIES (HEREINAFTER REFERRED TO AS 'THE AUTHOR') BE LIABLE TO ANY PARTY FOR DIRECT, INDIRECT, SPECIAL, INCIDENTAL, OR CONSEQUENTIAL DAMAGES, INCLUDING LOST PROFITS, ARISING OUT OF THE USE OF THIS SOFTWARE AND/OR ITS DOCUMENTATION, EVEN IF THE AUTHOR IS ADVISED OF THE POSSIBILITY OF SUCH DAMAGE.

THE AUTHOR SPECIFICALLY DISCLAIMS ANY WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE.
THE SOFTWARE AND ACCOMPANYING DOCUMENTATION, IF ANY, PROVIDED HEREUNDER IS PROVIDED "AS IS". THE AUTHOR HAS NO OBLIGATION TO PROVIDE MAINTENANCE, SUPPORT, UPDATES, ENHANCEMENTS, OR MODIFICATIONS.


Installation Instructions

  • Download the installation package found below, and unzip it anywhere on your Active Directory domain controller that holds the Schema Master FSMO role.  (Use the netdom query fsmo command if you forgot which DC is your Schema Master.)
  • If necessary, use the Unblock-File Powershell cmdlet or use the GUI to unblock the downloaded zip file.
  • You can verify the integrity of the downloaded files like so:


  • If you need to change your Powershell execution policy in order to run scripts on your DC, do so now with Set-ExecutionPolicy RemoteSigned.
  • Execute the Install script by typing .\Install.ps1 in the same directory as the script and LAPM.exe.

  • The installation script will perform several prerequisite checks to ensure your Active Directory forest and environment meet the criteria. It will also create a log file that stores a record of everything that takes place during this install session.  If you see any red [ERROR] text, read the error message and try to correct the problem that is preventing the install script from continuing, then try again. (E.g. SSL certificate not trusted, you're not on the Schema Master, etc.)  It's important that you read and consider the warning text, especially the part about how extending the Active Directory schema is a permanent operation.
  • Type yes at the warning prompt to commit to the installation.

  • The installation will now make a small schema modification by adding the LAPMLocalAdminPassword attribute to the Active Directory schema, adding that attribute to the computer object, and then adding an access control entry (ACE) to the root of the domain that allows the SELF principal the ability to write to that attribute.  That means that a computer has the right to modify its own LAPMLocalAdminPassword attribute, but not the attribute of another computer. (A computer does not have the ability to read its own LAPMLocalAdminPassword attribute. It is write-only.)

  • Finally, the install script copies LAPM.exe to the domain's SYSVOL share. This is so all domain members will be able to access it.
  • You are now done with the script and are in the post-installation phase.  You have one small thing left to do.
  • Open Group Policy Management on your domain controller.

  • Create a new GPO and link it to the domain:

  • Name the new GPO Local Admin Password Maintainer.
  • Right click on the new GPO and choose Edit. This will open the GPO editor.
  • Navigate to Computer Configuration > Preferences > Control Panel Settings > Scheduled Tasks.

  • Right-click in the empty area and choose New > Scheduled Task (At least Windows 7).

  • Choose these settings for the new scheduled task. It is very important that the scheduled task be run as NT Authority\System, also known as Local System.


  • This task will be triggered on the first of every month.  It's advisable to configure the random delay shown in the screenshot above, as this will mitigate the flood of new password uploads to your domain controllers on the first of the month.

  • For the program to execute, point to \\YourDomain\SYSVOL\YourDomain\LAPM.exe. Remember that the second "YourDomain" in the path is a reparse point/symlink that looks like "domain" if you view it in File Explorer.  For the optional argument, type BEGIN_MAGIC, in all capital letters.  It is case sensitive.
  • Lastly, the "Remove this item when it is no longer applied" setting is useful.  Unchecking "allow this task to be run on demand" can also be useful.  As an administrator, you have some leeway here to do what makes the most sense for your environment.  You might even choose to scope this GPO to only a certain OU if you only want a subset of the members of your domain to participate in Local Admin Account Maintainer.

  • Click OK to confirm, and you should now have a new scheduled task that will execute on all domain members.
  • Close the Group Policy editor.

Don't worry if the scheduled task also applies to domain controllers.  LAPM.exe detects whether it is running on a domain controller before it does anything, and exits if it is.


It also doesn't matter what the local administrator's name is, in case the account has been renamed. LAPM uses the SID.

LAPM logs successes and failures to the Windows Application event log.  Here is an example of what you might see if a client can't connect to a DC for some reason, like if SSL certificates aren't configured correctly:

In an event like this, LAPM.exe exits before changing the local administrator password, so the password will just stay what it was until the next time the scheduled job runs.

LAPM will generate a random, 16-character long password.  The "randomness" comes from the cryptographically secure PRNG supplied by the Windows API.

Success looks like this:


Now, notice that the standard domain user "Smacky the Frog" is unable to read the LAPMLocalAdminPassword attribute from Active Directory:

However, a Domain Administrator or Account Operator can!

Of course, you can also see it in the GUI as well, with Active Directory Users and Computers with advanced view turned on, for example.

So there you have it. Be smart, test it out in a lab first, and then enjoy your 30-day, random rotating local admin passwords!

As I continue to update this software package, new versions will be published on this page.

Download:

LAPM-1.0.zip (54.4KB)