Heap spraying is a technique which is implemented using Javascript and the sole purpose is arbitrary code execution. Although heap spray exploits has been in use since 2001 but since 2005 a more widespread use of this technique is seen in exploits targeted for web malwares. Let us now see what actually heap spraying is and how it is done.
A vulnerable application (in this case, browsers like IE or Firefox), because of certain illegal operation due to badly coded error handling modules, can jump into invalid memory addresses. Once it jumps to those memory addresses it is unable to read data from that invalid memory address resulting in an application crash. When the application crashes it throws a popup as shown below:
Now, depending on the nature of the vulnerablity in the application, we can inject the heap with "nop + shellcode", as much as possible, untill the invalid memory address gets overwritten with "nop + shellcode" and becomes a valid memory. By this we can create a scenario where we can ensure that our custom "shellcode" gets executed the next time a similar illegal operation happens and the application tries to reference that invalid address again. Once we control this behavior with a properly written exploit code, we can successfully use the vulnerability to our advantage to achieve arbitrary code execution. Please refer to the below image for a better understanding of the concepts mentioned above.
However, to successfully achieve arbitrary code exection using heap spray, there is one important things that we need to keep in mind. That is, as per the Windows Memory Layout, address higher than 0x7FFFFFFF falls in the KERNEL ADDRESS SPACE and address lower than 0x7FFFFFFF falls in the USER ADDRESS SPACE. The address of a program heap falls within this USER ADDRESS SPACE i.e the address is less than 0x7FFFFFFF. So during the overwriting of the heap and the invalid memory address, we must keep in mind that we are overwriting memory addresses that fall within the USER ADDRESS SPACE, not the KERNEL ADDRESS SPACE. If we write in memory locations that belong to the KERNEL ADDRESS SPACE, there will be a system crash.