hw/sd: Security fixes
cover hw/sd: Security fixes
Various "security" fixes (as defined by docs/system/security.rst:
data corruption / crash guest triggered) worth for 11.2.
Harshit Mukhedkar (1):
hw/sd/sdcard: Validate migrated blk_len in post_load
Philippe Mathieu-Daudé (8):
hw/sd/sdcard: Reject zero block length (CMD16) hw/sd/sdcard: Do not write data to write-protected areas hw/sd/sdcard: Do not abort when writing DAT lines on invalid cmd state hw/sd/sdcard: Fix incoming migration of SPI mode cards hw/sd/sdcard: Migrate the data transfer size
hw/sd/sdcard: Validate the migrated state
hw/sd/sdcard: Fill SPI R1 response for rejected commands hw/sd/sdhci: Report Auto CMD12 response timeout in error status
hw/sd/sdhci-internal.h | 1 + hw/sd/sd.c | 122 ++++++++++++++++++++++++++++++++++++++--- hw/sd/sdhci.c | 18 ++++-- 3 files changed, 128 insertions(+), 13 deletions(-)
Signature · 1 line
2.55.0
PATCH 1/9 hw/sd/sdcard: Reject zero block length (CMD16)
SET_BLOCKLEN (CMD16) accepts a zero block length. A following READ_SINGLE_BLOCK (CMD17) on a Standard Capacity card then reads 0 bytes from the backing image and enters the sending-data state with the data size of the previous transfer, so the guest reads back stale SDState::data[] content, such as the password sent by a previous LOCK_UNLOCK (CMD42):
CMD42 (set password "secret-password!")
CMD16 0
CMD17 -> data block contains "secret-password!"
The spec only requires BLOCK_LEN_ERROR above 512 bytes, but a zero length cannot carry any data. Reject a zero block length: set BLOCK_LEN_ERROR and keep the current block length.
--- hw/sd/sd.c | 2 +- 1 file changed, 1 insertion(+), 1 deletion(-)
hw/sd/sd.c +1 -1
@@ -1961,7 +1961,7 @@ static sd_rsp_type_t sd_cmd_SET_BLOCKLEN(SDState *sd, SDRequest req)if (sd->state != sd_transfer_state) {return sd_invalid_state_for_cmd (sd, req); } -if (req.arg > (1 <<HWBLOCK_SHIFT )) { +if (req.arg ==0 || req.arg > (1 <<HWBLOCK_SHIFT )) { sd->card_status |=BLOCK_LEN_ERROR ; }else {trace_sdcard_set_blocklen (req.arg);
Signature · 1 line
2.55.0
Re: [PATCH-for-11.2 1/9] hw/sd/sdcard: Reject zero block length (CMD16)
Quoted 16 lines · Philippe Mathieu-Daudé
SET_BLOCKLEN(CMD16) accepts a zero block length. A followingREAD_SINGLE_BLOCK(CMD17) on a Standard Capacity card then reads 0 bytes from the backing image and enters the sending-data state with the data size of the previous transfer, so the guest reads back stale SDState::data[] content, such as the password sent by a previousLOCK_UNLOCK(CMD42):CMD42 (set password "secret-password!")
CMD16 0
CMD17 -> data block contains "secret-password!"The spec only requires
BLOCK_LEN_ERRORabove 512 bytes, but a zero length cannot carry any data. Reject a zero block length: setBLOCK_LEN_ERRORand keep the current block length.
Quoted 6 lines
Fixes a1bb27b1e98a ("SD card emulation (initial implementation)")Signed-off-by Philippe Mathieu-Daudé <[email protected]>--- hw/sd/sd.c | 2 +- 1 file changed, 1 insertion(+), 1 deletion(-)
thanks
-- PMM
PATCH 2/9 hw/sd/sdcard: Do not write data to write-protected areas
In reply to Philippe Mathieu-DaudéWRITE_SINGLE_BLOCK (CMD24) and WRITE_MULTIPLE_BLOCK (CMD25) check write protection when the command is received, set the WP_VIOLATION status bit and enter the receiving-data state, relying on sd_write_data() to ignore the data while WP_VIOLATION is set.
However WP_VIOLATION is cleared on read: it is cleared when the R1 response of the write command is built, before any data is received. The data is then committed to the backing image, bypassing:
- the write protect groups (CMD28) for CMD24,
- the CSD TMP_WRITE_PROTECT / PERM_WRITE_PROTECT bits for CMD24 and CMD25 (CMD25 only re-checks the write protect groups).
Introduce sd_wp_violation() and check it again when committing the data.
--- hw/sd/sd.c | 23 ++++++++++++++++++----- 1 file changed, 18 insertions(+), 5 deletions(-)
hw/sd/sd.c +18 -5
@@ -1481,6 +1481,17 @@ static inline bool sd_wp_addr(SDState *sd, uint64_t addr)return test_bit (sd_addr_to_wpnum (addr), sd->wp_group_bmap); } +/* Return true if writing at @addr violates a write protection */ +static bool sd_wp_violation (SDState *sd,uint64_t addr) +{ +/* Permanent or temporary write protection of the whole card */ +if (sd->csd[14 ] &0x30 ) { +return true; + } +/* Only SDSC cards support write protect groups */ +return sd->size <=SDSC_MAX_CAPACITY &&sd_wp_addr (sd, addr); +} +static void sd_lock_command (SDState *sd) {int erase, lock, clr_pwd, set_pwd, pwd_len;
@@ -2691,6 +2702,10 @@ static size_t sd_write_data(SDState *sd, const void *buf, size_t length)switch (sd->current_cmd) {case 24 :/* CMD24: WRITE_SINGLE_BLOCK */ if (sd_generic_write_data (sd, buf, &length)) { +if (sd_wp_violation (sd, sd->data_start)) { + sd->card_status |=WP_VIOLATION ; +break ; + }/* TODO: Check CRC before committing */ sd->state = sd_programming_state;sd_blk_write (sd, sd->data_start, sd->data_offset);
@@ -2714,11 +2729,9 @@ static size_t sd_write_data(SDState *sd, const void *buf, size_t length) sd->data_start, blk_len)) {break ; } -if (sd->size <=SDSC_MAX_CAPACITY ) { -if (sd_wp_addr (sd, sd->data_start)) { - sd->card_status |=WP_VIOLATION ; -break ; - } +if (sd_wp_violation (sd, sd->data_start)) { + sd->card_status |=WP_VIOLATION ; +break ; } } sd->data[sd->data_offset++] = value[0 ];
Signature · 1 line
2.55.0
Re: [PATCH-for-11.2 2/9] hw/sd/sdcard: Do not write data to write-protected areas
Quoted 32 lines · Philippe Mathieu-Daudé
WRITE_SINGLE_BLOCK(CMD24) andWRITE_MULTIPLE_BLOCK(CMD25) check write protection when the command is received, set theWP_VIOLATIONstatus bit and enter the receiving-data state, relying onsd_write_data()to ignore the data whileWP_VIOLATIONis set.However
WP_VIOLATIONis cleared on read: it is cleared when the R1 response of the write command is built, before any data is received. The data is then committed to the backing image, bypassing:- the write protect groups (CMD28) for CMD24,
- the CSDTMP_WRITE_PROTECT/PERM_WRITE_PROTECTbits for CMD24 and CMD25 (CMD25 only re-checks the write protect groups).Introduce
sd_wp_violation()and check it again when committing the data.Fixes a1bb27b1e98a ("SD card emulation (initial implementation)")Signed-off-by Philippe Mathieu-Daudé <[email protected]>--- hw/sd/sd.c | 23 ++++++++++++++++++----- 1 file changed, 18 insertions(+), 5 deletions(-)hw/sd/sd.c +0
-0@@ -1481,6 +1481,17 @@ static inline bool sd_wp_addr(SDState *sd, uint64_t addr)return test_bit (sd_addr_to_wpnum (addr), sd->wp_group_bmap); }
hw/sd/sd.c static inline bool sd_wp_addr(SDState *sd, uint64_t addr) · line 1493
Quoted 10 lines
hw/sd/sd.c +10
-0+/* Return true if writing at @addr violates a write protection */ +static bool sd_wp_violation (SDState *sd,uint64_t addr) +{ +/* Permanent or temporary write protection of the whole card */ +if (sd->csd[14 ] &0x30 ) { +return true; + } +/* Only SDSC cards support write protect groups */ +return sd->size <=SDSC_MAX_CAPACITY &&sd_wp_addr (sd, addr); +}
We could also call this from sd_cmd_WRITE_SINGLE_BLOCK(), I think (it currently has the same checks open-coded).
hw/sd/sd.c static size_t sd_write_data(SDState *sd, const void *buf, size_t length) · line 2708
Quoted 12 lines
hw/sd/sd.c +5
-0+static void sd_lock_command (SDState *sd) {int erase, lock, clr_pwd, set_pwd, pwd_len;@@ -2691,6 +2702,10 @@ static size_t sd_write_data(SDState *sd, const void *buf, size_t length)switch (sd->current_cmd) {case 24 :/* CMD24: WRITE_SINGLE_BLOCK */ if (sd_generic_write_data (sd, buf, &length)) { +if (sd_wp_violation (sd, sd->data_start)) { + sd->card_status |=WP_VIOLATION ; +break ; + }
Is it correct to do this error check after calling sd_generic_write_data() rather than before ?
Quoted 5 lines
hw/sd/sd.c +0
-0/* TODO: Check CRC before committing */ sd->state = sd_programming_state;sd_blk_write (sd, sd->data_start, sd->data_offset);@@ -2714,11 +2729,9 @@ static size_t sd_write_data(SDState *sd, const void *buf, size_t length) sd->data_start, blk_len)) {
hw/sd/sd.c static size_t sd_write_data(SDState *sd, const void *buf, size_t length) · line 2734
Quoted 10 lines
hw/sd/sd.c +3
-5break ; } -if (sd->size <=SDSC_MAX_CAPACITY ) { -if (sd_wp_addr (sd, sd->data_start)) { - sd->card_status |=WP_VIOLATION ; -break ; - } +if (sd_wp_violation (sd, sd->data_start)) { + sd->card_status |=WP_VIOLATION ; +break ;
This is inside the "if (sd->data_offset == 0)" block, so we will only check for the first time around. Is that sufficient? I guess so, as we presumably abort the command on the error so can't come back in here for more data unless it succeeded the first time.
Quoted 5 lines
hw/sd/sd.c +0
-1} } sd->data[sd->data_offset++] = value[0 ]; --2.55.0
thanks
-- PMM
Re: [PATCH-for-11.2 2/9] hw/sd/sdcard: Do not write data to write-protected areas
Am 24. November 2026 11:51:13 UTC schrieb Peter Maydell <[email protected]>:
Quoted 77 lines
Quoted 32 lines · Philippe Mathieu-Daudé
WRITE_SINGLE_BLOCK(CMD24) andWRITE_MULTIPLE_BLOCK(CMD25) check write protection when the command is received, set theWP_VIOLATIONstatus bit and enter the receiving-data state, relying onsd_write_data()to ignore the data whileWP_VIOLATIONis set.However
WP_VIOLATIONis cleared on read: it is cleared when the R1 response of the write command is built, before any data is received. The data is then committed to the backing image, bypassing:- the write protect groups (CMD28) for CMD24,
- the CSDTMP_WRITE_PROTECT/PERM_WRITE_PROTECTbits for CMD24 and CMD25 (CMD25 only re-checks the write protect groups).Introduce
sd_wp_violation()and check it again when committing the data.Fixes a1bb27b1e98a ("SD card emulation (initial implementation)")Signed-off-by Philippe Mathieu-Daudé <[email protected]>--- hw/sd/sd.c | 23 ++++++++++++++++++----- 1 file changed, 18 insertions(+), 5 deletions(-)hw/sd/sd.c +0
-0@@ -1481,6 +1481,17 @@ static inline bool sd_wp_addr(SDState *sd, uint64_t addr)return test_bit (sd_addr_to_wpnum (addr), sd->wp_group_bmap); }hw/sd/sd.c static inline bool sd_wp_addr(SDState *sd, uint64_t addr) · line 1493
Quoted 10 lines
hw/sd/sd.c +10
-0+/* Return true if writing at @addr violates a write protection */ +static bool sd_wp_violation (SDState *sd,uint64_t addr) +{ +/* Permanent or temporary write protection of the whole card */ +if (sd->csd[14 ] &0x30 ) { +return true; + } +/* Only SDSC cards support write protect groups */ +return sd->size <=SDSC_MAX_CAPACITY &&sd_wp_addr (sd, addr); +}We could also call this from
sd_cmd_WRITE_SINGLE_BLOCK(), I think (it currently has the same checks open-coded).hw/sd/sd.c static size_t sd_write_data(SDState *sd, const void *buf, size_t length) · line 2708
Quoted 12 lines
hw/sd/sd.c +5
-0+static void sd_lock_command (SDState *sd) {int erase, lock, clr_pwd, set_pwd, pwd_len;@@ -2691,6 +2702,10 @@ static size_t sd_write_data(SDState *sd, const void *buf, size_t length)switch (sd->current_cmd) {case 24 :/* CMD24: WRITE_SINGLE_BLOCK */ if (sd_generic_write_data (sd, buf, &length)) { +if (sd_wp_violation (sd, sd->data_start)) { + sd->card_status |=WP_VIOLATION ; +break ; + }Is it correct to do this error check after calling
sd_generic_write_data()rather than before ?Quoted 13 lines
hw/sd/sd.c +1
-5/* TODO: Check CRC before committing */ sd->state = sd_programming_state;sd_blk_write (sd, sd->data_start, sd->data_offset);@@ -2714,11 +2729,9 @@ static size_t sd_write_data(SDState *sd, const void *buf, size_t length) sd->data_start, blk_len)) {break ; } -if (sd->size <=SDSC_MAX_CAPACITY ) { -if (sd_wp_addr (sd, sd->data_start)) { - sd->card_status |=WP_VIOLATION ; -break ; - } +if (sd_wp_violation (sd, sd->data_start)) {
Quoted 8 lines
hw/sd/sd.c static size_t sd_write_data(SDState *sd, const void *buf, size_t length) · line 2734
Quoted 2 lines
hw/sd/sd.c +2
-0+ sd->card_status |=WP_VIOLATION ; +break ;This is inside the "if (
sd->data_offset== 0)" block, so we will only check for the first time around. Is that sufficient? I guess so, as we presumably abort the command on the error so can't come back in here for more data unless it succeeded the first time.
The sd->data_offset == 0 means we're at a block boundary. Once we decided to transfer the block, we skip the redundant check until we hit the next block boundary which is guaranteed since we only transfer one byte at a time.
This rests on the assumption that the block size can't change while (multi) block transfer is in progress. AFAICS the SD spec doesn't allow for CMD16 (set block length) to be issued during these phases, so this optimization seems legal.
Best regards,
Bernhard
Quoted 10 lines
Quoted 6 lines
hw/sd/sd.c +0
-1} } sd->data[sd->data_offset++] = value[0 ]; --2.55.0
thanks
-- PMM
PATCH 3/9 hw/sd/sdcard: Do not abort when writing DAT lines on invalid cmd state
In reply to Philippe Mathieu-DaudéSince commit e2dec2eab04d, an illegal command resets SDState::current_cmd to 0 but leaves the card in the receiving-data state. Data written afterwards reaches the g_assert_not_reached() in sd_write_data():
CMD24 (WRITE_SINGLE_BLOCK) -> receiving-data state CMD2 (illegal in SPI mode) -> current_cmd = 0 data token + data -> sd_write_data(): abort
ERROR:../hw/sd/sd.c:<line>:sd_write_data: code should not be reached
Commit bd6207903eb8 already fixed the read side. Fix the write side the same way: log the guest error and ignore the data.
--- hw/sd/sd.c | 4 +++- 1 file changed, 3 insertions(+), 1 deletion(-)
hw/sd/sd.c +3 -1
@@ -2819,7 +2819,9 @@ static size_t sd_write_data(SDState *sd, const void *buf, size_t length)break ;default : -g_assert_not_reached (); +qemu_log_mask (LOG_GUEST_ERROR ,"%s: DAT write illegal for command %s\n" , + __func__, sd->last_cmd_name); +break ; }return length;
Signature · 1 line
2.55.0
Re: [PATCH-for-11.2 3/9] hw/sd/sdcard: Do not abort when writing DAT lines on invalid cmd state
Quoted 12 lines · Philippe Mathieu-Daudé
Since commit
e2dec2eab04d, an illegal command resetsSDState::current_cmdto 0 but leaves the card in the receiving-data state. Data written afterwards reaches theg_assert_not_reached()insd_write_data():CMD24 (WRITE_SINGLE_BLOCK) -> receiving-data state CMD2 (illegal in SPI mode) -> current_cmd = 0 data token + data -> sd_write_data(): abortERROR:../hw/sd/sd.c:<line>:sd_write_data: code should not be reached
Quoted 7 lines
Commit
bd6207903eb8already fixed the read side. Fix the write side the same way: log the guest error and ignore the data.Fixes e2dec2eab04d ("hw/sd/sdcard: Remove default case in read/write on DAT lines")Signed-off-by Philippe Mathieu-Daudé <[email protected]>---
thanks
-- PMM
PATCH 4/9 hw/sd/sdcard: Fix incoming migration of SPI mode cards
In reply to Philippe Mathieu-Daudésd_vmstate_pre_load() powers up the card when the OCR state is not part of the migration stream. Since commit b66f73a0cb31, SPI mode cards are already powered up at reset, so the incoming migration of a machine with an SPI mode card aborts in sd_ocr_powerup():
Assertion failed: (!FIELD_EX32(sd->ocr, OCR, CARD_POWER_UP)), function sd_ocr_powerup, file sd.c, line 409.
Only power up the card if it is not already powered up.
--- hw/sd/sd.c | 5 ++++- 1 file changed, 4 insertions(+), 1 deletion(-)
hw/sd/sd.c +4 -1
@@ -1067,8 +1067,11 @@ static int sd_vmstate_pre_load(void *opaque)/* If the OCR state is not included (prior versions, or not * needed), then the OCR must be set as powered up. If the OCR state * is included, this will be replaced by the state restore. +* In SPI mode the card is already powered up after reset. */ -sd_ocr_powerup (sd); +if (!FIELD_EX32 (sd->ocr,OCR ,CARD_POWER_UP )) { +sd_ocr_powerup (sd); + }return 0 ; }
Signature · 1 line
2.55.0
Re: [PATCH-for-11.2 4/9] hw/sd/sdcard: Fix incoming migration of SPI mode cards
Quoted 25 lines · Philippe Mathieu-Daudé
sd_vmstate_pre_load()powers up the card when the OCR state is not part of the migration stream. Since commitb66f73a0cb31, SPI mode cards are already powered up at reset, so the incoming migration of a machine with an SPI mode card aborts insd_ocr_powerup():Assertion failed: (!FIELD_EX32(sd->ocr, OCR,
CARD_POWER_UP)), functionsd_ocr_powerup, filesd.c, line 409.Only power up the card if it is not already powered up.
Fixes b66f73a0cb31 ("hw/sd: Add SDHC support for SD card SPI-mode")Signed-off-by Philippe Mathieu-Daudé <[email protected]>--- hw/sd/sd.c | 5 ++++- 1 file changed, 4 insertions(+), 1 deletion(-)hw/sd/sd.c +0
-0@@ -1067,8 +1067,11 @@ static int sd_vmstate_pre_load(void *opaque)/* If the OCR state is not included (prior versions, or not * needed), then the OCR must be set as powered up. If the OCR state
hw/sd/sd.c static int sd_vmstate_pre_load(void *opaque) · line 1077
Quoted 10 lines
hw/sd/sd.c +4
-1* is included, this will be replaced by the state restore. +* In SPI mode the card is already powered up after reset. */ -sd_ocr_powerup (sd); +if (!FIELD_EX32 (sd->ocr,OCR ,CARD_POWER_UP )) { +sd_ocr_powerup (sd); + }return 0 ; }
I think it would also be fine to just drop the assert in sd_ocr_powerup() if you prefer.
thanks
-- PMM
PATCH 5/9 hw/sd/sdcard: Migrate the data transfer size
In reply to Philippe Mathieu-DaudéCommit f486bf7d1092 introduced SDState::data_size, the size of the current data transfer, but did not migrate it. When migrating in the middle of a data transfer, the destination uses its reset value (0):
the transfer completes after the next byte, so the guest receives a truncated data block.
Migrate data_size in a subsection, only needed while sending or receiving data. When the subsection is absent (older source), assume the whole data buffer. Use uint32_t, as the size never exceeds the 512 byte data buffer.
--- hw/sd/sd.c | 27 ++++++++++++++++++++++++++- 1 file changed, 26 insertions(+), 1 deletion(-)
hw/sd/sd.c +26 -1
@@ -194,7 +194,7 @@ struct SDState {uint64_t data_start;uint32_t data_offset; -size_t data_size; +uint32_t data_size;uint8_t data[512 ];struct {uint32_t write_counter;
@@ -1002,6 +1002,25 @@ static bool sd_ocr_vmstate_needed(void *opaque)return !FIELD_EX32 (sd->ocr,OCR ,CARD_POWER_UP ); } +static bool sd_data_size_vmstate_needed (void *opaque) +{ +SDState *sd = opaque; + +return sd->state == sd_sendingdata_state + || sd->state == sd_receivingdata_state; +} + +static const VMStateDescription sd_data_size_vmstate = { + .name ="sd-card/data-size" , + .version_id =1 , + .minimum_version_id =1 , + .needed = sd_data_size_vmstate_needed, + .fields = (const VMStateField []) { +VMSTATE_UINT32 (data_size, SDState), +VMSTATE_END_OF_LIST () + }, +}; +static const VMStateDescription sd_ocr_vmstate = { .name ="sd-card/ocr-state" , .version_id =1 ,
@@ -1072,6 +1091,11 @@ static int sd_vmstate_pre_load(void *opaque)if (!FIELD_EX32 (sd->ocr,OCR ,CARD_POWER_UP )) {sd_ocr_powerup (sd); } +/* +* The data size is not included by older versions: assume the +* whole buffer. Replaced by the state restore when included. +*/ + sd->data_size =sizeof (sd->data);return 0 ; }
@@ -1110,6 +1134,7 @@ static const VMStateDescription sd_vmstate = { }, .subsections = (const VMStateDescription * const []) { &sd_ocr_vmstate, + &sd_data_size_vmstate, &emmc_extcsd_vmstate, &emmc_rpmb_vmstate,NULL
Signature · 1 line
2.55.0
Re: [PATCH-for-11.2 5/9] hw/sd/sdcard: Migrate the data transfer size
Quoted 11 lines · Philippe Mathieu-Daudé
Commit
f486bf7d1092introducedSDState::data_size, the size of the current data transfer, but did not migrate it. When migrating in the middle of a data transfer, the destination uses its reset value (0):
the transfer completes after the next byte, so the guest receives a truncated data block.Migrate
data_sizein a subsection, only needed while sending or receiving data. When the subsection is absent (older source), assume the whole data buffer. Useuint32_t, as the size never exceeds the 512 byte data buffer.
Not for this patch, but maybe we should assert() that the size is in bounds when we set sd->data_size in sd_cmd_to_receivingdata() and sd_cmd_to_sendingdata() ? (There is an assert already on size in sd_cmd_to_sendingdata(), but it's in the "if (data)" rather than in thi "if (size)" so it isn't executed in all cases where we set sd->data_size.)
Quoted 47 lines
Fixes f486bf7d1092 ("hw/sd/sdcard: Introduce sd_cmd_to_sendingdata and sd_generic_read_byte")Signed-off-by Philippe Mathieu-Daudé <[email protected]>--- hw/sd/sd.c | 27 ++++++++++++++++++++++++++- 1 file changed, 26 insertions(+), 1 deletion(-)hw/sd/sd.c +20
-1@@ -194,7 +194,7 @@ struct SDState {uint64_t data_start;uint32_t data_offset; -size_t data_size; +uint32_t data_size;uint8_t data[512 ];struct {uint32_t write_counter;@@ -1002,6 +1002,25 @@ static bool sd_ocr_vmstate_needed(void *opaque)return !FIELD_EX32 (sd->ocr,OCR ,CARD_POWER_UP ); } +static bool sd_data_size_vmstate_needed (void *opaque) +{ +SDState *sd = opaque; + +return sd->state == sd_sendingdata_state + || sd->state == sd_receivingdata_state; +} + +static const VMStateDescription sd_data_size_vmstate = { + .name ="sd-card/data-size" , + .version_id =1 , + .minimum_version_id =1 , + .needed = sd_data_size_vmstate_needed, + .fields = (const VMStateField []) { +VMSTATE_UINT32 (data_size, SDState), +VMSTATE_END_OF_LIST () + }, +}; +static const VMStateDescription sd_ocr_vmstate = { .name ="sd-card/ocr-state" , .version_id =1 ,
hw/sd/sd.c static int sd_vmstate_pre_load(void *opaque) · line 1098
Quoted 8 lines
hw/sd/sd.c +5
-0@@ -1072,6 +1091,11 @@ static int sd_vmstate_pre_load(void *opaque)if (!FIELD_EX32 (sd->ocr,OCR ,CARD_POWER_UP )) {sd_ocr_powerup (sd); } +/* +* The data size is not included by older versions: assume the +* whole buffer. Replaced by the state restore when included. +*/ + sd->data_size =sizeof (sd->data);
In the "we didn't get sent the right value" case, what's the effect of assuming the whole buffer? If "assume 0" resulted in the guest getting a truncated transfer, does "assume 512" result in an over-extended transfer ?
-- PMM
PATCH 6/9 hw/sd/sdcard: Validate migrated blk_len in post_load
In reply to Philippe Mathieu-DaudéFrom: Harshit Mukhedkar <[email protected]>
Migration streams are untrusted input. A crafted stream can set blk_len larger than the 512 byte data[] buffer, so a later block read passes that length to blk_pread() and overflows data[] on the host heap.
Reject such state in post_load.
Cc: [email protected]
Resolves: https://gitlab.com/qemu-project/qemu/-/work_items/4725
--- hw/sd/sd.c | 13 +++++++++++++ 1 file changed, 13 insertions(+)
hw/sd/sd.c +13 -0
@@ -1100,11 +1100,24 @@ static int sd_vmstate_pre_load(void *opaque)return 0 ; } +static int sd_vmstate_post_load (void *opaque,int version_id) +{ +SDState *sd = opaque; + +/* Check for blk_len that overflows data[] */ +if (sd->blk_len >sizeof (sd->data)) { +return -EINVAL ; + } + +return 0 ; +} +static const VMStateDescription sd_vmstate = { .name ="sd-card" , .version_id =2 , .minimum_version_id =2 , .pre_load = sd_vmstate_pre_load, + .post_load = sd_vmstate_post_load, .fields = (const VMStateField []) {VMSTATE_UNUSED (4 ),VMSTATE_INT32 (state, SDState),
Signature · 1 line
2.55.0
Re: [PATCH-for-11.2 6/9] hw/sd/sdcard: Validate migrated blk_len in post_load
Quoted 8 lines · Philippe Mathieu-Daudé
From: Harshit Mukhedkar <[email protected]>
Migration streams are untrusted input. A crafted stream can set
blk_lenlarger than the 512 byte data[] buffer, so a later block read passes that length toblk_pread()and overflows data[] on the host heap.Reject such state in
post_load.
With this patch on master (2bfbe39d0fff) under ASan, the #4725 mutated migration stream (blk_len == 4096) is rejected in sd-card post_load instead of overflowing data[] in sd_blk_read().
Tested with patch 6/9 alone and with the 9-patch series applied on Debian 13 x86_64.
Thanks,
Karl
PATCH 7/9 hw/sd/sdcard: Validate the migrated state
In reply to Philippe Mathieu-DaudéSeveral migrated fields index the card buffers or are used without validation:
- data_offset and data_size index the SDState::data[] buffer in sd_generic_read_data() and sd_generic_write_data(),
- blk_len bounds the CMD18/CMD25 data loops writing to SDState::data[], using the effective length from sd_blk_len() (fixed to 512 on SDHC/SDXC),
- pwd_len is the length used to access the SDState::pwd[] buffer,
- an unknown state hits g_assert_not_reached() in sd_mode().
Check these values in a post_load_errp() handler and reject invalid ones. In a data state, data_offset must be below the transfer size.
--- hw/sd/sd.c | 54 +++++++++++++++++++++++++++++++++++++++++++++++++----- 1 file changed, 49 insertions(+), 5 deletions(-)
hw/sd/sd.c +49 -5
@@ -1100,16 +1100,60 @@ static int sd_vmstate_pre_load(void *opaque)return 0 ; } -static int sd_vmstate_post_load (void *opaque,int version_id) +static bool sd_vmstate_post_load (void *opaque,int version_id,Error **errp) {SDState *sd = opaque; -/* Check for blk_len that overflows data[] */ +/* Values used to access the data and password buffers */ +if (sd->data_offset >sizeof (sd->data)) { +error_setg (errp,"sd-card: invalid data_offset %u" , sd->data_offset); +return false; + } +if (sd->data_size >sizeof (sd->data)) { +error_setg (errp,"sd-card: invalid data_size %u" , sd->data_size); +return false; + }if (sd->blk_len >sizeof (sd->data)) { -return -EINVAL ; +error_setg (errp,"sd-card: invalid blk_len %u" , sd->blk_len); +return false; + } +if (sd->pwd_len >sizeof (sd->pwd)) { +error_setg (errp,"sd-card: invalid pwd_len %u" , sd->pwd_len); +return false; + } +/* In a data state, data_offset must be below the active transfer size */ +if (sd->state == sd_sendingdata_state + || sd->state == sd_receivingdata_state) { +uint32_t limit = sd->data_size; + +if (sd->current_cmd ==18 || sd->current_cmd ==25 ) { +/* CMD18/CMD25 are bounded by the effective block length */ + limit =sd_blk_len (sd); + } + +if (sd->data_offset >= limit) { +error_setg (errp,"sd-card: invalid data_offset %u (limit %u)" , + sd->data_offset, limit); +return false; + } } -return 0 ; +switch (sd->state) { +case sd_inactive_state: + case sd_idle_state ... sd_disconnect_state: +return true; +case sd_waitirq_state: +case sd_bus_test_state: +case sd_sleep_state: +if (sd_is_emmc (sd)) { +return true; + } +break ; +default : +break ; + } +error_setg (errp,"sd-card: invalid state %d" , sd->state); +return false; }static const VMStateDescription sd_vmstate = {
@@ -1117,7 +1161,7 @@ static const VMStateDescription sd_vmstate = { .version_id = 2, .minimum_version_id = 2, .pre_load = sd_vmstate_pre_load, - .post_load = sd_vmstate_post_load, + .post_load_errp = sd_vmstate_post_load, .fields = (const VMStateField []) {VMSTATE_UNUSED (4 ),VMSTATE_INT32 (state, SDState),
Signature · 1 line
2.55.0
Re: [PATCH-for-11.2 7/9] hw/sd/sdcard: Validate the migrated state
Quoted 11 lines · Philippe Mathieu-Daudé
Several migrated fields index the card buffers or are used without validation:
-
data_offsetanddata_sizeindex the SDState::data[] buffer insd_generic_read_data()andsd_generic_write_data(),
-blk_lenbounds the CMD18/CMD25 data loops writing to SDState::data[], using the effective length fromsd_blk_len()(fixed to 512 on SDHC/SDXC),
-pwd_lenis the length used to access the SDState::pwd[] buffer,
- an unknown state hitsg_assert_not_reached()insd_mode().
Quoted 4 lines
Check these values in a
post_load_errp()handler and reject invalid ones. In a data state,data_offsetmust be below the transfer size.
Reported-by: phudd6 & kietvha1 from Viettel Cyber Security
Resolves: https://gitlab.com/qemu-project/qemu/-/work_items/4386
Quoted 4 lines
Signed-off-by Philippe Mathieu-Daudé <[email protected]>--- hw/sd/sd.c | 54 +++++++++++++++++++++++++++++++++++++++++++++++++----- 1 file changed, 49 insertions(+), 5 deletions(-)
Re: [PATCH-for-11.2 7/9] hw/sd/sdcard: Validate the migrated state
In reply to Philippe Mathieu-DaudéQuoted 27 lines · Philippe Mathieu-Daudé
Several migrated fields index the card buffers or are used without validation:
-
data_offsetanddata_sizeindex the SDState::data[] buffer insd_generic_read_data()andsd_generic_write_data(),
-blk_lenbounds the CMD18/CMD25 data loops writing to SDState::data[], using the effective length fromsd_blk_len()(fixed to 512 on SDHC/SDXC),
-pwd_lenis the length used to access the SDState::pwd[] buffer,
- an unknown state hitsg_assert_not_reached()insd_mode().Check these values in a
post_load_errp()handler and reject invalid ones. In a data state,data_offsetmust be below the transfer size.Signed-off-by Philippe Mathieu-Daudé <[email protected]>--- hw/sd/sd.c | 54 +++++++++++++++++++++++++++++++++++++++++++++++++----- 1 file changed, 49 insertions(+), 5 deletions(-)hw/sd/sd.c +0
-0@@ -1100,16 +1100,60 @@ static int sd_vmstate_pre_load(void *opaque)return 0 ;
hw/sd/sd.c static int sd_vmstate_pre_load(void *opaque) · line 1108
Quoted 10 lines
hw/sd/sd.c +3
-2} -static int sd_vmstate_post_load (void *opaque,int version_id) +static bool sd_vmstate_post_load (void *opaque,int version_id,Error **errp) {SDState *sd = opaque; -/* Check for blk_len that overflows data[] */ +/* Values used to access the data and password buffers */ +if (sd->data_offset >sizeof (sd->data)) {
Here our bounds check on data_offset is "greater than"...
Quoted 17 lines
hw/sd/sd.c +15
-1+error_setg (errp,"sd-card: invalid data_offset %u" , sd->data_offset); +return false; + } +if (sd->data_size >sizeof (sd->data)) { +error_setg (errp,"sd-card: invalid data_size %u" , sd->data_size); +return false; + }if (sd->blk_len >sizeof (sd->data)) { -return -EINVAL ; +error_setg (errp,"sd-card: invalid blk_len %u" , sd->blk_len); +return false; + } +if (sd->pwd_len >sizeof (sd->pwd)) { +error_setg (errp,"sd-card: invalid pwd_len %u" , sd->pwd_len); +return false; + } +/* In a data state, data_offset must be below the active transfer size */
hw/sd/sd.c static int sd_vmstate_pre_load(void *opaque) · line 1134
Quoted 10 lines
hw/sd/sd.c +10
-0+if (sd->state == sd_sendingdata_state + || sd->state == sd_receivingdata_state) { +uint32_t limit = sd->data_size; + +if (sd->current_cmd ==18 || sd->current_cmd ==25 ) { +/* CMD18/CMD25 are bounded by the effective block length */ + limit =sd_blk_len (sd); + } + +if (sd->data_offset >= limit) {
...but here it is "greater than or equal".
Are they both correct?
Quoted 14 lines
hw/sd/sd.c +11
-1+error_setg (errp,"sd-card: invalid data_offset %u (limit %u)" , + sd->data_offset, limit); +return false; + } } -return 0 ; +switch (sd->state) { +case sd_inactive_state: + case sd_idle_state ... sd_disconnect_state: +return true; +case sd_waitirq_state: +case sd_bus_test_state: +case sd_sleep_state:
hw/sd/sd.c static int sd_vmstate_pre_load(void *opaque) · line 1157
Quoted 10 lines
hw/sd/sd.c +9
-0+if (sd_is_emmc (sd)) { +return true; + } +break ; +default : +break ; + } +error_setg (errp,"sd-card: invalid state %d" , sd->state); +return false; }
Maybe prefer to structure this as
switch (sd->state) {
case sd_inactive_state:
case sd_idle_state ... sd_disconnect_state:
break;
case sd_waitirq_state:
case sd_bus_test_state:
case sd_sleep_state:
if (sd_is_emmc(sd)) {
break;
}
/* fall through */
default:
error_setg(errp, "sd-card: invalid state %d", sd->state);
return false;
}
return true;so it doesn't rely on being the last check in the function? But if you prefer what you have written I'm happy with that too.
thanks
-- PMM
PATCH 8/9 hw/sd/sdcard: Fill SPI R1 response for rejected commands
In reply to Philippe Mathieu-DaudéIn SPI mode the card always responds (Physical Layer spec v1.10, 7.2.8 "Error Conditions"), so sd_response_size() returns 1 for sd_r0 and sd_illegal. However sd_do_command() does not fill the response buffer for these response types, so the ssi-sd bridge returns uninitialized bytes instead of an R1 with the "illegal command" bit set. Before commit 1585ab9f1baf, ssi-sd itself replied 0x04 (illegal command) in this case.
Build the R1 response with the "illegal command" bit set.
--- hw/sd/sd.c | 4 ++++ 1 file changed, 4 insertions(+)
hw/sd/sd.c +4 -0
@@ -2693,6 +2693,10 @@ send_response: sd->data_offset =0 ;/* fall-through */ case sd_illegal: +if (sd_is_spi (sd)) { +sd_response_r1_make (sd, response); + response[0 ] |=1 <<2 ;/* ILLEGAL_COMMAND */ + }break ;default :g_assert_not_reached ();
Signature · 1 line
2.55.0
Re: [PATCH-for-11.2 8/9] hw/sd/sdcard: Fill SPI R1 response for rejected commands
Quoted 9 lines · Philippe Mathieu-Daudé
In SPI mode the card always responds (Physical Layer spec v1.10, 7.2.8 "Error Conditions"), so
sd_response_size()returns 1 forsd_r0andsd_illegal. Howeversd_do_command()does not fill the response buffer for these response types, so the ssi-sd bridge returns uninitialized bytes instead of an R1 with the "illegal command" bit set. Before commit1585ab9f1baf, ssi-sd itself replied0x04(illegal command) in this case.
Quoted 5 lines
Build the R1 response with the "illegal command" bit set.
Fixes 1585ab9f1baf ("hw/sd/sdcard: Fill SPI response bits in card code")Signed-off-by Philippe Mathieu-Daudé <[email protected]>
thanks
-- PMM
PATCH 9/9 hw/sd/sdhci: Report Auto CMD12 response timeout in error status
In reply to Philippe Mathieu-DaudéAuto CMD12 copied an uninitialised stack buffer into the upper Response register when the card did not respond.
Zero the buffer. On timeout, set the Auto CMD12 Timeout Error status bit and, if enabled, the Auto CMD12 Error interrupt.
--- hw/sd/sdhci-internal.h | 1 + hw/sd/sdhci.c | 18 ++++++++++++++---- 2 files changed, 15 insertions(+), 4 deletions(-)
hw/sd/sdhci-internal.h +1 -0
@@ -174,6 +174,7 @@ FIELD(SDHC_TIMEOUTCON, COUNTER, 0, 4);#define SDHC_EISEN_CMDTIMEOUT 0x0001#define SDHC_EISEN_BLKGAP 0x0004#define SDHC_EISEN_CMDIDX 0x0008 +#define SDHC_EISEN_CMD12ERR 0x0100#define SDHC_EISEN_ADMAERR 0x0200/* R/W Normal Interrupt Signal Enable Register 0x0 */
hw/sd/sdhci.c +14 -4
@@ -414,14 +414,24 @@ static void sdhci_end_transfer(SDHCIState *s)/* Automatically send CMD12 to stop transfer if AutoCMD12 enabled */ if ((s->trnmod &SDHC_TRNS_ACMD12 ) !=0 ) {SDRequest request; -uint8_t response[16 ]; +uint8_t response[16 ] = { }; +size_t rlen; request.cmd =0x0C ; request.arg =0 ;trace_sdhci_end_transfer (request.cmd, request.arg); -sdbus_do_command (&s->sdbus, &request, response,sizeof (response)); -/* Auto CMD12 response goes to the upper Response register */ - s->rspreg[3 ] =ldl_be_p (response); + rlen =sdbus_do_command (&s->sdbus, &request, response, +sizeof (response)); +if (rlen ==4 ) { + s->rspreg[3 ] =ldl_be_p (response); + }else { +trace_sdhci_error ("timeout waiting for Auto CMD12 response" ); + s->acmd12errsts |=R_SDHC_ACMD12ERRSTS_TIMEOUT_ERR_MASK ; +if (s->errintstsen &SDHC_EISEN_CMD12ERR ) { + s->errintsts |=SDHC_EIS_CMD12ERR ; + s->norintsts |=SDHC_NIS_ERR ; + } + } } s->prnsts &= ~(SDHC_DOING_READ | SDHC_DOING_WRITE |
Signature · 1 line
2.55.0
Re: [PATCH-for-11.2 9/9] hw/sd/sdhci: Report Auto CMD12 response timeout in error status
Quoted 3 lines · Philippe Mathieu-Daudé
Auto CMD12 copied an uninitialised stack buffer into the upper Response register when the card did not respond.
NB that this is harmless since we compile with -ftrivial-auto-var-init=zero, but explicitly zeroing it is clearer.
Quoted 2 lines
Zero the buffer. On timeout, set the Auto CMD12 Timeout Error status bit and, if enabled, the Auto CMD12 Error interrupt.
(Coverity was complaining that this is the one place where we call sdbus_do_command() and don't check its return value.)
Quoted 27 lines
Fixes d7dfca0807a0 ("hw/sdhci: introduce standard SD host controller")Signed-off-by Philippe Mathieu-Daudé <[email protected]>--- hw/sd/sdhci-internal.h | 1 + hw/sd/sdhci.c | 18 ++++++++++++++---- 2 files changed, 15 insertions(+), 4 deletions(-)hw/sd/sdhci-internal.h +1
-0@@ -174,6 +174,7 @@ FIELD(SDHC_TIMEOUTCON, COUNTER, 0, 4);#define SDHC_EISEN_CMDTIMEOUT 0x0001#define SDHC_EISEN_BLKGAP 0x0004#define SDHC_EISEN_CMDIDX 0x0008 +#define SDHC_EISEN_CMD12ERR 0x0100#define SDHC_EISEN_ADMAERR 0x0200/* R/W Normal Interrupt Signal Enable Register 0x0 */ hw/sd/sdhci.c +0
-0@@ -414,14 +414,24 @@ static void sdhci_end_transfer(SDHCIState *s)/* Automatically send CMD12 to stop transfer if AutoCMD12 enabled */ if ((s->trnmod &SDHC_TRNS_ACMD12 ) !=0 ) {
hw/sd/sdhci.c static void sdhci_end_transfer(SDHCIState *s) · line 423
Quoted 10 lines
hw/sd/sdhci.c +2
-3SDRequest request; -uint8_t response[16 ]; +uint8_t response[16 ] = { }; +size_t rlen; request.cmd =0x0C ; request.arg =0 ;trace_sdhci_end_transfer (request.cmd, request.arg); -sdbus_do_command (&s->sdbus, &request, response,sizeof (response)); -/* Auto CMD12 response goes to the upper Response register */
Should we keep this comment? It seems like it goes with the setting of s->rspreg[3].
Quoted 4 lines
hw/sd/sdhci.c +3
-1- s->rspreg[3 ] =ldl_be_p (response); + rlen =sdbus_do_command (&s->sdbus, &request, response, +sizeof (response)); +if (rlen ==4 ) {
hw/sd/sdhci.c static void sdhci_end_transfer(SDHCIState *s) · line 435
Quoted 10 lines
hw/sd/sdhci.c +9
-0+ s->rspreg[3 ] =ldl_be_p (response); + }else { +trace_sdhci_error ("timeout waiting for Auto CMD12 response" ); + s->acmd12errsts |=R_SDHC_ACMD12ERRSTS_TIMEOUT_ERR_MASK ; +if (s->errintstsen &SDHC_EISEN_CMD12ERR ) { + s->errintsts |=SDHC_EIS_CMD12ERR ; + s->norintsts |=SDHC_NIS_ERR ; + } + } }
thanks
-- PMM
Re: [PATCH-for-11.2 9/9] hw/sd/sdhci: Report Auto CMD12 response timeout in error status
Quoted 50 lines · Peter Maydell
Quoted 3 lines · Philippe Mathieu-Daudé
Auto CMD12 copied an uninitialised stack buffer into the upper Response register when the card did not respond.
NB that this is harmless since we compile with -ftrivial-auto-var-init=zero, but explicitly zeroing it is clearer.
Quoted 2 lines
Zero the buffer. On timeout, set the Auto CMD12 Timeout Error status bit and, if enabled, the Auto CMD12 Error interrupt.
Fixes Coverity CID 1619307(Coverity was complaining that this is the one place where we call
sdbus_do_command()and don't check its return value.)Quoted 32 lines
Fixes d7dfca0807a0 ("hw/sdhci: introduce standard SD host controller")Signed-off-by Philippe Mathieu-Daudé <[email protected]>--- hw/sd/sdhci-internal.h | 1 + hw/sd/sdhci.c | 18 ++++++++++++++---- 2 files changed, 15 insertions(+), 4 deletions(-)hw/sd/sdhci-internal.h +1
-0@@ -174,6 +174,7 @@ FIELD(SDHC_TIMEOUTCON, COUNTER, 0, 4);#define SDHC_EISEN_CMDTIMEOUT 0x0001#define SDHC_EISEN_BLKGAP 0x0004#define SDHC_EISEN_CMDIDX 0x0008 +#define SDHC_EISEN_CMD12ERR 0x0100#define SDHC_EISEN_ADMAERR 0x0200/* R/W Normal Interrupt Signal Enable Register 0x0 */ hw/sd/sdhci.c +2
-1@@ -414,14 +414,24 @@ static void sdhci_end_transfer(SDHCIState *s)/* Automatically send CMD12 to stop transfer if AutoCMD12 enabled */ if ((s->trnmod &SDHC_TRNS_ACMD12 ) !=0 ) {SDRequest request; -uint8_t response[16 ]; +uint8_t response[16 ] = { }; +size_t rlen;
Quoted 8 lines
hw/sd/sdhci.c static void sdhci_end_transfer(SDHCIState *s) · line 423
Quoted 5 lines
hw/sd/sdhci.c +0
-2request.cmd =0x0C ; request.arg =0 ;trace_sdhci_end_transfer (request.cmd, request.arg); -sdbus_do_command (&s->sdbus, &request, response,sizeof (response)); -/* Auto CMD12 response goes to the upper Response register */ Should we keep this comment? It seems like it goes with the setting of s->rspreg[3].
Kept it in v2:
https://lore.kernel.org/qemu-devel/[email protected]/
Quoted 16 lines
Quoted 5 lines
hw/sd/sdhci.c +3
-1- s->rspreg[3 ] =ldl_be_p (response); + rlen =sdbus_do_command (&s->sdbus, &request, response, +sizeof (response)); +if (rlen ==4 ) {hw/sd/sdhci.c static void sdhci_end_transfer(SDHCIState *s) · line 435
Quoted 10 lines
hw/sd/sdhci.c +9
-0+ s->rspreg[3 ] =ldl_be_p (response); + }else { +trace_sdhci_error ("timeout waiting for Auto CMD12 response" ); + s->acmd12errsts |=R_SDHC_ACMD12ERRSTS_TIMEOUT_ERR_MASK ; +if (s->errintstsen &SDHC_EISEN_CMD12ERR ) { + s->errintsts |=SDHC_EIS_CMD12ERR ; + s->norintsts |=SDHC_NIS_ERR ; + } + } }
Quoted 1 line
Reviewed-by Peter Maydell <[email protected]>
Thanks!
Re: [PATCH-for-11.2 9/9] hw/sd/sdhci: Report Auto CMD12 response timeout in error status
In reply to Philippe Mathieu-DaudéQuoted 9 lines · Philippe Mathieu-Daudé
Auto CMD12 copied an uninitialised stack buffer into the upper Response register when the card did not respond.
Zero the buffer. On timeout, set the Auto CMD12 Timeout Error status bit and, if enabled, the Auto CMD12 Error interrupt.
Fixes d7dfca0807a0 ("hw/sdhci: introduce standard SD host controller")Signed-off-by Philippe Mathieu-Daudé <[email protected]>
For 10.0.x stable series, I'm also picking up:
3025ea65bd5 hw/sd/sdcard: Factor sd_response_size() out b82e7a2a1da hw/sd/sdbus: Provide buffer size to sdbus_do_command()
Sure I can easily fix this "Auto CMD12" change for 10.0.x, but it feels the above two changes are safe to pick and makes the code closer to current.
FWIW.
Thanks,
/mjt