├── Day1 └── readme.md ├── Day2 └── Readme.md ├── Day3 └── Readme.md ├── Day4 └── Readme.md ├── Day5 └── Readme.md ├── Day6 └── Readme.md ├── Day7 └── Readme.md ├── Day8 └── Readme.md ├── Day9 └── Readme.md └── README.md /Day1/readme.md: -------------------------------------------------------------------------------- 1 | # Concept and Tools 2 | 3 | ## Windows API Flavours 4 | 5 | ### Windows API 6 | 7 | - Windows appplication programming Interface is the user mode system programming interface to windows OS family. 8 | - All the older API is written in C/C++ 9 | - C was chosen because it was that low enogh that can easily interact with OS Services 10 | 11 | ### OLE 12 | - Object Linking and Embedding enables microsoft office applications to communicate and exchange data between documents(such as inserting an excel chart into mirosoft document) 13 | - OLE is based on DDE, Dynamic Data Exchange , which is an older method of data exchanging 14 | - DDE have some limitiation and secuity issues which have given rise to COM. Read here https://revelate.co/blog/dynamic-data-exchange/ 15 | 16 | ### Component Object Model 17 | - It helps in data excahnge using Interfaces, that we called as Windows API 18 | - The APIs can be easily called from any language like C, C++, Visual Baic, etc. 19 | 20 | ### Windows RunTime 21 | - The Windows Runtime (WinRT) is the technology that powers the Universal Windows Platform, letting developers write applications that are common to all Windows devices, from Xbox to PCs to HoloLens to phones. 22 | - WinRT APIs are easily accessible from managed languages like C#, however for native C++ developers, using WinRT either requires a lot of complex COM code, or the use of Visual C++ component extensions, better known as C++/CX 23 | - Read Here https://blogs.windows.com/windowsdeveloper/2016/11/28/standard-c-windows-runtime-cwinrt/ 24 | 25 | ## Services, Functions and routines 26 | 27 | ### Process 28 | - Process is a container for a set of resources used when executing the instance of the program 29 | - Process conains following things 30 | - Virtual Space : Set of virtual memory space that a process can used. 31 | - Executable Program : EXE 32 | - Open Handles : List of open handles of objects like semaphores,files,etc. that can be used by a process 33 | - Security Context: Basically an Access token which can specify what can be accessed by a process 34 | - process id: ID of the process 35 | - Atleast One thread 36 | 37 | #### Process Status 38 | - Status column will specify , what is the status of a process. It could be Running, Suspended, Not Responding 39 | - Running (Non UI) : If a process do not have UI , then Running means that the process is waiting for some kernel object being signaled or some I/O operation to complete 40 | - Running (UI) : If a process have a UI, then it means that it is waiting for some UI Input 41 | - Suspended : If a process loses its foreground UI (or user clicks on minimize option), then it goes into suspended state so that battery/power can be saved. 42 | - Not Responding : The process (actually the thread that owns the window) may be busy doing some CPU-intensive work or waiting on something else entirely. 43 | 44 | 45 | ### Threads 46 | - It is just an entity in a process 47 | - A process can have multiple threads 48 | - A process in independeent of other process running in the system, whereas threads are interdependent to each other 49 | - Theads shared memory with each other within a process, whereas process do not share memory with other processes. 50 | - By default, threads don’t have their own access token, but they can obtain one, thus allowing individual threads to impersonate the security context of another process—including processes 51 | on a remote Windows system—without affecting other threads in the process 52 | - A thread contain following things: 53 | - Content of CPU registers representing the state of processor 54 | - Two stacks , one for execution in kernel level, and one for execution in user mode. 55 | - TLS : Thread local storage , used by DLLs, runtime libraies, etc. 56 | - Thread ID : Unique ID of a thread 57 | - Red here more about process and threads : https://de-engineer.github.io/Processes-threads-jobs-fibers/ 58 | 59 | #### Thread Scheduling 60 | - They provide developers with the ability to implement custom scheduling algorithms that suit the specific needs of their applications. 61 | - Fibers and UMS are two types of thread scheduling mechanism. 62 | 63 | ### Jobs 64 | - Jobs function is to manage and manipulate groups of processess as unit. 65 | 66 | 67 | 68 | 69 | -------------------------------------------------------------------------------- /Day2/Readme.md: -------------------------------------------------------------------------------- 1 | ### Virtual Memory 2 | - This concept of virtual memory is helpful when a page (small chunk of memory, having default size of 4kb) wants to be loaded into the memory(secondary) but memory is not available, then in that particular scenario virtual memory comes into picture and allows some memory from RAM itself. 3 | - Virtual Memory is a storage scheme that provides user an illusion of having a very big main memory. This is done by treating a part of secondary memory as the main memory. 4 | - Read more about working of virtual memory here https://www.techtarget.com/searchstorage/definition/virtual-memory#:~:text=A%20system%20using%20virtual%20memory,having%20to%20purchase%20more%20RAM. 5 | - We will se more about Virtual memory working, translation of address in upcoming days. 6 | 7 | Note: A page, memory page, or virtual page is a fixed-length contiguous block of virtual memory, described by a single entry in the page table. It is the smallest unit of data for memory management in a virtual memory operating system. 8 | 9 | ### Kernel Mode vs User Mode 10 | 11 | #### Introduction 12 | - User application code runs in user mode, whereas OS code (such as system services and device drivers) runs in kernel mode. 13 | - Kernel mode refers to a mode of execution in a processor that grants access to all system memory and all CPU instructions. 14 | - These privilege levels or modes is called as rings. 15 | - When you open a process in user mode , the os createas a private virtual space because os wants to isolate the application's process from other process, so if a process crashes , it doesn't affect the other process. 16 | Whereas the kernel mode isn't isolated from the other drivers and the OS itself, so if a kernel driver crashes whole OS will crash 17 | ![POC](https://github.com/SecTheBit/Windows-Internals/assets/46895441/eaecc6a4-4e44-445a-ae64-71cf4b142413) 18 | 19 | #### Ring 20 | ![POC](https://github.com/SecTheBit/Windows-Internals/assets/46895441/73575372-a6c6-4a3e-bb47-dfa6d71c6993) 21 | - Kernel mode operates in ring 0 level, where it have access to all memory regions and CPU 22 | - Every applications running in normal user context will work in ring 3 level. 23 | - The OS uses ring 1 to interact with the computer’s hardware. This ring would need to run commands such as streaming a video through a camera on our monitor. Instructions that must interact with the system storage, loading, or saving files are stored in ring 2. 24 | 25 | #### Memory Regions 26 | - Pages in kernel/system mode space can be accessible from system itself not from user mode. 27 | - Pages in user mode space can be accessible from both user and kernel mode 28 | - Page which are not writable (only redable) cannot be writable from any mode 29 | - Additionally, on processors that support no-execute memory protection, Windows marks pages containing data as non-executable, thus preventing inadvertent or malicious code execution in data 30 | areas (if this feature, Data Execution Prevention [DEP] is enabled 31 | - Windows doesn’t provide any protection for private read/write system memory being used by components running in kernel mode. In other words, once in kernel mode, OS and device-driver code 32 | has complete access to system-space memory and can bypass Windows security to access objects. 33 | - This lack of protection also emphasizes the need to remain vigilant when loading a third-party device driver, especially if it’s unsigned, because once in kernel mode, the driver has 34 | complete access to all OS data 35 | 36 | #### Driver signing 37 | - If someone loads a malicious driver in kernel mode, then the attacker have access to all memory region and CPU which is not good from a security perspective. 38 | - Keeping the security in mind, microsoft introduces a siginificant approach to deal with the problem, which is basically signing the drivers from legitimate authorities. 39 | - For windows 10, all the kernel drivers must be signed by the two of the accepted certification authorities with SHA1 Extended Validation(EV) Hardware certificate, and once the driver is signed, it must be submitted to microsoft through System Device (SysDev) portal for attestaion signing. This step ensures that drives receives one more signature from microsoft. 40 | - On top of the aforementioned EV requirements, mere attestation signing is insufficient. For a Windows 10 driver to load on a server system, it must pass through stringent Windows Hardware Quality Labs (WHQL) certification as part of the Hardware Compatibility Kit (HCK) and be submitted for formal evaluation, then only driver can be loaded into kernel mode. 41 | - This is how microsoft protects the OS from malicious drivers. 42 | 43 | #### Context Switch 44 | - When a user level application wants to perform an action which is only possible in kernel mode like accessing hardware, modifying system settings, then it make syscalls to kernel which helps in doing such operations. 45 | - This switching between user mode to kernel mode called as Context switching 46 | - Mode switching can be time-consuming and resource-intensive, and can impact system performance 47 | - Modern operating systems use various techniques to minimize mode switching, such as caching kernel mode data in user mode, and using hardware support for virtualization and context 48 | switching. 49 | - Read more in depth https://www.geeksforgeeks.org/user-mode-and-kernel-mode-switching/ 50 | 51 | ### Windows Registry 52 | - It is a database that contains all information needed to boot and configure the system, system-wide software settings that control operation of windows , the security database and user settings and configurtions. 53 | - It also contains information about current harware settings, loaded device drivers , resources being used by device drivers,etc. 54 | - Registry keys are containers that act like folders, with values or subkeys contained within them. 55 | - The main branches of the registry are called hives. And most PCs have five of them. All the folders in the registry are called keys except for these five hives 56 | - HKEY_CLASSES_ROOT 57 | - HKEY_CURRENT_USER 58 | - HKEY_LOCAL_MACHINE 59 | - HKEY_USERS 60 | - HKEY_CURRENT_CONFIG 61 | - Inside these hives are more folders called keys. Keys contain values, which are the settings themselves. 62 | - Reference https://www.avast.com/c-windows-registry 63 | 64 | 65 | -------------------------------------------------------------------------------- /Day3/Readme.md: -------------------------------------------------------------------------------- 1 | ## Digging into Windows Internals 2 | ### View Exported Function 3 | - For viewing exported functions in a DLL, you can use Dependency Walker http://www.dependencywalker.com 4 | - Just open the tool and click on open file and choose kernel32.dll from C:\windows\System32 5 | ![POC](https://github.com/SecTheBit/Windows-Internals/assets/46895441/093d2c22-0b7c-4da9-b768-60cd0ec0e9a3) 6 | 7 | ### Kernel Debugging 8 | - Kernel Debugging means examining the internal kernel data structure or stepping through functions in the kernel 9 | - There are particular set of files that we need in order to do kernel debugging, called as symbol files. 10 | - When applications, libraries, drivers, or operating systems are linked, the linker that creates the .exe and .dll files also creates a number of additional files known as symbol files. 11 | - Symbol files hold a variety of data which are not actually needed when running the binaries, but which could be very useful in the debugging process. 12 | - Symbol files contain the names of functions and variables and the layout and format of data structures. They are generated by the linker and used by debuggers to reference and display these 13 | names during a debug session. Read more about symbol files here https://learn.microsoft.com/en-us/windows-hardware/drivers/debugger/symbols-and-symbol-files 14 | - To use any of the kernel-debugging tools to examine internal Windows kernel data structures such as the process list, thread blocks, loaded driver list, memory usage information, and so on, 15 | we must have the correct symbol files for at least the kernel image, Ntoskrnl.exe 16 | - For now, we will use windbg to see basics of kernel debugging 17 | - We will do the local machine , due to which we will only have read access to kernel, because we won't be able to set up breakpoints on the machine on windbg is running. 18 | - You can download windbg from here https://learn.microsoft.com/en-us/windows-hardware/drivers/debugger/ 19 | - Let's examine our own kernel 20 | 21 | ### Windbg Usage 22 | 23 | * Getting Details of all Process using command ``` !process``` 24 | ![POC](https://github.com/SecTheBit/Windows-Internals/assets/46895441/f14e22fc-9d06-47fd-a4fe-427adf7b8624) 25 | 26 | * View all function in a kernel (click on nt -> functions) 27 | ![POC](https://github.com/SecTheBit/Windows-Internals/assets/46895441/93f08086-8f6c-4cb8-aa17-418db08a7512) 28 | 29 | * View all the modules in the kernel (You can observer the "nt" module, "Ntoskrnl", which is heart of the kernel) 30 | ![POC](https://github.com/SecTheBit/Windows-Internals/assets/46895441/7e3b1e35-2d09-4129-8395-f07447d2d4f1) 31 | 32 | * Display memory (bytes and ascii text) 33 | ![POC](https://github.com/SecTheBit/Windows-Internals/assets/46895441/fd24760e-54e9-4b4e-9bac-054e60bdc219) 34 | 35 | * View Functions in Ntoskrnl Kernel Image 36 | ![POC](https://github.com/SecTheBit/Windows-Internals/assets/46895441/5a3890cc-c8d9-46ff-bd9f-8253f725e4a3) 37 | 38 | * View Disassemble funtions (few bytes) 39 | ![POC](https://github.com/SecTheBit/Windows-Internals/assets/46895441/1a840017-a9c4-48a0-98ce-787b5535394d) 40 | 41 | ### Refrences 42 | https://samsclass.info/126/proj/PMA410d.htm 43 | https://www.youtube.com/watch?v=V75-TF8QOUI 44 | 45 | 46 | 47 | 48 | 49 | 50 | 51 | 52 | -------------------------------------------------------------------------------- /Day4/Readme.md: -------------------------------------------------------------------------------- 1 | ## System Architecutre 2 | 3 | ### Architecute Overview 4 | 5 | ![image](https://github.com/SecTheBit/Windows-Internals/assets/46895441/91e51cce-858c-49e3-aa37-d4c09d6656ab) 6 | 7 | W will first try to get a very high overview of the above architecture, starting with the four type of user mode process, given in the above diagram 8 | 9 | - User Processs: These can be of following types, windows 32 bit and 64 bit , Windows 3.1 16-bit, MS-DOS 16-bit, or POSIX 32-bit or 64-bit. Note that 16-bitapplications can be run only on 32-bit Windows, and that POSIX applications are no longer supported as of Windows 8. 10 | - Service Process : These are the processes that host windows services such as Task Scheduler, Print spooler, etc. services. Services generally have the requirement that they run independently of user logons. 11 | - System Process: Process such as logon and session manager that are not started by service control manager 12 | - Environment Subsytem server process : We will see about this in coming days 13 | 14 | The kernel-mode components consist of following things: 15 | 16 | - Executive: It helps in managing base OS service like memory management,process and thead management, networking, security,I/O and inter process communication 17 | - The Windows kernel: This consists of low-level OS functions, such as thread scheduling, interrupt and exception dispatching, and multiprocessor synchronization. 18 | - Device Drivers: It includes both hardware and non-hardware drivers. 19 | - Hardware Abstraction Layer: This is a layer of code that isolates the kernel, the device drivers, and the rest of the Windows executive from platform-specific hardware differences 20 | - Hypervisor layer: Hypervisor itself. 21 | 22 | #### Hypervisor 23 | - All modern solutions employ the use of a hypervisor, which is a specialized and highly privileged component that allows for the virtualization and isolation of all resources on the machine, from virtual to physical memory, to device interrupts, and even to PCI and USB devices 24 | - Hypervisor has more access to OS than kernel itself 25 | - It can protect and monitor a single host instance to offer assurances and guarantees beyond what the kernel provides 26 | - In Windows 10, Microsoft now leverages the Hyper-V hypervisor to 27 | - provide a new set of services known as virtualization-based security (VBS): 28 | - Device Guard 29 | - Hyper Guard 30 | - Credential Guard 31 | - Application Guard 32 | - The key advantage of all these technologies is that unlike previous kernel-based security improvements, they are not vulnerable to malicious or badly written drivers, regardless of whether 33 | they are signed or not 34 | - This makes them highly resilient against today’s advanced adversaries. This is possible due to the hypervisor’s implementation of Virtual Trust Levels (VTLs). 35 | - Because the normal operating system and its components are in a less privileged mode (VTL 0), but these VBS technologies run at VTL 1 (a higher privilege), they cannot be affected even by 36 | kernel mode code, even if there is some malicious code running in the kernel. 37 | ![image](https://github.com/SecTheBit/Windows-Internals/assets/46895441/4cf7b4a5-cf23-4d58-8f5a-a08295cc32fa) 38 | 39 | - the regular user versus kernel rules apply, but are now augmented by VTL considerations.In other words, kernel-mode code running at VTL 0 cannot touch user mode running at VTL 1 becauseVTL 40 | 1 is more privileged. Yet, user-mode code running at VTL 1 cannot touch kernel mode running at VTL 0 either because user (ring 3) cannot touch kernel (ring 0) 41 | 42 | #### Environment subsytems and subsystems DLLs 43 | - The role of an environment subsystem is to expose some subset of the base Windows executive system services to application programs. Each subsystem can provide access to different subsets of the native services in Windows. 44 | - Each executable image (.exe) is bound to one and only one subsystem 45 | 46 | -------------------------------------------------------------------------------- /Day5/Readme.md: -------------------------------------------------------------------------------- 1 | ## Process and Jobs 2 | 3 | ### Creating a Process 4 | 5 | - CreateProcess is one of the functions provided by the Windows API which can helps in creating process 6 | - If above function gets called , then it will call a internal function CreateProcessInternal, which will helps in calling NtCreateUserProcess in ntdll.dll in kernel mode,which will continue the kernel-mode part of process creation in the function with the same name 7 | - ![image](https://github.com/SecTheBit/Windows-Internals/assets/46895441/c9dbf4d3-0739-46ca-bcad-7bfd228578fe) 8 | 9 | ### CreateProcess Function Explained 10 | ``` 11 | BOOL CreateProcessA( 12 | [in, optional] LPCSTR lpApplicationName, 13 | [in, out, optional] LPSTR lpCommandLine, 14 | [in, optional] LPSECURITY_ATTRIBUTES lpProcessAttributes, 15 | [in, optional] LPSECURITY_ATTRIBUTES lpThreadAttributes, 16 | [in] BOOL bInheritHandles, 17 | [in] DWORD dwCreationFlags, 18 | [in, optional] LPVOID lpEnvironment, 19 | [in, optional] LPCSTR lpCurrentDirectory, 20 | [in] LPSTARTUPINFOA lpStartupInfo, 21 | [out] LPPROCESS_INFORMATION lpProcessInformation 22 | ); 23 | ``` 24 | - If you see above , there are several parameters which are required while calling CreateProcess functions, let's understand one by one: 25 | - lpApplicationName: The name of the application (exe, dll) to be executed 26 | - lpCommandLine: Any optional command line arguments to fire with the application. 27 | - lpProcesAttributes: Pointer to SECURITY_ATTRIBUTES structure which will determine whether the newly created process can be inherited or not. I always Use NULL for this parameter 28 | - lpThreadAttributes: Pointer to SECURITY_ATTRIBUTES structure which will determine whether the newly created thread object can be inherited or not. 29 | - bInheritHandles: If this parameter is TRUE, each inheritable handle in the calling process is inherited by the new process. 30 | - dwCreationFlags: Process creation flags, refer here https://learn.microsoft.com/en-us/windows/win32/procthread/process-creation-flags 31 | - lpEnvironment: A pointer to the environment block for the new process. If this parameter is NULL, the new process uses the environment of the calling process. 32 | - lpStartupInfo: Pointer to STARTUPINFOEX structure 33 | - lpProcessInformation: A pointer to a PROCESS_INFORMATION structure that receives identification information about the new process. 34 | 35 | - If you worried about unknown data types used above, refer here: https://learn.microsoft.com/en-us/windows/win32/winprog/windows-data-types 36 | 37 | -------------------------------------------------------------------------------- /Day6/Readme.md: -------------------------------------------------------------------------------- 1 | # Process and Jobs 2 | 3 | ### Process Environment Block 4 | - The PEB is a structure which holds data about the current process under it’s field values – some fields being structures themselves to hold even more data. 5 | - It contains information about a “running” process like: the process name, PID and loaded modules. 6 | - Moreover, we can access the PEB structure from user-mode 7 | - Let's See the PEB structure 8 | ``` 9 | typedef struct _PEB { 10 | BYTE Reserved1[2]; 11 | BYTE BeingDebugged; 12 | BYTE Reserved2[1]; 13 | PVOID Reserved3[2]; 14 | PPEB_LDR_DATA Ldr; 15 | PRTL_USER_PROCESS_PARAMETERS ProcessParameters; 16 | PVOID Reserved4[3]; 17 | PVOID AtlThunkSListPtr; 18 | PVOID Reserved5; 19 | ULONG Reserved6; 20 | PVOID Reserved7; 21 | ULONG Reserved8; 22 | ULONG AtlThunkSListPtr32; 23 | PVOID Reserved9[45]; 24 | BYTE Reserved10[96]; 25 | PPS_POST_PROCESS_INIT_ROUTINE PostProcessInitRoutine; 26 | BYTE Reserved11[128]; 27 | PVOID Reserved12[1]; 28 | ULONG SessionId; 29 | } PEB, *PPEB; 30 | ``` 31 | 32 | 33 | The PEB Structure contains the following elements 34 | 1. Reserved1[2] : Reserved for internal use by the operating system. 35 | 2. Reserved3[2] : Reserved for internal use by operating system. 36 | 3. Ldr : Pointer to PEB_LDR_DATA structure that contains information about the loaded modules for the process. 37 | 4. Process Parameters: A pointer to an RTL_USER_PROCESS_PARAMETERS structure that contains process parameter information such as the command line 38 | 5. All the other elements are reserved for internal purpose only. Refer here https://learn.microsoft.com/en-us/windows/win32/api/winternl/ns-winternl-peb 39 | 40 | ### Image Loader 41 | - A loader is a type of program that is responsible for loading programs and libraries into memory,and linking together all the necessary dependencies to run an application 42 | - when a process is started on the system, the kernel creates a process object to represent it and performs various kernel-related initialization tasks, these tasks are performed by the image loader. 43 | - The image loader lives in the user-mode system DLL Ntdll.dll and not in the kernel library. Therefore, it behaves just like standard code that is part of a DLL, and it is subject to the same restrictions in terms of memory access and security rights. 44 | - The image loader will always be present in the running process 45 | 46 | 47 | ## Jobs 48 | - Jobs function is to control one or more than one process called as group. 49 | - A job object’s basic function is to allow groups of processes to be managed and manipulated as a unit. 50 | - A job object is created using the ```CreateJobObject``` API 51 | 52 | -------------------------------------------------------------------------------- /Day7/Readme.md: -------------------------------------------------------------------------------- 1 | # Memory Management 2 | 3 | ## Introduction to Memory Management 4 | - The memory management in the operating system is to control or maintain the main memory and transfer processes from the primary memory to disk during execution. 5 | - It also helps to keeps track of all memory locations, whether the process uses them or not. 6 | - It tracks when memory is released or when it is shared and changes the status accordingly. 7 | - These all things related to Memory management is being done by Memory Manager, like managing virtual address space, paging, etc. 8 | 9 | ## Virtual Address Space 10 | - The virtual address space for a process is the set of virtual memory addresses that it can use. The address space for each process is private and cannot be accessed by other processes unless it is shared 11 | - A virtual address does not represent the actual physical location of an object in memory; instead, the system maintains a page table for each process, which is an internal data structure used to translate virtual addresses into their corresponding physical addresses 12 | - Each time a thread references an address, the system translates the virtual address to a physical address. 13 | - Read more here https://learn.microsoft.com/en-us/windows/win32/memory/virtual-address-space 14 | 15 | ### Page 16 | - Memory management is done in distinct chunks called pages. This is because the hardware memory management unit translates virtual to physical addresses at the granularity of a page. 17 | - Hence, a page is the smallest unit of protection at the hardware level. 18 | 19 | ### Paging 20 | - When the total memory requested by active processes exceeds the actual physical memory available, it leads to a situation known as overcommitment. Operating systems might allow this condition temporarily, anticipating that not all processes will simultaneously require their maximum allocated memory at the same time. 21 | Paging, in this context, helps manage overcommitted memory. When the system reaches a point of overcommitment and the physical memory becomes insufficient to hold all the data needed by active processes, the operating system adopts a technique where it selectively moves or "pages out" parts of the memory from RAM to the disk. This process is often referred to as "swapping" or "paging to disk." 22 | 23 | ## Memory Manager 24 | - It resides in NtOSkrnl.exe 25 | - No parts of the memmory manager exists in HAL 26 | - The memory manager is fully reentrant and supports simultaneous execution on multiprocessor systems. That is, it allows two threads to acquire resources in such a way that they don’t corrupt each other’s data. To aquire this, memory manager implement various internal synchronizaion techniques. 27 | - Windows API provided for Memory Mangement 28 | - Virtual API: It is used for memeory allocation and de-allocation. It includes VirtualAlloc, VirtualFree, VirtualProtect, VirtualLock and others. 29 | - Heap API: This provides functions for small allocations (typically less than a page). It uses the Virtual API internally, but adds management on top of it. It includes HeapAlloc, HeapFree, HeapCreate, HeapReAlloc and others. 30 | - Local/Global APIs: These are leftovers from 16-bit Windows and are now implemented using the Heap API. 31 | - Memory Mapped Files: A memory-mapped file contains the contents of a file in virtual memory. This mapping between a file and memory space enables an application, including multiple processes, to modify the file by reading and writing directly to the memory.Memory-mapped file functions include Create-FileMapping, OpenFileMapping, MapViewOfFile, and others. 32 | 33 | ![image](https://github.com/SecTheBit/Windows-Internals/assets/46895441/c77c0486-cfbe-4915-affe-584956560fac) 34 | 35 | ### Shared Memory and mapped Files 36 | 37 | - Windows provides a mechanism to share memory among processes and the operating system. Shared memory can be defined as memory that is visible to more than one process or that is present in more than one process virtual address space 38 | - For example, if two processes use the same DLL, it would make sense to load the referenced code pages for that DLL into physical memory only once and share those pages between all processes that map the DLL, as 39 | - Each process would still maintain its private memory areas to store private data but the DLL code and unmodified data pages could be shared without harm. 40 | 41 | ## Data Execution Prevention 42 | - Data Execution Prevention (DEP) is a technology built into Windows that helps protect you from executable code launching from places it's not supposed to. DEP does that by marking some areas of your PC's memory as being for data only, no executable code or apps will be allowed to run from those areas of memory 43 | - This can prevent certain types of malware from exploiting bugs in the system through the execution of code placed in a data page such as the stack. 44 | - DEP can also catch poorly written programs that don’t correctly set permissions on pages from which they intend to execute code. 45 | - On 64-bit versions of Windows, execution protection is always applied to all 64-bit processes and device drivers and can be disabled only by setting the nx BCD option to AlwaysOff 46 | - On 64-bit Windows, execution protection is applied to thread stacks (both user and kernel mode), user-mode pages not specifically marked as executable, the kernel paged pool, and the kernel session pool. 47 | - On ARM systems, DEP is set to AlwaysOn. 48 | - The application of execution protection for 32-bit processes depends on the value of the BCD nx option. 49 | - Heap allocations made by calling the malloc and HeapAlloc functions are non-executable. 50 | - DEP is configured at system boot according to the no-execute page protection policy setting in the boot configuration data. 51 | - An application can get the current policy setting by calling the GetSystemDEPPolicy function. Depending on the policy setting, an application can change the DEP setting for the current process by calling the SetProcessDEPPolicy function 52 | - Read more here https://learn.microsoft.com/en-us/windows/win32/memory/data-execution-prevention 53 | 54 | ### View DEP Status (Using Process Explorer) 55 | - Go to any process 56 | - Select it and click on view -> select columns -> DEP Status 57 | 58 | ![POC](https://github.com/SecTheBit/Windows-Internals/assets/46895441/71399911-c78a-4fdf-aeb0-1aaaf879bf7c) 59 | 60 | ### DEP Status Values 61 | - DEP (permanent) This means the process has enabled DEP because it is a “necessary Windows program or service.” 62 | - DEP This means the process opted in to DEP. 63 | - Nothing If the column displays no information for this process, DEP is disabled. 64 | -------------------------------------------------------------------------------- /Day8/Readme.md: -------------------------------------------------------------------------------- 1 | # Memory Management 2 | 3 | ## Kernel-mode heaps (system memory pools) 4 | - At system initialization, the memory manager creates two dynamically sized memory pools, or heaps, that most kernel-mode components use to allocate system memory: 5 | - Paged Pool: This is a region of virtual memory in system space that can be paged into and out of the system 6 | - Non Paged Pool: Unlike the paged pool, the non-paged pool is memory that must stay in physical RAM at all times. It's reserved for critical system objects that the operating system or device drivers need for various essential functions 7 | - Both memory pools are in the system part of the address space and are mapped in the virtual address space of every process 8 | - The executive provides routines to allocate and deallocate from these pools. For information on these routines, see the functions that start with *ExAllocatePool*, *ExAllocatePoolWithTag*, and *ExFreePool* in the Windows Development Kit (WDK) documentation 9 | 10 | ## Heap 11 | - Heaps are memory areas allocated to each program. Memory allocated to heaps can be dynamically allocated, unlike memory allocated to stacks. 12 | ### Heap Manager 13 | - User program calls heap manager to allocate a block of any desired size to store some dynamic data. 14 | - Heap manager returns a pointer to a block. The program uses that block for its purpose. The block’s memory is reserved exclusively for that use. 15 | - The heap manager exists in two places: Ntdll.dll and Ntoskrnl.exe 16 | - The most common Windows heap functions are: 17 | - HeapCreate or HeapDestroy: These create or delete, respectively, a heap. The initial reserved and committed size can be specified at creation 18 | - HeapAlloc: This allocates a heap block. It is forwarded to RtlAllocateHeap in Ntdll.dll. 19 | - HeapFree: This frees a block previously allocated with HeapAlloc 20 | - HeapReAlloc: This changes the size of an existing allocation, growing or shrinking an existing block. It is forwarded to RtlReAllocateHeap in Ntdll.dll. 21 | - HeapLock and HeapUnlock: These control mutual exclusion to heap operations 22 | - HeapWalk: This enumerates the entries and regions in a heap. 23 | 24 | ### Types of Heap 25 | - NT Heap 26 | - Segemnt Heap 27 | 28 | ### View Heap Structure using WinDbg 29 | Attach calculator process to WinDbg, use the command ```!heap``` 30 | ![POC](https://github.com/SecTheBit/Windows-Internals/assets/46895441/0a0dba2b-f718-4029-8956-b54afc97c8b9) 31 | 32 | View Structure of NT Heap 33 | ![POC](https://github.com/SecTheBit/Windows-Internals/assets/46895441/f6cdb7c2-5ded-4df8-b7f9-e13914bf3132) 34 | 35 | 36 | -------------------------------------------------------------------------------- /Day9/Readme.md: -------------------------------------------------------------------------------- 1 | ## Memory Management 2 | 3 | ### Virtual Address Space 4 | - There are 3 main types of data that are mapped to virtual space: 5 | - Per-Process private code and data : Each process has a private address space that cannot be accessed by other processes. That is, a virtual address is always evaluated in the context of the current process and cannot refer to an address defined by any other process. 6 | - Session Wide Code and Data : A session consists of the processes and other system objects such as the window station, desktops, and windows that represent a single user’s logon session.Each session has a session-specific paged pool area used by the kernel-mode portion of the Windows subsystem (Win32k.sys) to allocate session-private GUI data structures. 7 | - System Wide Code and Data : System space contains global operating system code and data structures visible by kernel-mode code regardless of which process is currently executing 8 | ### x86 Address Space Layout 9 | - By default, each user process on 32-bit versions of Windows has a 2 GB private address space. (The operating system takes the remaining 2 GB.) 10 | - However, for x86, the system can be configured with the increaseuserva BCD boot option to permit user address spaces up to 3 GB 11 | - For a process to grow beyond 2 GB of address space, the image file must have the IMAGE_FILE_LARGE_ADDRESS_AWARE flag set in the image header (in addition to the global increaseuserva setting). 12 | - Several system images are marked as large address space aware so that they can take advantage of systems running with large process address spaces. These include the following: 13 | - lsass.exe 14 | - Inetinfo.exe 15 | - Chkdsk.exe 16 | - Smss.exe 17 | - Dllhst3g.exe 18 | - For viewing if the process is using large process address space use the dumpbin tool with following command and search for string "Application can handle large (>2GB) addresses" 19 | ``` dumpbin /headers c:\windows\system32\smss.exe ``` 20 | - Memory allocations using VirtualAlloc, VirtualAllocEx, and VirtualAllocExNuma start with low virtual addresses and grow higher by default 21 | - Therefore,for testing purposes, you can force memory allocations to start from high addresses by using the MEM_TOP_DOWN flag to the VirtualAlloc* functions or by adding a DWORD registry value named AllocationPreference to the HKLM\SYSTEM\CurrentControlSet\Control\Session Manager\Memory Management key and setting its value to 0x100000. 22 | 23 | #### x86 System Address Space Layout 24 | - The 32-bit versions of Windows implement a dynamic system address space layout by using a virtual address allocator 25 | - Many kernel-mode structures use dynamic address space allocation. These structures are therefore not necessarily virtually contiguous with themselves 26 | - Each can easily exist in several disjointed pieces in various areas of system address space. 27 | 28 | #### x86 Session Space 29 | - For systems with multiple sessions (which is almost always the case, as session 0 is used by system processes and services, while session 1 is used for the first logged on user), the code and data unique to each session are mapped into system address space but shared by the processes in that session 30 | 31 | ### 64-bit Address Space Layout 32 | - The theoretical 64-bit virtual address space is 16 exabytes (EB), or 18,446,744,073,709,551,616 bytes 33 | - The address space is divided in half, where the lower 128 TB are available as private user processes and the upper 128 TB are system space. 34 | - System space is divided into several different-sized regions 35 | 36 | #### x64 virtual addressing limitations 37 | - As discussed, 64 bits of virtual address space allow for a possible maximum of 16 EB of virtual memory. Obviously, neither today’s computers nor tomorrow’s are even close to requiring support for that much memory. 38 | - Accordingly, to simplify chip architecture and avoid unnecessary overhead—particularly in address translation (described later)—AMD’s and Intel’s current x64 processors implement only 256 TB of virtual address space. 39 | 40 | ### System virtual addres space quotas 41 | - To address more specific quota requirementsthat system administrators might have, the memory manager collaborates with the process manager to enforce either system-wide or user-specific quotas for each process. 42 | - You can configure the PagedPoolQuota, NonPagedPoolQuota, PagingFileQuota, and Working-SetPagesQuota values in the HKLM\SYSTEM\CurrentControlSet\Control\Session Manager\Memory Management key to specify how much memory of each type a given process can use. 43 | 44 | ### User address space layout 45 | - Just as address space in the kernel is dynamic, the user address space is also built dynamically. The addresses of the thread stacks, process heaps, and loaded images (such as DLLs and an application’s executable) are dynamically computed (if the application and its images support it) through the ASLR mechanism. 46 | 47 | #### Analyzing user virtual address space using VMMap 48 | - Following things will be shown in VMMap 49 | - Image : This displays memory allocations used to map the executable and its dependencies (such as dynamic libraries) and any other memory-mapped image (portable executable format) files 50 | - Mapped file: This displays memory allocations for memory mapped data files 51 | - Shareable : This displays memory allocations marked as shareable, typically including shared memory (but not memory-mapped files, which are listed under either Image or Mapped File). 52 | - Heap : This displays memory allocated for the heap(s) that this process owns 53 | - Managed Heap: This displays memory allocated by the .NET CLR 54 | - Stack : This displays memory allocated for the stack of each thread in this process 55 | - Private Data : This displays memory allocations marked as private other than the stack and heap, such as internal data structures. 56 | ![POC](https://github.com/SecTheBit/Windows-Internals/assets/46895441/1dbf0a25-7e7e-40de-83a1-c49044dc4866) 57 | -------------------------------------------------------------------------------- /README.md: -------------------------------------------------------------------------------- 1 | # Windows-Internals 2 | Learnings about windows Internals from malware development/reversing purpose. 3 | I will cover only those topics which are necessary in maldev . Hope it helps to Red Teamers.!! 4 | 5 | ## Day 1 6 | - Introduction to following things 7 | - Windows API 8 | - OLE 9 | - COM 10 | - Process 11 | - Process Status 12 | - Threads 13 | - Threads Scheduling 14 | 15 | ## Day 2 16 | - Introduction to Virtual Memory 17 | - Kernel mode vs User mode 18 | - Introduction 19 | - What are terms ring0 , ring3, etc. signify 20 | - Memory regions accessible through User mode and kernel mode 21 | - context switching 22 | - Driver Signing 23 | - Brief Introduction to Windows Registry 24 | 25 | ## Day 3 26 | - Viewing Exported functions of a DLL file using Dependency Walker 27 | - Kernel Debugging (Locally) using WinDbg 28 | 29 | ## Day 4 30 | - System architecture 31 | - How Hypervisor helps in protecting system from malicious kernel drivers 32 | 33 | ## Day 5 34 | - CreateProcess Function Explained 35 | 36 | ## Day 6 37 | - Process Environment Block 38 | - Basic Info about Jobs 39 | 40 | ## Day 7 41 | - Memory Management 42 | - Introuction to Memory Managment 43 | - Virtual Address Space 44 | - Page 45 | - Paging 46 | - Memory Manager 47 | - Memory Related Windows API 48 | - Shared Memory and Mapped Files 49 | - Data Execution Policy 50 | - Introduction 51 | - Viewing DEP Status using Process Explorer 52 | - DEP Status Values Description 53 | ## Day 8 54 | - System Memory Pools 55 | - Paged Pool 56 | - Non Paged Pool 57 | - APIs used for allocating memory with kernel memory pool 58 | - Heaps 59 | - Introduction 60 | - Types 61 | - Viewing Structure of Heap using WinDBG 62 | ## Day 9 63 | - Virtual Address Space 64 | - Types of data mapped to Virtual Address Space 65 | - x86 Address Space Layout 66 | - x86 System Address Space Layout 67 | - x86 Session Space 68 | - System Virtual Address Space Quotas 69 | - User Address Space layout 70 | - Analyzing user virtual address space using VMMap 71 | --------------------------------------------------------------------------------