Windows Basics
Windows Shells
Windows Command Prompt
The Command Prompt, cmd.exe
, is a shell that contains a defined set of commands that allow users to interact with Win32
objects and applications.
Just like Zsh or Bash, cmd.exe can be used to create and manipulate files, navigate to directories, and run shell scripts. On Windows, these scripts are referred to as batch files.
Builtin Commands and Help
The first command to learn is help
. When no arguments are provided, help
displays all the other builtin commands.
C:\>help
For more information on a specific command, type HELP command-name
ASSOC Displays or modifies file extension associations.
ATTRIB Displays or changes file attributes.
BREAK Sets or clears extended CTRL+C checking.
BCDEDIT Sets properties in boot database to control boot loading.
...
We can also provide help with the name of a second command as an argument to obtain its usage information as output.
C:\>help time
Displays or sets the system time.
TIME [/T | time]
Type TIME with no parameters to display the current time setting and a prompt
for a new one. Press ENTER to keep the same time.
If Command Extensions are enabled the TIME command supports
the /T switch which tells the command to just output the
current time, without prompting for a new time.
We could also use the /?
shortcut to get information about how to use a command. This is similar to the -h
switch for many Bash commands.
C:\>time /?
Displays or sets the system time.
Common build-in commands:
Command | Description |
---|---|
cd | Displays the name of or changes the current directory. |
cls | Clears the screen. |
cmd | Starts a new instance of the Windows command interpreter. |
copy | Copies one or more files to another location. |
del | Deletes one or more files. |
dir | Displays a list of files and subdirectories in a directory. |
echo | Displays messages, or turns command echoing on or off. |
erase | Deletes one or more files. |
exit | Quits the cmd.exe program (command interpreter). |
find | Searches for a text string in a file or files. |
findstr | Searches for strings in files. |
mkdir | Creates a directory. |
more | Displays output one screen at a time. |
move | Moves one or more files from one directory to another directory. |
ren | Renames a file or files. |
rmdir | Removes a directory. |
type | Displays the contents of a text file. |
Windows PowerShell
PowerShell is a task automation solution comprised of a command-line shell, a scripting language, and a configuration management framework. It is now cross-platform and can be run on Linux and macOS as PowerShell Core. It is possible to run all the commands that the Command Prompt supports as well as many more. It is therefore a far more robust and flexible option for interacting with the Windows OS.
Windows PowerShell is built on the .NET framework and employs the use of cmdlets to run administrative tasks. PowerShell is able to fully interface with the Component Object Model (COM) and the Windows Management Instrumentation (WMI), which gives users the ability to perform administrative tasks on both local and remote Windows systems.
The command-line component of PowerShell can be started by invoking the PowerShell.exe binary in a regular Command Prompt window.
WMCI
The Windows Management Instrumentation Command-Line (WMIC) utility provides a command-line interface for Windows Management Instrumentation (WMI). WMI allows scripting languages like VBScript and PowerShell to manage Windows systems locally and remotely. It also allows for the sharing of information between management applications.
Windows File System Navigation
Windows Navigation on the Command Line
We can use the dir /A
option with dir to display hidden files.
C:\Users>dir /A
Volume in drive C has no label.
Volume Serial Number is 1234-5678
Directory of C:\Users
05/24/2021 04:53 PM <DIR> .
05/24/2021 04:53 PM <DIR> ..
05/24/2021 04:53 PM <SYMLINKD> All Users [C:\ProgramData]
05/24/2021 04:53 PM <DIR> Default
05/24/2021 04:53 PM <JUNCTION> Default User [C:\Users\Default]
05/24/2021 04:53 PM 174 desktop.ini
05/24/2021 04:48 PM <DIR> Public
1 File(s) 174 bytes
5 Dir(s) 32,934,400,000 bytes free
C:\Users>
Standard Directories
\PerfLogs
: This directory stores Windows performance logs, but it is usually empty on a default configuration of Windows.\Program Files
: This directory is found on both 32-bit and 64-bit versions on Windows. On 32-bit editions, this is the only Program Files directory available, and it stores 32-bit programs. On 64-bit versions of Windows, this directory stores 64-bit programs.\Program Files (x86)
: This directory can be found on 64-bit editions of Windows and stores 32-bit versions of programs.\ProgramData
: This is a hidden directory that contains program data that is expected to be accessed by computer programs regardless of the logged in user account.\Users
: Every user who has logged in to the OS at least once will have a subdirectory created under their name in this directory.\Users\Public
: This is a subdirectory of\Users
and contains user data. It can be accessed by all users, and is used to share files among them. It can also be accessed across the network from valid user accounts with remote access permissions.\Users\[UserName]\AppData
: This is a hidden subdirectory of\Users
. It stores application data and settings for every user.\AppData
contains three additional subfolders, namely\Roaming
,\Local
, andLocalLow
.\Roaming
is used for network-based logins for roaming profiles and synchronizes the user's data when they log in to the computer.- The Windows per-user temporary directory,
\Temp
, can be found here under\Local
.
\Windows
: This stores the main Windows installation and contains files related to the OS itself.\System
,\System32
, and\SysWOW64
: These directories store dynamic-link library (DLL) files that execute the core features of Windows and the Windows API. The nomenclature for these directories can by a bit confusing.\System
stores 16-bit DLLs and is usually empty on 64-bit editions of Windows because 16-bit applications cannot run on 64-bit OSs.\System32
stores either 32-bit or 64-bit DLL files, depending on whether a 32-bit or 64-bit edition of Windows is running.\SysWOW64
is found only on 64-bit editions of Windows, and despite its name, stores 32-bit DLLs.
System Information and Environment Variables
Retrieving System Information
systeminfo.exe
is a Windows binary capable of extracting detailed configuration information about the system it is run on. It can also be run against remote machines if provided the /s
option.
C:\>systeminfo
Host Name: Fubar-Machine
OS Name: Microsoft Windows 10 Pro
OS Version: 10.0.19041 N/A Build 19041
OS Manufacturer: Microsoft Corporation
OS Configuration: Standalone Workstation
OS Build Type: Multiprocessor Free
Registered Owner: Fubar
...
Though systeminfo
is not a built-in command, we can still use the /?
option to query the program's usage information:
C:\>systeminfo /?
SYSTEMINFO [/S system [/U username [/P [password]]]] [/FO format] [/NH]
Description:
This tool displays operating system configuration information for
a local or remote machine, including service pack levels.
Parameter List:
/S system Specifies the remote system to connect to.
/U [domain\]user Specifies the user context under which
the command should execute.
/P [password] Specifies the password for the given
user context. Prompts for input if omitted.
/FO format Specifies the format in which the output
is to be displayed.
Valid values: "TABLE", "LIST", "CSV".
/NH Specifies that the "Column Header" should
not be displayed in the output.
Valid only for "TABLE" and "CSV" formats.
/? Displays this help message.
Examples:
SYSTEMINFO
SYSTEMINFO /?
SYSTEMINFO /S system
SYSTEMINFO /S system /U user
SYSTEMINFO /S system /U domain\user /P password /FO TABLE
SYSTEMINFO /S system /FO LIST
SYSTEMINFO /S system /FO CSV /NH
Windows is capable of storing environment variables similar to those found on Linux.
Some of the most frequently used Windows environment variables include the following.
Environment Variable | Purpose |
---|---|
PATH | Holds the search path for executable files |
USERNAME | Shows the currently logged on user |
TEMP | Returns the default temporary storage directory(ies) |
USERPROFILE | Holds the profile location of the current user |
In the Linux Basics, we learned that we could reference Bash or Zsh environment variables with the $[VARIABLE-NAME]
syntax. On Windows, we need to wrap the variable name in percentage signs like so: %[VARIABLE-NAME]%
.
For example, we can use the echo command to retrieve our username.
C:\>echo username
username
C:\>echo $username
$username
C:\>echo %username%
fubar
When the set
command is used without parameters, it will display all currently stored environment variables.
C:\>set
ALLUSERSPROFILE=C:\ProgramData
APPDATA=C:\Users\Fubar\AppData\Roaming
asl.log=Destination=file
CommonProgramFiles=C:\Program Files\Common Files
CommonProgramFiles(x86)=C:\Program Files (x86)\Common Files
CommonProgramW6432=C:\Program Files\Common Files
COMPUTERNAME=Fubar-Machine
ComSpec=C:\WINDOWS\system32\cmd.exe
DriverData=C:\Windows\System32\Drivers\DriverData
FPS_BROWSER_APP_PROFILE_STRING=Internet Explorer
FPS_BROWSER_USER_PROFILE_STRING=Default
HOMEDRIVE=C:
HOMEPATH=\Users\Administrator
LOCALAPPDATA=C:\Users\Fubar\AppData\Local
LOGONSERVER=\\Fubar-Machine
NUMBER_OF_PROCESSORS=8
OneDrive=C:\Users\Fubar\OneDrive
OS=Windows_NT
Path=C:\Windows\system32;C:\Windows;
...
The
set
command can also be used to temporarily change the value of an environment variable in the context of the current shell. Thesetx
command can be used to change a value permanently by modifying the registry.
SysInternals Overview and psinfo
Download: https://docs.microsoft.com/en-us/sysinternals/downloads/
Upon executing any of the Sysinternals tools for the first time, we will need to accept the End-User License Agreement (eula). The eula can also be accepted via the command-line for each ulitily with the /accepteula
option. After we accept the eula, we can run psinfo
with no arguments or options. This will display some vital local system information.
The psinfo
tool is quite versatile, and can retrieve information related to security, installed software, system patches, disk volume, and more. It can even be used on a remote machine.
Managing Files From the Command Line
Linux vs Windows
echo
=echo
cat
=type
rm
=del
mv
=rename
mv
=move
cp
=copy
mkdir
=mkdir
rmdir
=rmdir
diff
=fc
ln
=mklink
To create an empty file, we can execute echo
with no arguments and redirect error output to the filename we want to create:
C:\Users\Fubar>echo 2> EmptyFile.txt
The xcopy
and robocopy
commands are more robust versions of copy that are often used in batch scripts. While xcopy
has been deprecated, robocopy
is very helpful because it has a high tolerance for network interruptions. It also has several other powerful features that are useful for security auditing.
Windows includes the ability to create soft and hard symbolic links, similar to what you will find in Linux. A symbolic link essentially points to another file or directory. A soft symbolic link is the equivalent of a shortcut. That is, it redirects attempts to connect to invoke the linked file back to the original.
A hard symbolic link makes it appear as though the referenced file or directory actually exists in the same location as the link's location. This can be useful when working with programs that require access to specific files or directories.
Note that the hardlink file has a regular filetype and does not contain the
<SYMLINK>
tag. If we were to change the contents of the original file, hardlink would remain unchanged.
Searching for Files and Text
Locating Files Using Windows Command Line
dir /s
C:\Users\Fubar>dir /s *.exe /p
Volume in drive C has no label.
Volume Serial Number is 523D-9369
Directory of C:\Users\Fubar\AppData\Local\atom
05/25/2021 02:29 PM 1,709,096 Update.exe
1 File(s) 1,709,096 bytes
Directory of C:\Users\Fubar\AppData\Local\Discord
05/25/2021 11:43 PM 1,512,760 Update.exe
1 File(s) 1,512,760 bytes
...
We use the
/p
switch in listing 25 to pause the print after the terminal page is full, so that we can browse the output at the pace we prefer.
tree
C:\Users\Fubar>tree
Folder PATH listing
Volume serial number is 523D-9369
C:.
...
├───Links
├───Music
│ └───Artists
│ ├───Albums
│ │ ├───Songs
│ │ ├───Generated
│ │ └───MyMusic
├───SecretStuff
│ ├───Documents
│ ├───Firewalls
│ │ ├───DontCheckHere
│ ├───Databases
│ │ ├───VPNs
│ │ ├───Images
│ │ ├───Resources
│ │ └───Videos
│ ├───Intelligence
│ │ ├───Profiles
│ │ ├───Policies
│ │ └───Orientation
│ │ └───scripts
...
We can use
tree
to easily search through a user's home directory to find interesting files. The/F
flag will display any files that exist within each of the directories in the output.
forfiles
The forfiles
command is an expressive tool that can execute other commands on a defined set of files. While forfiles
is very versatile, we'll focus here on its search capability.
C:\Users\Fubar>forfiles /P C:\Windows /S /M notepad.exe /c "cmd /c echo @PATH"
...
"C:\Windows\SysWOW64\notepad.exe"
ERROR: Access is denied for "C:\Windows\SysWOW64\Com\dmp\".
ERROR: Access is denied for "C:\Windows\SysWOW64\config\".
ERROR: Access is denied for "C:\Windows\SysWOW64\Configuration\".
ERROR: Access is denied for "C:\Windows\SysWOW64\FxsTmp\".
ERROR: Access is denied for "C:\Windows\SysWOW64\Msdtc\".
ERROR: Access is denied for "C:\Windows\SysWOW64\networklist\".
ERROR: Access is denied for "C:\Windows\SysWOW64\sru\".
ERROR: Access is denied for "C:\Windows\SysWOW64\Tasks\".
In the example, we used forfiles to find the path of notepad.exe.
/P
specifies where to begin our search./S
indicates that we want to search recursively./M
points at what we want to search for./C
executes a specified command.
Searching Text Using Windows Command Line
find
In Linux, find
is used to locate a file. Somewhat confusingly, in Windows the find
command is used to search for a string of text.
C:\>find "password" C:\Users\Fubar\importantfile.txt
---------- C:\USERS\FUBAR\IMPORTANTFILE.TXT
user: Johnny - password: George1984!
The Windows Command Prompt supports redirection and piping:
C:\Users\Fubar>type importantfile.txt | find "password"
user: Johnny - password: George1984!
findstr
When findstr is provided more than one space-delimited string, it interprets the input as a logical OR. In other words, if findstr is provided two strings as input, it will search for occurrences of either of those strings.
C:\Users\Fubar>findstr "Johnny password" importantfile.txt
user: Johnny - password: George1984!
The more
command allow us to conveniently view the output. This is similar in behavior to the /P flag when executed with dir, but more lets us scroll one line at a time, whereas dir /P will scroll one "screen" at a time. Note that we can pipe the output of other commands to more, just as we did above with find.
The sort
command can be used to order output in a variety of ways. Lets say we have a text file full of unordered numbers, and we wish to order the contents beginning with the highest number. We can use the /R flag to do so.
Windows Access Controls and Security Principles
It is important to highlight that the Windows concepts of users and permissions are not identical to those of Linux.
Windows has more than three permissions, and it also defines more than three access categories. Further, Microsoft places a heavy emphasis on design for networked-based access, which increases the complexity. Given this design emphasis, it's interesting to note that even the base command to create and manage users on a Windows system is called net
.
Essentially, a security principal is a subject that the operating system can opt to (or not to) authenticate. Security principals are not limited to human user accounts. They include automated accounts, threads, processes, groups of users, and even parts of the OS itself.
Security principals are identified by security identifiers (SIDs). SIDs are alpha-numeric codes that uniquely identify principals on a Windows machine. Some SIDs are considered well-known, and they identify the same principal on every Windows OS. An example of a well-known SID is S-1-1-0
, which belongs to the Everyone
group. This SID includes all users on the machine.
SIDs do not need to be of a constant length. Some are quite short (as seen above), and others are much longer sequences of characters. We can check the SID of our current user with the whoami
command by providing it the /user
option:
C:\>whoami /user
USER INFORMATION
----------------
User Name SID
========================= ============================================
fubar-machine\fubar S-1-5-21-2753864161-1776656122-2845895175-1001
Each hyphen-separated number is called a component, and each component assigns values with specific meanings.
We won't delve into what each component means and their potential values here. The important takeaway is that the security identifier system provides Windows with a flexible and robust means of categorizing and referring to different security principals.
One important concept that makes use of SIDs are access control entries (ACEs) and access control lists (ACLs). An ACL is generally a dictionary of trustees and sets of permissions they've been assigned. In Windows, each element of an ACL is an ACE. There are six types of ACEs, and each ACE includes a SID, a set of access rights, and several flags that each indicate different properties.
SIDs are also used by the Local Security Authority (LSA) to assign access tokens to each user when they log on to an operating system. An in-depth exploration of the LSA and access tokens is beyond the scope of this topic. For now, note that a access tokens are protected objects containing a user's SID and any rights that they have on the OS.
Windows User and Group Permissions
Windows Local Accounts & Groups
Administrator: Administrator is a user account designed for the system administrator to manage the machine. Its SID is always S-1-5-domain-500. The Administrator has full permissions on all files and directories on the machine. This makes it an especially desired target during penetration tests and security audits. It’s important to note that the Administrator account is disabled by default on Windows 10. During initial account creation, another user account will usually be assigned administrative permissions to act in its stead. Such permissions are provided by means of membership to the Local Administrators group.
Guest: The Guest account lets non-users of the machine log on temporarily with restrictive permissions. It belongs to the Guests group, with SID S-1-5-32-546. By default, the Guest account is disabled, but when enabled it often has a blank password. It's important to note the implications of this from a security perspective, because if the guest account on a victim has been enabled, we can often log on to it.
SYSTEM: The SYSTEM account is used by the OS to run services that need elevated permissions. By default, it has all the permissions of the Administrator, but it isn't supposed to be logged-in to by a human user. That being said, some exploits can allow us to execute code in the context of its owner. If a process running as SYSTEM gets exploited, we might be able to impersonate the SYSTEM user itself.
We can use the net
command to add, remove, and modify user accounts and group membership on a local or networked machine. The net command contains a series subcommands that each perform a specific function.
C:\>net help
The syntax of this command is:
NET HELP
command
-or-
NET command /HELP
Commands available are:
NET ACCOUNTS NET HELPMSG NET STATISTICS
NET COMPUTER NET LOCALGROUP NET STOP
NET CONFIG NET PAUSE NET TIME
NET CONTINUE NET SESSION NET USE
NET FILE NET SHARE NET USER
NET GROUP NET START NET VIEW
NET HELP
NET HELP NAMES explains different types of names in NET HELP syntax lines.
NET HELP SERVICES lists some of the services you can start.
NET HELP SYNTAX explains how to read NET HELP syntax lines.
NET HELP command | MORE displays Help one screen at a time.
User Account Control
User Account Control(UAC) is an another security feature on Windows that has no standard Linux analogue. Its purpose, in general, is to protect aginst malicious actions by forcing an active human user to manually confirm administrative actions by means of a prompt, or message box.
The details of how UAC works is beyond the scope of this topic. For our purposes, we want to highlight three important takeaways.
- Windows SYSTEM and Administrator accounts aren't quite trusted with the same amount of power as root accounts on Unix-like machines.
- UAC is one of Microsoft's methods of applying the Principle of Least Privilege (POLP), which we covered in an earlier section. As a reminder, POLP says to give users, accounts, and systems access to only the things they need to get their job done.
- The pop-up windows that UAC triggers are an important phenomenon for an attacker to be aware of. If an attacker triggers UAC with a malicious action, the active user will likely become aware of the attempt. Strong attackers have a good model of what actions can trigger UAC, so that they can better avoid it.
runas
and cmd /c
C:\>runas
RUNAS USAGE:
RUNAS [ [/noprofile | /profile] [/env] [/savecred | /netonly] ]
/user:<UserName> program
RUNAS [ [/noprofile | /profile] [/env] [/savecred] ]
/smartcard [/user:<UserName>] program
RUNAS /trustlevel:<TrustLevel> program
/noprofile specifies that the user's profile should not be loaded.
This causes the application to load more quickly, but
can cause some applications to malfunction.
/profile specifies that the user's profile should be loaded.
This is the default.
/env to use current environment instead of user's.
/netonly use if the credentials specified are for remote
access only.
/savecred to use credentials previously saved by the user.
/smartcard use if the credentials are to be supplied from a
smartcard.
/user <UserName> should be in form USER@DOMAIN or DOMAIN\USER
/showtrustlevels displays the trust levels that can be used as arguments
to /trustlevel.
/trustlevel <Level> should be one of levels enumerated
in /showtrustlevels.
program command line for EXE. See below for examples
Examples:
> runas /noprofile /user:mymachine\administrator cmd
> runas /profile /env /user:mydomain\admin "mmc %windir%\system32\dsa.msc"
> runas /env /user:[email protected] "notepad \"my file.txt\""
NOTE: Enter user's password only when prompted.
NOTE: /profile is not compatible with /netonly.
NOTE: /savecred is not compatible with /smartcard.
Since runas
can execute commands with another user's permissions, it can be useful for attackers to attempt it if they obtain low-level access to a machine.
Another thing attackers can do with limited access to a target (say, via remote command execution) is to invoke the cmd.exe
binary itself. So far, we've been running cmd.exe
as a terminal with legitimate permissions to do so. However, since cmd.exe
is a binary that can get executed like any other, a remote attacker may be able to use it to execute individual arbitrary commands. We can do this with the /c
option, which runs the command it's provided as an argument and then terminates immediately.
C:\>echo hi
hi
C:\>cmd /c echo hi
hi
runas
is best used with a GUI interface, since it executes the desired command under a different context than the shell that starts it. Therefore, we'll be using the rdesktop
utility on Kali Linux to remotely connect to the Windows target GUI instead of our regular SSH connection.
The rdesktop
syntax is: rdesktop -u USERNAME -p PASSWORD IP-ADDRESS
. The -f
and -g
switches may also be useful for better visibility.
Introduction to Windows Permissions
Like Unix-based permissions, NTFS treats files and directories slightly differently. Let's learn about them one at a time.
The following is the basic set of permissions assignable to files.
- Read: Allows the user to view the contents of the file. Crucially, read also allows users to execute scripts.
- Write: Allows the user to write to the file. Note that write does not allow a user to delete the file, though they can delete its contents.
- Read & Execute: Allows the user to read the file, as well as execute binaries.
- Modify: Allows the user to read and write to the file. Also allows the user to delete it.
- Full Control: Allows the user to read, write, change, or delete the file.
Here is the basic set of permissions assignable to directories.
- Read: Allows the user to view and list any file in the directory.
- Write: Allows the user to add files or subfolders to the directory.
- Read & Execute: Allows the user to view and list any file or subfolder in the directory, and also allows execution of any binary within the folder.
- List Folder Contents: Allows the user to list any file or subfolder in the directory, and also allows execution of any binary within the folder. List Folder Contents appears on first glance very similar to Read & Execute. The difference between them is that Read & Execute allows for viewing the contents of files as well.
- Modify: Allows the user to read, write and delete files and subfolders within the directory.
- Full Control: Allows the user to read, write, change, and delete files and subfolders within the directory. Note that the Full Control permission on a directory allows the user to delete all files in it, even if they aren't assigned Modify or Full Control permissions on the files themselves.
These basic permissions are actually made up of a larger set of special permissions. These special permissions allow for more granular control over what users can do. We can think of the special permissions as building blocks that make up the basic ones, where the basic ones are just the most frequently used combinations.
One important concept to cover quickly is that of inheritance. In general, inheritance allows a parent entity to propagate attributes to its children. In the case of NTFS, inheritance has to do with the permissions assigned to a particular file or folder. By default, a particular file or folder inherits the permissions of the folder it is contained within.
The icacls
tool and its depracated predecessor, cacls
, are built-in executables that can display and modify permissions on files and folders.
C:\>icacls
ICACLS name /save aclfile [/T] [/C] [/L] [/Q]
stores the DACLs for the files and folders that match the name
into aclfile for later use with /restore. Note that SACLs,
owner, or integrity labels are not saved.
ICACLS directory [/substitute SidOld SidNew [...]] /restore aclfile
[/C] [/L] [/Q]
applies the stored DACLs to files in directory.
...
Towards the bottom of the extensive usage information, we can see that the various rights are coded with one to four characters:
perm is a permission mask and can be specified in one of two forms:
a sequence of simple rights:
N - no access
F - full access
M - modify access
RX - read and execute access
R - read-only access
W - write-only access
D - delete access
a comma-separated list in parentheses of specific rights:
DE - delete
RC - read control
WDAC - write DAC
WO - write owner
S - synchronize
AS - access system security
MA - maximum allowed
GR - generic read
GW - generic write
GE - generic execute
GA - generic all
RD - read data/list directory
WD - write data/add file
AD - append data/add subdirectory
REA - read extended attributes
WEA - write extended attributes
X - execute/traverse
DC - delete child
RA - read attributes
WA - write attributes
inheritance rights may precede either form and are applied
only to directories:
(OI) - object inherit
(CI) - container inherit
(IO) - inherit only
(NP) - don't propagate inherit
(I) - permission inherited from parent container
Here are some of the common options we might be interested in:
/T
executes the operation recursively on all subfolders/C
forces the operation to continue despite any errors/L
is used with symbolic links. It causes the operation to be executed on the link itself rather than its target.
We can supply a folder as input to icacls
to view its permissions.
C:\Users\Fubar>icacls Music
Music NT AUTHORITY\SYSTEM:(OI)(CI)(F)
BUILTIN\Administrators:(OI)(CI)(F)
Fubar-Machine\Fubar:(OI)(CI)(F)
Successfully processed 1 files; Failed processing 0 files
Earlier, we started to learn about ACEs and ACLs. An ACE represents a particular permission, and an ACL is just a list of the permissions. Above, each line of the output is considered an ACE. The values in parentheses indicate the inheritance properties and rights of the given user. For example, (OI)
stands for Object Inherit, which means the ACE will be inherited by files and folders placed within the directory. In this case all three users of the machine are granted full access to the file because of the F
flag.
We can use the /grant
and /deny
options to provide or remove rights to a file or folder.
c:\>icacls Music /grant Susan:(OI)(CI)(F)
processed file: Folder
Successfully processed 1 files; Failed processing 0 files
c:>icacls Music /t /c
Music NT AUTHORITY\SYSTEM:(OI)(CI)(F)
BUILTIN\Administrators:(OI)(CI)(F)
Fubar-Machine\Fubar:(OI)(CI)(F)
Fubar-Machine\Susan:(OI)(CI)(F)
Music\RockAndRoll NT AUTHORITY\SYSTEM:(OI)(CI)(F)
BUILTIN\Administrators:(OI)(CI)(F)
Fubar-Machine\Fubar:(OI)(CI)(F)
Fubar-Machine\Susan:(OI)(CI)(F)
...
One of the many programs included in the Sysinterals suite we downloaded earlier is called accesschk.exe
, or simply AccessChk. AccessChk is a robust auditing tool that can retrieve information on permissions across the entire operating system.
Note that we need to supply the full path to the file or execute it from the directory containing Sysinternals.
We can view the rights of a specific security principal by providing it as input to AccesssChk
. Let's see what kind of permisisons the users group has on the C:\
drive:
c:\Users\Fubar\Desktop\SysinternalsSuite>accesschk.exe "users" c:\
Accesschk v6.13 - Reports effective permissions for securable objects
Copyright ⌐ 2006-2020 Mark Russinovich
Sysinternals - www.sysinternals.com
RW c:\$Recycle.Bin
R c:\$WINDOWS.~BT
R c:\bootmgr
R c:\BOOTNXT
R c:\Documents and Settings
c:\MSOCache
c:\pagefile.sys
Error getting security:
The process cannot access the file because it is being used by another process.
c:\PerfLogs
R c:\Program Files
R c:\Program Files (x86)
RW c:\ProgramData
R c:\Python27
R c:\Recovery
c:\swapfile.sys
Error getting security:
The process cannot access the file because it is being used by another process.
c:\System Volume Information
R c:\Users
R c:\Windows
Windows Processes
Windows Processes
In this section we'll cover Windows processes. A process is the container in which a program runs, and a thread is a single running instance of that program. Microsoft uses the following analogy to describe the differences between threads, processes, and programs: A process is like a room, and a thread is like a person in that room. A program is the set of instructions that the person in the room will follow. The thread is the thing actually happening, the process is the environment in which it happens, and the program is the procedure that the thread executes.
Before we dive into Windows processes, we need to understand that there are two modes that an operating system can work in: Kernel mode and User mode. Generally, a computer will switch back and forth between these two modes, as it needs to execute many different tasks in short periods of time. Kernel mode is for the most trusted operations that the OS itself needs to execute. Processes running under Kernel mode have access to the physical machine's underlying hardware. On the other hand, User mode is for the vast majority of programs running on the computer, but processes running in User mode do not have access to the machine's hardware.
We mention this here because diving into Kernel mode processes is well beyond the scope of this topic. We will instead focus our attention on User mode processes.
As mentioned above, we won't cover kernel processes here, with one exception. System is a Kernel mode procedure responsible for core operating system mechanisms. It makes sure that the OS can talk to the machine's underlying hardware, and starts a cascade of other processes that each perform key User mode functionality. In particular, it is the parent of smss.exe
. Another way to say this is that it spawns smss.exe
.
smss.exe
: Session Manager is the first User mode process that's started on a Windows machine. It is primiarily responsible for mapping out virtual address space. It is actually spawned by System twice: one instance spawnswinlogon.exe
andcsrss.exe
and then exits, and the other stays alive to watch over the user's session. When it notices thatwinlogon.exe
orcsrss.exe
stop, it signals the OS to shutdown or crash, depending on the reason for the halt.winlogon.exe
: Windows Logon is responsible not only for authenticating users, but also for loading users' profiles. In addition, it performs an array of functions even after login. For example, it listen's for the famousC+Alt+Delete
key sequence that opens the security menu. Despite being started by another process, Windows Logon has no parent, because it is spawned by the instance ofsmss.exe
that exits immediately upon its creation. It is also the parent ofuserinit.exe
, which itself starts the user's initial shell and then exits. Usually,userinit.exe
startsexplorer.exe
.csrss.exe
: The Client Server Runtime Process is responsible for several background functions. It begins the shutdown sequence when terminated, and it is the parent of the process that eventually spawnscmd.exe
.explorer.exe
: Windows Explorer is responsible for rendering much of the Windows GUI shell that the user interacts with. It governs the Windows Start Menu, the Taskbar, and the System Tray. It is the parent of several children processes, but it has no parent itself, becauseuserinit.exe
exits as soon asexplorer.exe
is started.wininit.exe
: Windows Startup is responsible for triggering a crucial set of User mode applictions that must run to maintain the system's stability and functionality. Windows Startup is the parent of several children processes.
There are plenty of other essential Windows processes that we won't get into here. In particular, we will cover server-related processes like svchost.exe
in later topics.
The tasklist
command will list all running and currently-suspended processes on the machine:
C:\>tasklist
Image Name PID Session Name Session# Mem Usage
========================= ======== ================ =========== ============
System Idle Process 0 Services 0 8 K
System 4 Services 0 136 K
Registry 124 Services 0 34,532 K
smss.exe 428 Services 0 1,200 K
csrss.exe 628 Services 0 5,576 K
wininit.exe 780 Services 0 7,032 K
csrss.exe 788 Console 1 5,440 K
winlogon.exe 888 Console 1 12,120 K
services.exe 948 Services 0 10,264 K
lsass.exe 968 Services 0 22,064 K
svchost.exe 668 Services 0 28,920 K
...
We can note a few things right away: System always runs with a PID of 4
. In addition, System Idle Process runs with a PID of 0
. Essentially, the Idle Process just runs when the OS has nothing else to spend cycles on.
One important option the /FI
flag, which allows us to parse results based on additional input. For example, we can view all processes running under SYSTEM's user context as follows:
C:\>tasklist /fi "USERNAME eq NT AUTHORITY\SYSTEM" /fi "STATUS eq running"
Image Name PID Session Name Session# Mem Usage
========================= ======== ================ =========== ============
csrss.exe 788 Console 1 5,448 K
NVDisplay.Container.exe 2892 Console 1 46,768 K
rundll32.exe 5388 Console 1 7,280 K
...
We can use the taskkill
command to terminate a process by specifying its process ID or image name.
Let's use taskkill
to terminate our cmd.exe
process. We know from above that cmd.exe
is running as PID 84
, so let's use that knowledge now to end it:
C:\>taskkill /PID 84
Sysinternals Process Utilities
The Sysinternals Suite contains several tools that can help us manage and analyze processes. The pslist
tool is like an enhanced and more detailed version of tasklist
. Lets check the usage information with the standard /?
flag:
C:\Users\Fubar\Downloads\SysinternalsSuite>pslist /?
PsList v1.4 - Process information lister
Copyright (C) 2000-2016 Mark Russinovich
Sysinternals - www.sysinternals.com
Usage: pslist [-d][-m][-x][-t][-s [n] [-r n] [\\computer [-u username][-p password][name|pid]
-d Show thread detail.
-m Show memory detail.
-x Show processes, memory information and threads.
-t Show process tree.
-s [n] Run in task-manager mode, for optional seconds specified.
Press Escape to abort.
-r n Task-manager mode refresh rate in seconds (default is 1).
\\computer Specifies remote computer.
-u Optional user name for remote login.
-p Optional password for remote login. If you don't present
on the command line pslist will prompt you for it if necessary.
name Show information about processes that begin with the name
specified.
-e Exact match the process name.
-nobanner Do not display the startup banner and copyright message.
pid Show information about specified process.
All memory values are displayed in KB.
Abbreviation key:
Pri Priority
Thd Number of Threads
Hnd Number of Handles
VM Virtual Memory
WS Working Set
Priv Private Virtual Memory
Priv Pk Private Virtual Memory Peak
Faults Page Faults
NonP Non-Paged Pool
Page Paged Pool
Cswtch Context Switches
Just as Sysinternals has an analogue for tasklist
, so it does too for taskkill
. We can use the pskill
tool to terminate local and remote processes by supplying it with a PID or name.
C:\Users\Fubar\Downloads\SysinternalsSuite>pskill /?
PsKill v1.16 - Terminates processes on local or remote systems
Copyright (C) 1999-2016 Mark Russinovich
Sysinternals - www.sysinternals.com
Usage: pskill [-t] [\\computer [-u username [-p password]]] <process ID | name>
-t Kill the process and its descendants.
-u Specifies optional user name for login to
remote computer.
-p Specifies optional password for user name. If you omit this
you will be prompted to enter a hidden password.
-nobanner Do not display the startup banner and copyright message.
We can use pssuspend
to either suspend or resume a process on a local or remote system. This is useful for situations where we would rather temporarily stop a process, rather than kill it completely. If we supply no options to the command, it will suspend the provided process, and if we supply the -r
switch, it will resume the provided process.
We can use the listdlls
command to check which DLLs are called upon by various processes.
We can use the -u
switch to list any unsigned DLLs. This can be helpful to locate any potentially untrusted code running on the system:
C:\Users\Fubar\Downloads\SysinternalsSuite>listdlls -u
Listdlls v3.2 - Listdlls
Copyright (C) 1997-2016 Mark Russinovich
Sysinternals
...
unsigned.exe pid: 4992
Command line: "unsigned.exe"
Base Size Path
0x0000000080000000 0x5000 C:\WINDOWS\system32\Unsigned2.dll
Verified: Unsigned
Publisher: 2021-03-18 Fubar
Description: Example Unsigned DLL
Product: PEN-100
Version: 1.3.3.7
File version: 1.3.3.7
Create time: Sun Mar 18 20:11:25 2021
Windows Dynamic Link Libraries
Libraries are repositories of functions that can easily be imported into other programs. Windows uses Dynamic-Link Libraries (DLLs), which are themselves actually written in the same format as .exe files.
On 64-bit versions of Windows, DLLs and system executables are stored in System32 and SysWOW64. As we touched on in a previous section, System32 contains 64-bit libraries and SysWOW64 contains 32-bit libraries. On 32-bit version of Windows, all system-wide libraries are located in System32.
HAL.DLL
: The Hardware Abstraction Layer is a Kernel mode library file and it cannot be used by any User mode programs. It performs multiple functions related to the system's underlying hardware.NTDLL.DLL
: The New-Technology DLL allows User mode programs to call upon the Windows Native API. The Native API is used when other more robust APIs are unavailable, such as during system startup. For example, the aformentionedcsrss.exe
calls uponNTDLL.DLL
functionality.KERNEL32.DLL
: This DLL allows applications to call upon most of the Win32 base APIs involving things like memory management, input and output operations, and more. As an example of how DLLs can be used by other code,KERNEL32.DLL
itself implements much of its functionality by calling uponNTDLL.DLL
code.USER32.DLL
: Allows applications to call upon objects making up the user interface, like the desktop, taskbar, and Start menu.ADVAPI32.DLL
: Allows applications to call upon security features as well as functions that manipulate the Registry. We'll discuss the Registry in detail in the following section.
There are many more DLLs that Windows runs on. It is outside the scope of this topic to go through them all; however, we encourage you to review this list should you be interested in learning more about Windows core libraries.
Windows Registry
Windows Registry Overview
The Windows Registry acts as a central database for the OS. The Registry is important to understand from a security perspective because it contains the most critical system information. This information is constantly referenced by the OS and by applications during startup as well as during regular system operation.
Through the Registry, we can access both system information and user information. In additon, we can use it to control which services and applications get executed on the system.
A full exposition of the Registry is well beyond the scope of this course so we'll be focusing on gathering a high-level understanding. The basic unit of data within the Registry is called a key, which is similar to a directory. The Registry uses a hierarchical structure, so every key can contain additional subkeys or subdirectories, but they can also contain specific values. Each value has a name, a data type, and data content.
When an application wants to write data in the registry, it needs to open the relevant key. To open a key, the application must provide the name of the desired key to another, already opened key. We might ask ourselves if this seems a bit circular: to open keys we seem to need to open keys.
Windows solves this apparent paradox with the concept of predefined keys. Predefined keys start and stay open, so they can be always be invoked by applications. Here is a list of some of the predefined keys and a short description. For a more extensive explanation of theses keys, please see the resources section.
HKEY_CLASSES_ROOT (HKCR)
: Provides information related to file types and properties. The subkeys under HKCR are often used by shell applications (such as the Command Prompt) and by Component Object Model (COM) applications.HKEY_CURRENT_CONFIG (HKCC)
: Provides information related to the hardware configurations upon which the OS is running, specifically in comparison to the default configuration.HKEY_CURRENT_USER (HKCU)
: Provides information related to the setting configurations of the current user. Note that the HKCU key and subkeys will be different depending on what user is logged in, including SYSTEM.HKEY_LOCAL_MACHINE
: Provides information about the local machine related to input/output devices, memory, and drivers.HKEY_PERFORMANCE_DATA
: Provides information related to system performance. Notably, data associated with this key isn't stored within the Registry itself but is rather referenced by Registry functions.HKEY_USERS
: Provides information related to the default settings assigned to new users.
In order to better organize keys and subkeys, the Registry employs the concept of hives. A hive is a set of keys and their values. Each hive has specific files associated with it that get loaded into memory upon a trigger, for example, when the system is booted up or when a user authenticates.
Windows Registry Values
The Run and RunOnce Registry keys allow applications to run upon user authentication. In a nutshell, any program that is specified as a value of one of these keys will be started once a user logs in. Multiple programs can be included within the value of a given key.
By default, there are four Run and RunOnce keys, which live under HKEY_LOCAL_MACHINE and HKEY_CURRENT_USER:
HKEY_LOCAL_MACHINE\Software\Microsoft\Windows\CurrentVersion\Run
HKEY_CURRENT_USER\Software\Microsoft\Windows\CurrentVersion\Run
HKEY_LOCAL_MACHINE\Software\Microsoft\Windows\CurrentVersion\RunOnce
HKEY_CURRENT_USER\Software\Microsoft\Windows\CurrentVersion\RunOnce
The difference between the Run and RunOnce keys is that the values of the latter will be deleted from the key as soon as the program(s) are run.
C:\>reg /?
REG Operation [Parameter List]
Operation [ QUERY | ADD | DELETE | COPY |
SAVE | LOAD | UNLOAD | RESTORE |
COMPARE | EXPORT | IMPORT | FLAGS ]
Return Code: (Except for REG COMPARE)
0 - Successful
1 - Failed
For help on a specific operation type:
REG Operation /?
Examples:
REG QUERY /?
REG ADD /?
REG DELETE /?
REG COPY /?
REG SAVE /?
REG RESTORE /?
REG LOAD /?
REG UNLOAD /?
REG COMPARE /?
REG EXPORT /?
REG IMPORT /?
REG FLAGS /?
Scheduling Tasks on Windows
The Windows Task Scheduler allows us to schedule computer programs or scripts to run at pre-defined times or upon certain triggers. The scheduler has functionality that is analogous to cronjobs on Linux.
C:\>schtasks /?
SCHTASKS /parameter [arguments]
Description:
Enables an administrator to create, delete, query, change, run and
end scheduled tasks on a local or remote system.
Parameter List:
/Create Creates a new scheduled task.
/Delete Deletes the scheduled task(s).
/Query Displays all scheduled tasks.
/Change Changes the properties of scheduled task.
/Run Runs the scheduled task on demand.
/End Stops the currently running scheduled task.
/ShowSid Shows the security identifier corresponding to a scheduled task name.
/? Displays this help message.
Examples:
SCHTASKS
SCHTASKS /?
SCHTASKS /Run /?
SCHTASKS /End /?
SCHTASKS /Create /?
SCHTASKS /Delete /?
SCHTASKS /Query /?
SCHTASKS /Change /?
SCHTASKS /ShowSid /?
Windows Disk Utilities and Alternate Data Streams
In terms of built-in utilities, Windows comes with the fsutil set of programs that can manage drives. We can see the full list of tools included in the suite by invoking the command with no parameters:
C:\>fsutil
---- Commands Supported ----
8dot3name 8dot3name management
behavior Control file system behavior
dax Dax volume management
dirty Manage volume dirty bit
file File specific commands
fsInfo File system information
hardlink Hardlink management
objectID Object ID management
quota Quota management
repair Self healing management
reparsePoint Reparse point management
storageReserve Storage Reserve management
resource Transactional Resource Manager management
sparse Sparse file control
tiering Storage tiering property management
transaction Transaction management
usn USN management
volume Volume management
wim Transparent wim hosting management
Note that the
/?
option does not work withfsutil
. Instead we'll need to reference a particular subcommand with no additional arguments to understand what it does.
Now that we know a little bit more about NTFS, we can consider the dir /R
option which is useful for identifying Alternate Data Streams (ADS).
A stream is a property of files under NTFS that essentially allows us to store content within arbitrary sections of the file. When we create a new file, the content is stored in the default data stream. When we want to retrieve the contents (say, with type), we will read from that default stream.
ADS allows files to contain multiple data streams. We can place content in a new data stream with the :<stream>
syntax using echo
:
C:\streamtest>echo fileOne uses the default stream > defaultStream.txt
C:\streamtest>echo fileTwo uses the 'Fubar' stream > FubarStream.txt:Fubar
C:\streamtest>type defaultStream.txt
fileOne uses the default stream
C:\streamtest>type FubarStream.txt
C:\streamtest>dir
Volume in drive C has no label.
Volume Serial Number is 523D-9369
Directory of C:\streamtest
2021-06-03 03:39 PM <DIR> .
2021-06-03 03:39 PM <DIR> ..
2021-06-03 03:38 PM 34 defaultStream.txt
2021-06-03 03:39 PM 0 FubarStream.txt
2 File(s) 34 bytes
2 Dir(s) 31,895,818,240 bytes free
C:\streamtest>dir /r
Volume in drive C has no label.
Volume Serial Number is 523D-9369
Directory of C:\streamtest
2021-06-03 03:39 PM <DIR> .
2021-06-03 03:39 PM <DIR> ..
2021-06-03 03:38 PM 34 defaultStream.txt
2021-06-03 03:39 PM 0 FubarStream.txt
35 FubarStream.txt:Fubar:$DATA
2 File(s) 34 bytes
2 Dir(s) 31,939,903,488 bytes free
Interesting, dir
still reports the total space usage to be 34 bytes; this result does not include the 35 bytes belonging to FubarStream.txt. We can use du
to view the true disk usage:
C:\Users\Fubar\Downloads\SysinternalsSuite>du c:\streamtest
DU v1.62 - Directory disk usage reporter
Copyright (C) 2005-2018 Mark Russinovich
Sysinternals - www.sysinternals.com
Files: 2
Directories: 1
Size: 69 bytes
Size on disk: 12,328 bytes
To view the contents of the ADS, use more
:
C:\streamtest>more < FubarStream.txt:Fubar
fileTwo uses the 'Fubar' stream
Note that we had to use the "<" character to pass the contents of FubarStream.txt to standard input first, and then to redirect it to more. This is because passing an ADS directly to more does not work either:
C:\streamtest>more FubarStream.txt:Fubar
Cannot access file C:\streamtest\FubarStream.txt:Fubar
Relevant Note(s): Information Technology Linux Basics