Re: [PATCH] scsi: core: initialize cmd->cmnd before it is used

From: Douglas Gilbert
Date: Mon Nov 01 2021 - 21:56:09 EST


On 2021-11-01 4:20 p.m., Bart Van Assche wrote:
On 11/1/21 1:13 PM, Tadeusz Struk wrote:
On 11/1/21 13:06, Bart Van Assche wrote:
This patch is a duplicate and has been posted before.

Please take a look at https://lore.kernel.org/linux-scsi/20210904064534.1919476-1-qiulaibin@xxxxxxxxxx/.
 From the replies to that email:
"> Thinking further about this: is there any code left that depends on
 > scsi_setup_scsi_cmnd() setting cmd->cmd_len? Can the cmd->cmd_len
 > assignment be removed from scsi_setup_scsi_cmnd()?

cmd_len should never be 0 now, so I think we can remove it."

Thanks for quick response, but I'm not sure if statement
"cmd_len should never be 0 now" is correct, because the cmd_len is
in fact equal to 0 here and this BUG can be triggered on mainline, 5.14,
and 5.10 stable kernels.

(+Doug Gilbert)

One of the functions in the call stack in the first message of this email
thread is sg_io(). I am not aware of any documentation that specifies whether
it is valid to set cmd_len in the sg_io header to zero. My opinion is that
the SG_IO implementation should either reject cmd_len == 0 or set cmd_len
to a valid value if it is zero.

For the sg driver in production, the v3 interface users (including
ioctl(<sg_fd>, SG_IO,) ) have this check:

if ((!hp->cmdp) || (hp->cmd_len < 6) || (hp->cmd_len > sizeof (cmnd))) {
sg_remove_request(sfp, srp);
return -EMSGSIZE;
}

For the v1 and v2 interface users there was no cmd_len. It was deduced via
COMMAND_SIZE(opcode) or by calling ioctl(SG_NEXT_CMD_LEN) prior to the write()
to issue the SCSI command.

Looking at the block layer/ SCSI mid level implementation of ioctl(SG_IO) I
can see no lower bound check on cmd_len (which is 'unsigned char' so at least
it can't go negative).

Doug Gilbert