Search code examples
powershellsecurestringdsquery

Use SecureString password object in dsquery command authentication


I have followed the following guide to create a SecureString password. Now, I need to log on to a foreign Domain Controller with the dsquery options -s (server) -u (user) and -p (password).

dsquery group -name $group -s $rmSrv -u $user -p $pass  | dsget group -members -expand -c -s $rmSrv -u $user -p $pass  | dsget user -samid -c -s $rmSrv -u $user -p $pass > $filename

When I enter the password in plaintext, I get authenticated. Once using the SecureString object, I can not authenticate. I have tried a few options, but could not get it running.

Do you have ideas?


Solution

  • The only way to do that is to decrypt the SecureString object and get it as a string.

    Here is a sample function:

    function ConvertTo-String {
      param(
        [Security.SecureString] $secureString
      )
      try {
        $bstr = [Runtime.InteropServices.Marshal]::SecureStringToBSTR($secureString)
        [Runtime.InteropServices.Marshal]::PtrToStringAuto($bstr)
      }
      finally {
        if ( $bstr -ne [IntPtr]::Zero ) {
          [Runtime.InteropServices.Marshal]::ZeroFreeBSTR($bstr)
        }
      }
    }
    

    Caution: Decrypting a SecureString object bypasses the protections that SecureString objects provide.

    If you insist on using the dsquery command, this is the only option, because it requires a plain-text password on its command line. This is inherently insecure.

    Instead, I would recommend to use the Active Directory cmdlets that can use SecureString directly without the need to convert to plain-text.