Thread Local Storage

Adversaries may inject malicious code into processes via thread local storage (TLS) callbacks in order to evade process-based defenses as well as possibly elevated privileges. TLS callback injection is a method of executing arbitrary code in the address space of a separate live process.
TLS call back injection involves manipulating pointers inside a portable executable (PE) to redirect a process to malicious code before reaching the code's legitimate entry point. TLS callbacks are normally used by the OS to setup and/or cleanup data used by threads. Manipulating TLS callbacks may be performed by allocating and writing to specific offsets within process' memory space using other Process Injection techniques such as Process Hollowing.
Running code in the context of another process may allow access to the process's memory, system/network resources, and possibly elevated privileges. Execution via TLS callback injection since the execution is masked under a legitimate process.
Example
Thread Local Storage callbacks are mechanisms provided by the Windows Loader to allow programs to perform initilisation tasks that are thread specific when a process starts. What is interesting about TLS callbacks is that they are executed before the entry point of the application, so before the main() function. This is problematic for a couple of reason:
· Debuggers usually stop at the main function, thus missing any extra TLS code
· Disassemblers and static analysis tools first present the main function, again leading to possibly hidden code.
To use these we need to declare the prototype
Callbacks are defined like this:
Now let me show the sample code
We see above that we declared the TLS Callback and we have our main function below, once executed the main function will never get executed becvause of the ExitProcess() in the TLSCallback declaration, of course we can remove this and have it print in the console, but in here will just demonstrate the TLS and then have it terminate as what it's meant to do.
Once we hit Ok, the process simply terminate as intended
We see above that the main section of the code where it just supposed to print some text in the console didn't execute since our TLS callback was the first to execute and terminate the process before reaching the main section
There were samples where these TLSCallbacks would execute even before loading onto a debugger
I couldn't replicate this but it's good to be aware of.
References: