Batch - How to identify / globalize SID

Discussion in 'Software' started by thisisu, Sep 10, 2012.

  1. thisisu

    thisisu Malware Consultant

    Hi,

    I'm trying to make a tool in batch that will find and remove blacklisted files, folders, registry keys, values, etc..

    Here is my dilemma, many of the registry keys I want to pursue look somewhat like this:

    HKEY_USERS\S-1-5-21-3375191861-1959199812-1684766954-1001\Software\Babylon

    I highlighted the problematic area in red..

    Since this isn't globalized to every machine (just mine), how can I gather the correct SID information from everyone else's machine to pursue?

    Thanks for any help.
     
  2. GermanOne

    GermanOne Guest

    Each user (profile) on your computer has an own SID. To find the SID of the currently logged in user you could read the value from the registry.
    Try:
    Code:
    @echo off &setlocal
    
    set "RegPath=HKEY_LOCAL_MACHINE\Software\Microsoft\Windows NT\CurrentVersion\ProfileList"
    for /f "delims=" %%i in ('reg query "%RegPath%"^|findstr /ibc:"%RegPath%\S-"') do (
      reg query "%%i" /v "ProfileImagePath"|findstr /iec:"%UserProfile%" >nul &&set "SID=%%~nxi"
    )
    
    echo %SID%
    pause
    
    If you can run WMIC (XP Pro and newer Win versions) there is another possibility.
    Code:
    @echo off &setlocal
    
    for /f "delims=" %%i in ('wmic useraccount where "name='%UserName%'" get sid /value') do (
      for /f "delims=" %%j in ("%%i") do set "%%j"
    )
    
    echo %SID%
    pause
    
    Regards
    GermanOne
     
  3. thisisu

    thisisu Malware Consultant

    Amazing, thank you.
    This stuff is so easy for you I bet :)
    I'm over here banging my head up a wall trying to learn :-D
     
  4. GermanOne

    GermanOne Guest

    You're welcome.
    I know how to write batch code - you know how to combat malicious software. Hence if I ever had a problem with malware I would know where to find you ;)

    BTW If there's anything in my code you don't understand don't hesitate to ask.
     
  5. thisisu

    thisisu Malware Consultant

    Thanks. I typically look up stuff like this on my own but I will take you up on your offer :)

    From your first code:
    Code:
    @echo off [COLOR="Red"]&setlocal[/COLOR]
    
    set "RegPath=HKEY_LOCAL_MACHINE\Software\Microsoft\Windows NT\CurrentVersion\ProfileList"
    for /f "delims=" %%i in ('reg query "%RegPath%"[COLOR="Red"]^[/COLOR]|findstr [COLOR="Red"]/ibc:[/COLOR]"%RegPath%\S-"') do (
      reg query "%%i" /v "ProfileImagePath"|findstr /iec:"%UserProfile%" >nul &&set "SID=%%[COLOR="Red"]~nxi[/COLOR]"
    )
    
    echo %SID%
    pause
    
    1) What does &setlocal do? I've never seen this combined with @echo off.
    2) What does the carrot (^) do?
    3) What's /ibc: and /iec: ?
    4) What's ~nxi?
     
  6. GermanOne

    GermanOne Guest

    1) The "&" is nothing but inline command concatenation.
    You don't need the SETLOCAL if you run the batch file via double click. It's one of my defaults. SETLOCAL starts a sub environment. This would be interesting if you drag/drop a batch file into an open CMD window. In that case the batch file is executed in the same cmd.exe process. All set variables would be valid even if the batch file has been finished. That means if you run another batch file in the same cmd window it will inherit these variables. SETLOCAL restricts the validity of the set variables to the current batch file. (An ENDLOCAL is executed automatically when the batch code ends.)

    2) Well as you probably know the | pipes the output of one command to the next. For that reason if the cmd.exe parses the command line it splits the line at the pipe character. Hence in my example it would pipe for /f "delims=" %%i in ('reg query "%RegPath%" to findstr /ibc:"%RegPath%\S-"') do ( which causes a syntax error. We want the the cmd.exe execute the expression (enclosed in single quotes) in a separate thread of the process. That's why we need the carrot character. It tells the CMD that it has to parse the pipe as a literal expression for the moment.

    3) These are options for the FINDSTR command. Run FINDSTR /?
    Code:
      /B         Matches pattern if at the beginning of a line.
      /E         Matches pattern if at the end of a line.
      /I         Specifies that the search is not to be case-sensitive.
      /C:string  Uses specified string as a literal search string.
    
    4) I "misuse" these modifiers. Run FOR /?
    Code:
       %~nxI       - expands %I to a file name and extension only
    
    But why do I use it even though there is no file path? Well the answer is simple. In %%i we have an registry path. E.g.:
    HKEY_LOCAL_MACHINE\Software\Microsoft\Windows NT\CurrentVersion\ProfileList\S-1-5-21-3375191861-1959199812-1684766954-1001
    It looks like a file path and it behaves like a file path if we apply the variable modifiers to it. The result is the substring next to the last back slash.

    Hope that helps.
     
  7. thisisu

    thisisu Malware Consultant

    Thank you for the explanations.

    I have another question about the first code you provided. Notice the small change I made:

    Code:
    @echo off &setlocal
    
    set "RegPath=HKEY_LOCAL_MACHINE\Software\Microsoft\Windows NT\CurrentVersion\ProfileList"
    for /f "delims=" %%i in ('reg query "%RegPath%"^|findstr /ibc:"%RegPath%\S-"') do (
      reg query "%%i" /v "ProfileImagePath"|findstr /iec:"%UserProfile%" >nul &&set "SID=%%~nxi"
    )
    
    echo %SID% >%systemdrive%\CrapRemover\temp\SID.txt
    I know this is a seperate issue, but would it even be feasible for me to save the SID so I can refer to it later in other batch files.

    Here is where I'm getting at, let's say I want to Call another .bat to read SID.txt, and then take action on it.

    For example:

    Code:
    "%systemdrive%\CrapRemover\SWReg" DELETE "HKEY_USERS\[COLOR="Red"]<SID provided by %systemdrive%\CrapRemover\temp\SID.txt>[/COLOR]\Software\Babylon"
    Is this just over complicating things in your opinion?

    Basically I am having one batch file gather information, and then dumping that information into a temp directory (e.g. \temp\Operatingsystem.txt and \temp\SID.txt) to "read / Access" later on for separate batch files. Does this make sense?

    Thanks for any additional advice if you have any.
     
    Last edited: Sep 11, 2012
  8. GermanOne

    GermanOne Guest

    First of all be careful with spaces in echo redirections. You wrote:
    Code:
    echo %SID% >%systemdrive%\CrapRemover\temp\SID.txt
    
    The space between %SID% and > would be ECHOed and redirected as well.
    I always recomment to write redirections in a reversed style.
    Code:
    >"%systemdrive%\CrapRemover\temp\SID.txt" echo %SID%
    
    It is very easy to read the first line of a file into a variable unsing SET /P
    Code:
    set /p "SID="<"%systemdrive%\CrapRemover\temp\SID.txt"
    
    Now you can use this variable instead of a fix string
    Code:
    "%systemdrive%\CrapRemover\SWReg" DELETE "HKEY_USERS\%SID%\Software\Babylon"
    
    But possibly you don't need the temporary file. You could combine both codes directly.
    Code:
    @echo off &setlocal
    
    set "RegPath=HKEY_LOCAL_MACHINE\Software\Microsoft\Windows NT\CurrentVersion\ProfileList"
    for /f "delims=" %%i in ('reg query "%RegPath%"^|findstr /ibc:"%RegPath%\S-"') do (
      reg query "%%i" /v "ProfileImagePath"|findstr /iec:"%UserProfile%" >nul &&set "SID=%%~nxi"
    )
    
    "%systemdrive%\CrapRemover\SWReg" DELETE "HKEY_USERS\%SID%\Software\Babylon"
    
    BTW: Actually the REG command is a program (%SystemRoot%\system32\reg.exe) that also supports the deletion of registry keys. Perhaps you don't need a 3rd party.
    Code:
    reg delete "HKEY_USERS\%SID%\Software\Babylon" /f
    
     
  9. thisisu

    thisisu Malware Consultant

    Works for me :)
    Thanks a lot GermanOne.
     
  10. GermanOne

    GermanOne Guest

    Just a bugfix:
    The "ProfileImagePath" value may contain an environment variable. In that case it fails to find the content of %UserProfile% in the registry data and the %SID% variable is empty / not defined. Use the following code instead:
    Code:
    set "RegPath=HKEY_LOCAL_MACHINE\Software\Microsoft\Windows NT\CurrentVersion\ProfileList"
    for /f "delims=" %%i in ('reg query "%RegPath%"^|findstr /ibc:"%RegPath%\S-"') do (
      reg query "%%i" /v "ProfileImagePath"|findstr /iec:"\\%UserName%" >nul &&set "SID=%%~nxi"
    )
    
    It matches the last backslash, the user name and the end of line in the ProfileImagePath data. Tested on Win7 and XP.

    @thisisu Thanks for pointing.
     
  11. thisisu

    thisisu Malware Consultant

    Thank you. I was trying to figure this out for hours when you posted. So much fail from me :banghead. Have a laugh :-D

    Note to anyone else reading: This is completely wrong!

    Code:
    :: GET SID (Thanks to GermanOne)
    
    REM We need two checks for this section.
    REM Check for the presence of XP first.
    
    For %%g in (
                %systemdrive%\CrapRemover\temp\OS.txt
               ) do ( %windir%\system32\findstr /i "Vista 7" >>%systemdrive%\CrapRemover\temp\junk.txt"
                      IF NOT ERRORLEVEL 1 goto get_SID_7_vista
                    )
    
    :get_SID_7_vista
    set "RegPath=HKEY_LOCAL_MACHINE\Software\Microsoft\Windows NT\CurrentVersion\ProfileList"
    for /f "delims=" %%i in ('reg query "%RegPath%"^|findstr /ibc:"%RegPath%\S-"') do (
    reg query "%%i" /v "ProfileImagePath"|findstr /iec:"%UserProfile%" >nul &&set "SID=%%~nxi"
    )
    set /p "SID="<"%systemdrive%\CrapRemover\temp\SID.txt"
    
    :get_SID_XP
    set "RegPath=HKEY_LOCAL_MACHINE\Software\Microsoft\Windows NT\CurrentVersion\ProfileList"
                     for /f "delims=" %%i in ('reg query "%RegPath%"^|findstr /ibc:"%RegPath%\S-"') do (
                     reg query "%%i" /v "ProfileImagePath" |findstr /iec:"\\%UserName%" >nul &&set "SID=%%~nxi"
    )
    set /p "SID="<"%systemdrive%\CrapRemover\temp\SID.txt"
     
  12. GermanOne

    GermanOne Guest

    Why didn't you ask earlier :-D

    In your snippet you check the Win version. You don't need it in that case but I admit it can be useful. I think primarily you have to distinguish between Vista and newer (due to the UAC restrictions and a lot of other things that behave differently) and Versions before Vista. I don't know where you get the information for your OS.txt. Another possibility is to extract the version out of the of the VER command output.
    XP has version 5.1.xxxx
    Vista has version 6.0.xxxx
    Win7 has version 6.1.xxxx
    As you can see it's sufficient to get the main version and check whether or not it is less than 6.
    Code:
    for /f "tokens=2 delims=[" %%i in ('ver') do for /f "tokens=2 delims=. " %%j in ("%%i") do set /a mainver=%%j
    
    echo Main version: %mainver%
    if %mainver% lss 6 (
      echo older than Vista
    ) else (
      echo Vista or newer
    )
    
     
    Last edited by a moderator: Sep 17, 2012
  13. thisisu

    thisisu Malware Consultant

    I'm trying to figure it out myself without having to bug you so much :-D

    Here is another code I'm having trouble with. Do you see the issue?

    Code:
    @echo off
    
    set "regdelete="%windir%\system32\reg.exe" DELETE"
    
    :: REGISTRY PORTION OF ASK REMOVAL
    
    For %%g in (
    HKEY_CLASSES_ROOT\GenericAskToolbar.ToolbarWnd
    ) do ( if exist %%g (
                         REM output these detected keys and values to a temp file
                         echo Detected and deleted: %%g >%systemdrive%\CrapRemover\temp\DELETION_ask.txt
                         REM Now carry out deletion
                         %regdelete% %%g 
                        )
         )
    HKEY_CLASSES_ROOT\GenericAskToolbar.ToolbarWnd is still present on the test machine I'm using. I can't even get it to acknowledge its presence much less delete it from the registry. :-o

    Some of the keys have spaces in them, so I chose one that doesn't as the example. But am I going to need to surround them with quotations in the For %%g in section?
     
  14. GermanOne

    GermanOne Guest

    You're not bugging me :)

    Use "IF EXIST ..." if you want to determine whether or not a file/folder exists. You can't apply that to a registry key. You need to use REG QUERY to achieve it.
    Enclose the path into double quotes if you're not sure about spaces (it will also work if there are no spaces in the path).
    Use the logical command concatenation && to execute a command if the first command was successful (similar to "IF NOT ERRORLEVEL 1 ...").

    Code:
    @echo off &setlocal
    
    set "regquery="%windir%\system32\reg.exe" QUERY"
    set "regdelete="%windir%\system32\reg.exe" DELETE"
    set "DELETION_ask=%systemdrive%\CrapRemover\temp\DELETION_ask.txt"
    
    :: CREATE AN EMPTY FILE
    >"%DELETION_ask%" type nul
    
    :: REGISTRY PORTION OF ASK REMOVAL
    for %%g in (
      "HKEY_CLASSES_ROOT\GenericAskToolbar.ToolbarWnd"
    ) do (
      %regquery% %%g >nul 2>&1 &&(
        REM output these detected keys and values to a temp file
        >>"%DELETION_ask%" echo Detected: %%g
        REM Now carry out deletion
        %regdelete% %%g /f >nul 2>&1 && (
          >>"%DELETION_ask%" echo Deleted : %%g
        )
      )
    )
    
     
  15. thisisu

    thisisu Malware Consultant

    Thanks again :)

    One thing that is perplexing me as I try to understand the latest sample of code provided.

    Code:
    @echo off &setlocal
    
    set "regquery="%windir%\system32\reg.exe" QUERY"
    set "regdelete="%windir%\system32\reg.exe" DELETE"
    set "DELETION_ask=%systemdrive%\CrapRemover\temp\DELETION_ask.txt"
    
    :: CREATE AN EMPTY FILE
    >"%DELETION_ask%" type nul
    
    :: REGISTRY PORTION OF ASK REMOVAL
    for %%g in (
      "HKEY_CLASSES_ROOT\GenericAskToolbar.ToolbarWnd"
    ) do (
      %regquery% %%g >nul 2>&1 [COLOR="Red"]&&([/COLOR]
        REM output these detected keys and values to a temp file
        >>"%DELETION_ask%" echo Detected: %%g
        REM Now carry out deletion
        %regdelete% %%g /f >nul 2>&1 [COLOR="blue"]&& ([/COLOR]
          >>"%DELETION_ask%" echo Deleted : %%g
        )
      )
    )
    
    Look at what I highlighted in red and blue

    Is there a reason why one of them includes a space between & and ( and the other does not?
     
  16. GermanOne

    GermanOne Guest

    No, in this case it doesn't matter if you have no space, one space or a couple of spaces between & and (.
    command >nul 2>&1 && (command block)
    where
    >nul redirects the StdOut of the command to NUL (a virtual black hole :-D)
    2>&1 merges the StdErr and the StdOut (both are finally redirected to NUL this way)
     
  17. Rickdanna

    Rickdanna Private E-2

    Wow! Can I just say a big thank you to GermanOne and Thisisu. I have been Googling for a solution like this for a long time.

    I was wondering how I could get this to work on a remote PC within a domain enviroment.

    I tried different variations using REG QUERY /? and following the syntax I can get the following to display all SIDs:
    Code:
    H:\>REG QUERY "\\TESTPC\HKEY_LOCAL_MACHINE\SOFTWARE\Microsoft\Windows NT\Curr
    entVersion\ProfileList" /s
    I was hoping that by altering the code It could be utilised on a remote PC. I made a test batch file with pauses so I could see where the script is failing:

    Code:
    @ECHO ON
    
    set REGPATH="\\LOANER010\HKEY_LOCAL_MACHINE\Software\Microsoft\Windows NT\CurrentVersion\ProfileList"
    for /f "delims=" %%i in ('reg query "%REGPATH%"^|findstr /ibc:"%REGPATH%\S-"') do (
      reg query "%%i" /v "ProfileImagePath"|findstr /iec:"c:\Users\Test" >nul &&set "SID=%%~nxi"
    )
    
    ECHO %SID%
    
    PAUSE
    
    REG DELETE "\\LOANER010\HKEY_LOCAL_MACHINE\Software\Microsoft\Windows NT\CurrentVersion\ProfileList\%SID%" /F
    
    PAUSE
    I keep getting this error:
    FINDSTR: Cannot open NT\CurrentVersion\ProfileList\S-
    ERROR: Invalid syntax.
    Type "REG QUERY /?" for usage.

    I thought maybe I show put the regpath in quotes because of the space between Windows and NT
    Code:
    set REGPATH="\\LOANER010\HKEY_LOCAL_MACHINE\Software\Microsoft\Windows NT\CurrentVersion\ProfileList"
    Unfortunately this didn't help me either.

    I would really appreciate it if someone could throw me a bone here.

    Any help?
     
  18. PC-XT

    PC-XT Master Sergeant


MajorGeeks.Com Menu

Downloads All In One Tweaks \ Android \ Anti-Malware \ Anti-Virus \ Appearance \ Backup \ Browsers \ CD\DVD\Blu-Ray \ Covert Ops \ Drive Utilities \ Drivers \ Graphics \ Internet Tools \ Multimedia \ Networking \ Office Tools \ PC Games \ System Tools \ Mac/Apple/Ipad Downloads

Other News: Top Downloads \ News (Tech) \ Off Base (Other Websites News) \ Way Off Base (Offbeat Stories and Pics)

Social: Facebook \ YouTube \ Twitter \ Tumblr \ Pintrest \ RSS Feeds