@@ -362,15 +362,54 @@ static void sam_ba_monitor_loop(void)
362362 }
363363 else if (command == 'O' ) // write byte
364364 {
365- * ptr_data = (char ) current_number ;
365+ if (b_security_enabled && (uint16_t * )ptr_data == & NVMCTRL -> CTRLA .reg && (current_number & NVMCTRL_CTRLA_CMD_Msk ) == NVMCTRL_CTRLA_CMD_ER )
366+ {
367+ // NVM Erase Row command received in secure mode.
368+ // To mitigate that an attacker might not use the ordinary BOSSA method of erasing flash before programming,
369+ // always erase flash, if it hasn't been done already.
370+ if (erased_from != 0x2000 )
371+ {
372+ eraseFlash (0x2000 );
373+ }
374+ }
375+ else
376+ {
377+ * ptr_data = (char ) current_number ;
378+ }
366379 }
367380 else if (command == 'H' ) // Write half word
368381 {
369- * ((uint16_t * ) ptr_data ) = (uint16_t ) current_number ;
382+ if (b_security_enabled && (uint16_t * )ptr_data == & NVMCTRL -> CTRLA .reg && (current_number & NVMCTRL_CTRLA_CMD_Msk ) == NVMCTRL_CTRLA_CMD_ER )
383+ {
384+ // NVM Erase Row command received in secure mode.
385+ // To mitigate that an attacker might not use the ordinary BOSSA method of erasing flash before programming,
386+ // always erase flash, if it hasn't been done already.
387+ if (erased_from != 0x2000 )
388+ {
389+ eraseFlash (0x2000 );
390+ }
391+ }
392+ else
393+ {
394+ * ((uint16_t * ) ptr_data ) = (uint16_t ) current_number ;
395+ }
370396 }
371397 else if (command == 'W' ) // Write word
372398 {
373- * ((int * ) ptr_data ) = current_number ;
399+ if (b_security_enabled && (uint16_t * )ptr_data == & NVMCTRL -> CTRLA .reg && (current_number & NVMCTRL_CTRLA_CMD_Msk ) == NVMCTRL_CTRLA_CMD_ER )
400+ {
401+ // NVM Erase Row command received in secure mode.
402+ // To mitigate that an attacker might not use the ordinary BOSSA method of erasing flash before programming,
403+ // always erase flash, if it hasn't been done already.
404+ if (erased_from != 0x2000 )
405+ {
406+ eraseFlash (0x2000 );
407+ }
408+ }
409+ else
410+ {
411+ * ((int * ) ptr_data ) = current_number ;
412+ }
374413 }
375414 else if (command == 'o' ) // Read byte
376415 {
0 commit comments