get the account name from SID using Perl

Viewed 115

On my Windows 10 machine I am using Win32::LookupAccountSID() to get the SID by account. In cmd.exe I run:

whoami /user

I grab the SID from the output and use it on the below $sid variable but the account printed is empty any idea what is wrong with the script?

use strict;
use warnings;
use Win32;
my $account;
my $domain;
my $sidtype;

my $sid = 'S-1-5-21-1994326832-1066739575-5522801-113721';

Win32::LookupAccountSID(undef,$sid,$account,$domain,$sidtype);

print $account;
1 Answers

You need convert the SID to binary format before calling Win32::LookupAccountSID(). Here is an example using the Win32::Security::SID module to convert to binary format:

use strict;
use warnings;
use Win32;
use Win32::Security::SID;
use Data::Dumper qw(Dumper);
{
    my $system = undef;
    my $account;
    my $domain;
    my $sidtype;
    my $stringsid = 'S-1-5-21-1768581528-3487803020-3219343602-1001';
    my $sid = Win32::Security::SID::ConvertStringSidToSid($stringsid);
    Win32::LookupAccountSID($system, $sid, $account, $domain, $sidtype);
    print Dumper({account => $account, domain => $domain, sidtype => $sidtype});
}

Output:

$VAR1 = {
          'domain' => 'DESKTOP-43CR0B8',
          'sidtype' => 1,
          'account' => 'hakon'
        };
Related