Automated Credential Validation: Script Solutions for Password Verification in Windows Environments


2 views

In enterprise IT environments, verifying service account credentials without interactive login is a common pain point. Traditional methods like RDP or VM access create unnecessary overhead when you simply need to validate whether a password is correct.

Here's a robust PowerShell script that handles credential verification through WMI access - a method that works even when share permissions might interfere with drive mapping approaches:

function Test-Credential {
    param(
        [Parameter(Mandatory=$true)]
        [string]$Username,
        [Parameter(Mandatory=$true)]
        [string]$Password,
        [string]$Domain = $env:USERDOMAIN
    )
    
    $securePassword = ConvertTo-SecureString $Password -AsPlainText -Force
    $credential = New-Object System.Management.Automation.PSCredential ("$Domain\$Username", $securePassword)
    
    try {
        $wmiParams = @{
            ComputerName = $env:COMPUTERNAME
            Credential   = $credential
            Class        = 'Win32_BIOS'
            ErrorAction  = 'Stop'
        }
        $null = Get-WmiObject @wmiParams
        return $true
    }
    catch {
        if ($_.Exception.Message -match "Access is denied") {
            return $false
        }
        throw $_
    }
}

# Example usage:
$result = Test-Credential -Username "svc_account" -Password "P@ssw0rd!"
Write-Host "Credential validation result: $result"

For Active Directory environments, LDAP binding provides another verification method. This C# example demonstrates the technique:

using System.DirectoryServices;

bool ValidateCredentials(string username, string password, string domain)
{
    try {
        DirectoryEntry entry = new DirectoryEntry("LDAP://" + domain, 
                                                username, 
                                                password);
        object nativeObject = entry.NativeObject;
        return true;
    }
    catch (DirectoryServicesCOMException) {
        return false;
    }
}

When implementing credential verification tools:

  • Never store passwords in plaintext - use SecureString in PowerShell
  • Implement proper error handling to avoid exposing sensitive information
  • Consider account lockout policies - these scripts may trigger them
  • Run with least privileges necessary
  • Log validation attempts appropriately

For environments needing cross-platform support, here's a Python implementation using win32api:

import win32security
import win32con

def validate_credentials(username, password, domain):
    try:
        handle = win32security.LogonUser(
            username,
            domain,
            password,
            win32con.LOGON32_LOGON_NETWORK,
            win32con.LOGON32_PROVIDER_DEFAULT
        )
        win32security.CloseHandle(handle)
        return True
    except win32security.error:
        return False

For frequent credential validation needs in large organizations, consider:

  • PowerShell Module: CredentialTester (available in PowerShell Gallery)
  • Commercial tools like Thycotic Secret Server with API access
  • Custom REST API endpoints wrapping the validation logic
  • Ansible playbooks for credential verification across multiple systems

Every sysadmin has faced this situation: you need to verify whether a service account password is correct without going through the full authentication process. While you could spin up a VM or remote into a system, there are more efficient programmatic solutions.

Here are three practical approaches to test credentials:


// PowerShell method using PSCredential
$credential = Get-Credential
try {
    Start-Process -FilePath "cmd.exe" -Credential $credential -NoNewWindow -ErrorAction Stop
    Write-Output "Password is valid"
} catch {
    Write-Output "Invalid credentials"
}

Here's a complete VBScript solution for testing credentials through drive mapping:


' VB Script credential tester
Set objNetwork = CreateObject("WScript.Network")
strUser = InputBox("Enter username:")
strPass = InputBox("Enter password:")
strShare = "\\server\share"

On Error Resume Next
objNetwork.MapNetworkDrive "", strShare, False, strUser, strPass

If Err.Number = 0 Then
    MsgBox "Valid credentials", vbInformation
    objNetwork.RemoveNetworkDrive strShare
Else
    MsgBox "Invalid credentials", vbExclamation
End If

For more advanced scenarios, you can use the LogonUser API via C#:


// C# credential validation using Windows API
[DllImport("advapi32.dll", SetLastError = true)]
static extern bool LogonUser(
    string lpszUsername,
    string lpszDomain,
    string lpszPassword,
    int dwLogonType,
    int dwLogonProvider,
    out IntPtr phToken);

public bool ValidateCredentials(string username, string password, string domain)
{
    IntPtr token;
    bool isValid = LogonUser(username, domain, password, 2, 0, out token);
    if (isValid)
    {
        CloseHandle(token);
        return true;
    }
    return false;
}

When implementing credential testing:

  • Never store credentials in scripts
  • Use secure strings in PowerShell
  • Consider account lockout policies
  • Audit all credential testing activities

For those who prefer not to script:

  • PsExec with -u and -p parameters
  • Windows Credential Manager (control keymgr.dll)
  • Third-party tools like NetExec or CrackMapExec