Introduction to Windows System Internals part I by

Introduction to Windows System Internals part I by Tim Shelton Black Security redsand@blacksecurity. org

Outline � Brief History of the Windows Operating Systems � Unicode Explained � Registry Basics � Windows Services (services. exe) � Startup & Shutdown Procedures � Q&A

Windows History Overview � Microsoft formed its team of 20 developers in November 1988 � 4 core developers wrote key components � Began a dream to write an Advanced Operating System � Designed for Desktops and Servers � Secure, scalable Multi-Processor design � All new code base

Windows History Overview Cont. �Microsoft announced its commitment to rigorous discipline �Developers are required detailed documentation �Developers are required peer code review �Developers are required to unit test their code. .

Windows History Overview Cont. �Past – Personal Computing, 16 -32 bits, Windows 9 x code base, objective: bringing computers to the consumer. Features – usability and compatibility �Present – Enterprise Computing, 32/64 bits, NT code base, solid architectural foundation, objective: reliability, performance, and to meed the demands for Server Processing. �Future – Managed Code (. NET Framework), objective: World Domination (go figure!) Longhorn.

Commitment of the NT Architecture �Reliability – Crash proof Operating System �Security – Built into design from day one. �Portability – Multi-processor support, avoiding nonportable solutions, flexible hardware abstraction Layer �Modularity – Space to grow and needs to be fulfilled. �Performance – Microsoft is willing to sacrifice performance for all of the above.
![Common Windows Internal Tools File Monitor – [filemon] www. sysinternals. com � �List DLLs Common Windows Internal Tools File Monitor – [filemon] www. sysinternals. com � �List DLLs](http://slidetodoc.com/presentation_image_h/0f59288f55cc4d41bc109cee8407c463/image-7.jpg)
Common Windows Internal Tools File Monitor – [filemon] www. sysinternals. com � �List DLLs loaded within specific process' virtual address space – [listdlls] www. sysinternals. com �Kernel Debuggers [windbg, kd] Platform SDK and Windows SDK �Live Kernel Debugging [livekd] www. sysinternals. com �Object Viewer – [winobj] www. sysinternals. com �Process Explorer – [procexp] replacement for taskmgr and much more! www. sysinternals. com �And More! Visit the Platform SDK or www. sysinternals. com

Add text output/ screen shots here and next few slides


Unicode and Language Independence �Most internal text strings are stored and processed as 16 -bit Unicode characters. �Unicode is an international character set standard that defines unique 2 byte values (maximum 65536 characters) for most of the world's known character sets. �References: www. unicode. org Or MSDN Documentation

Unicode and Language Independence Cont. �Because most applications use 8 -bit ANSI character sets, Windows functions that accept string parameters have two entry points: a Unicode and an ANSI version. Ex: Create. Process. A and Create. Process. W (found in kernel 32. dll) �Lesson learned: Use Unicode for multi-lingual support.

Windows Registry �Hives located in %System. Root%Config � A Hive is a logical file system within a flat file. Keys == directories Values == files �Registry is a collection of “Hives”. �A Hive contains a collection of “Bins”. �A Bin contains a collection of “Cells”. �Each Cell is a unit of allocation containing raw data

Windows Registry Cont. �Below are a few Example NT API’s available for managing the Windows Registry: Nt. Enumerate. Value. Key(KHANDLE, int); Nt. Query. Value. Key(KHANDLE, Var. Name); Nt. Load. Key(KHANDLE, Hive. File. Name); … more found in Advapi 32. dll

�A Windows Registry Cont. Hive is a file (two if you count the. LOG) - Primary: holds the actual hive data -. LOG: used when flushing the hive (crash recovery) �Storage Mapping Types: - Stable: maps to the hive file - Volatile: mapped into paged pool of memory, lost after reboot. �Primary file grows in 256 k increments to prevent fragmentation. First page (4 k) is the registry header, followed by chained Bins

Windows Registry Cont. �A Cell is the unit of storage allocation within a Hive. �Always 8 -byte aligned. �Always reuse free cells if one with the same or greater exists. � If size is bigger, then split it and re-enlist in free cell table.


Windows Registry Cont. �Keys, Values, Security Descriptors, Indexes, etc. are all made up of Cells. �Retrieving a value within a Key might involve several faults spread across the Hive file. - Solution: Registry Hive Caching (Win 2 k), locality enforcement (XP/. NET) to help with performance.

Registry: Hive Flush �Most “expensive” operation, called externally by Nt. Flush. Key/Reg. Flush. Key, or anytime a value is written to the Hive. (Set. Value, Delete. Value, Create. Key, Delete. Key, etc). Automatic Flush at Shutdown/Reboot �“Lazy Flush” waits 5 seconds after write then walks the list of Hives looking for Cells marked as ‘Dirty’. Ignores Hives marked as NO_LAZY_FLUSH. �During Flush, registry is marked as read-only �No data is written to the Hive File until the Flush is completed. This may lead to a possible loss of data.

Registry: Loading the Hive �Loaded at boot time by Boot Loader (NTLDR) and the kernel (ntoskrnl. exe) �Explicitly loaded by calling Nt. Load. Key/Reg. Load Key - This requires ‘Restore’ security privileges. �Files are opened in “exclusive” mode; and kept open by the kernel. �Read Primary header and verify checksums, if failed: - Physical integrity check, walk entire Hive and check each individual cell - Logical integrity check, walk the tree check every key/value.

Registry: Hives Locations �Two distinct User hives per account. Located in %USERPROFILE% - NTUSER. DAT: Mounted under HKEY_USERSSID roaming enabled (if roaming profiles are used) - Usr. Class. DAT: local (no roaming) �Special hives similar to above; always loaded: - S-1 -5 -18: SYSTEM account - S-1 -5 -19: Local Service - S-1 -5 -20: Network Service

Registry: Review �Registry is intended to maintain configuration data. �Stored in a special, highly tuned flat file. �Native APIs can be found within Advapi 32 �Used by the kernel, drivers, internal system, applications, security, policies, and more…

Services Explained What are services? �Processes that run without the need for an interactive logon. �This is the Windows equivalent of the UNIX daemon.

NT Services �Started early during boot process by winlogon. exe �Responsible for enforcing service load order and dependencies. �Starts all service processes marked for load on boot. �Manages all service processes - Only allows access to service via API - Access guarded by use of access checks. �Can be configured to run under any account (such as Local. System).

NT Services �Examples of common services: - spoolsv. exe (Print Spooler running as Local. System only) - svchost. exe (Generic host, any account) - services. exe (Eventlog, Plug ‘n Play running as NT AuthoritySYSTEM privileges. ) �Services register with both a Service Name and a Service Description. - ex: ALG vs. Application Layer Gateway Service

NT Services �Configuration: HKLMSYSTEMCurrent. Control. SetServices �Follows the Service Programming Model: - Requires Service. Main and Handler (Ex) - Multiple services within each process must implement its own Service. Main �If service is its own executable, it must call Start. Service. Ctrl. Dispatcher in Win. Main which will in turn call Service. Main.

svchost. exe �Individual services can be configured to run within svchost. exe - Initialized within configuration during Service Creation - %System. Root%system 32svchost. exe –k <service name> - svchost Service list is static, instance must be added to: HKLMSoftwareMicrosoftWindowsSvchost �When svchost begins, it will read the list of services and setup a generic Service. Main routine.

Startup Procedure Files Required for Successful Boot: NTLDR Boot Loader Boot. ini Boot Configuration Ntdetect. com Detect Hardware for Boot Ntoskrnl. exe Core Kernel binary SYSTEM Registry Hive System Configuration Device drivers Hal Hardware Support

Startup Procedure Initially the Boot Sector will find and load Ntldr. Below are the steps of Ntldr: § When NTLDR runs, it switches the processor into 32 -bit flat memory mode (until this point the computer was running in real mode (just like your old 8086 or 8088 CPU). § It then starts the appropriate mini-file system (e. g. : FAT, NTFS), so that it can read the files from the disk. § It will then read the Boot. ini file, and display the boot menu on the screen.

Startup Procedure Ntldr Continued: § If an OS other than Windows 2000 is selected, NTLDR then loads the bootsect. dos file and passes control to it, which then boots the other OS. § If a Windows OS is selected, then NTLDR runs Ntdetect. com to gather information about the computer's hardware. – Hardware includes: Computer ID, Video Adapter, Keyboard, etc. Computer ID § It is also in this step when you can choose to press F 8 for troubleshooting and advanced startup options.

Startup Procedure Ntoskrnl begins the first of two phases: § Disable Interrupts § Calls Ki. System. Startup -> Hal. Initialize. Processor -> Ki. Initialize. Kernel (per cpu) § Proceeds to call Exp. Initialize. Executive which loads critical resource management interfaces. (Plug ‘n Play, Security Monitor, Memory Manger) Phase two begins: § Ntoskrnl re-enables Interrupts and displays the Windows Boot Status Screen § Ntoskrnl loads the HARDWARE Registry hive § Ntoskrnl proceeds to initialize the necessary drivers

Startup Procedure This step begins with the starting of the Session Manager (Smss. exe) § Smss, being a native application, can perform unique actions. – Creation of Security Tokens – Uses its own native API, unavailable to the rest of Windows § Smss’s first task is initializing the rest of the Registry Hive § Smss then runs any programs defined in HKLMSYSTEMCurrent. Control. SetControlSession ManagerBoot. Execute § Smss loads the Windows Subsystem (Win 32 k. sys) § Smss then loads Csrss and Winlogon

Startup Procedure Winlogin and Csrss § Winlogon then performs its startup steps such as creating the initial window station and desktop objects. § Winlogon then loads Msgina. dll (or replacement) to handle Wlx. Logged. Out. SAS, displaying the standard Windows logon dialog box. § Winlogon creates the Service Control Manager (SCM) or services. exe – Loads all the necessary services marked for auto-start – Loads the Local Security Authentication Subsystem (Lsass)

Startup Procedure Winlogin and Csrss § SCM deems boot success and updates “Last Known Good Configuration” located at HKLMSYSTEMSelectLast. Known. Good to match Current. Controlset

Startup Procedure Post Authentication § Winlogon: maps HKCU and sets the User Environment stored in HKCUEnvironment § Msgina: loads executables within HKLMSoftwareWindows NTCurrent. VersionWin. LogonUserinit § Userinit. exe: processes user scripts and machine logon scripts § If group policy specified, user quota loaded (%System. Directory%Proquota. exe) § Launches comma-seperated shell(s) specified in HKCUSoftwareMicrosoftWindows NTCurrent. VersionWinlogonShell (default is Explorer. exe)

Shutdown Procedure Exit. Windows. Ex() § Csrss impersonates the caller and sends a Windows Message to a hidden window owned by Winlogon, telling it to shutdown § Csrss traverses through each user process “informing” it of its intentions. § Csrss calls Exit. Windows. Ex() once again within System space, informing csrss to kill any processes owned by SYSTEM. § Winlogon calls Nt. Set. System. Power. State – Sends shutdown I/O packets to all device drivers that have requested shutdown notification. – Winlogon then sets the power status to the required request. (Shutdown, Reboot)

Questions? Now is the time to hit me with all you got!

Kill() Time() Windows Shattr Attacks Windows Create. Remote. Thread Injection DLL Detach Injection
- Slides: 37