I suppose that there is problem with reprogramming of FSEC byte default state = 0xFE = unsecured.
I guess that your loader simply write code into flash without erasing. So, when we rewrite default security byte 0xFE by 0xFF, nothing happened and MCU stay unsecured (Flash bit could be programmed only in one direction 0b1 -> 0b0).
Note: Flash data must be in the erased state before being programmed. Cumulative programming of bits is not allowed.
So, you have to:
- erase sector from address 0x400 prior programming OR
- choose different value of SEC bits. For example: 0xfffffffc.
Second solution isn’t clear (cumulative programming), but in case of security byte it could be conditionally accepted.