Are stack canaries shared via threads

compilermemorystack

As far as I understand, stack canaries work as fllows:
Upon program startup a random value is generated and stored
in the thread local storage (%fs:0x28). This random value is then pushed onto the stack in each function call to be checked against later.

I have two questions regarding this "master-cookie" in the TLS area:

  1. Considering the typical memory process layout:
    enter image description here

Where in this layout would is the thread local storage?

  1. When the process spawns a new thread, will the thread local storage (and, as a result, the stack canary value) be copied to that new thread? Or does the kernel generate a new stack canary value for each thread?

Best Answer

  1. When a new thread is spawned, a memory area is allocated for the thread's stack. Space for thread local variables is allocated from this area. The TLS variables are not strictly part of the stack, i.e. they are not pushed an popped to and from the stack, but they exist in the same area on top of the stack.

    Where this area is located in the address space depends on a lot of factors. When a new thread is created with pthread_create, the programmer can pass a pointer to memory to be used as the thread's stack. The location of this memory depends on how the memory was allocated. If no pre-allocated memory is used, then a memory area is allocated using mmap with NULL as the addr parameter, which let's the kernel decide where the memory is mapped. On x86_64, the memory allocated this way is located between the stack and the heap.

  2. A new canary value is used for each thread. See the answer to this question.

Related Question