Re: [PATCH 1/2] comedi: Prevent writes to the buffer through read-only mappings

From: Ian Abbott

Date: Mon Nov 30 2026 - 06:23:37 EST


On 29/11/2026 19:33, Chris Down wrote:
comedi_mmap() maps the pages of a buffer that wasn't allocated for DMA
with remap_pfn_range(..., PAGE_SHARED), ignoring vma->vm_page_prot. As a
result, the PTEs it installs are always writable, even for a PROT_READ
mapping, and even when the device was opened O_RDONLY (where VM_MAYWRITE
is clear and mprotect() refuses to add PROT_WRITE).

For example, with comedi_test attached as /dev/comedi0:

fd = open("/dev/comedi0", O_RDONLY);
p = mmap(NULL, 4096, PROT_READ, MAP_SHARED, fd, 0);
*p = 0x5a;

The store doesn't fault, and the byte in the read subdevice's buffer
changes from 00 to 5a. So anyone who can open a comedi device read-only
can overwrite the samples in the acquisition buffer that are read by
whoever is running the command. The same goes for a one page
MAP_PRIVATE mapping, where a store should break CoW but goes straight to
the shared buffer instead.

The DMA path is already fine, since dma_mmap_coherent() builds its PTEs
from vma->vm_page_prot.

Let's pass vma->vm_page_prot to remap_pfn_range() as well, so the PTEs
are only writable when the mapping is. Writable MAP_SHARED mappings of a
device opened O_RDWR, as comedilib's demos use, still work as before.

Fixes: ed9eccbe8970 ("Staging: add comedi core")
Cc: stable@xxxxxxxxxxxxxxx
Signed-off-by: Chris Down <chris@xxxxxxxxxxxxxx>
---
drivers/comedi/comedi_fops.c | 2 +-
1 file changed, 1 insertion(+), 1 deletion(-)

diff --git a/drivers/comedi/comedi_fops.c b/drivers/comedi/comedi_fops.c
index 6d71ceeff6fc..d31214f1a8c1 100644
--- a/drivers/comedi/comedi_fops.c
+++ b/drivers/comedi/comedi_fops.c
@@ -2574,7 +2574,7 @@ static int comedi_mmap(struct file *file, struct vm_area_struct *vma)
buf = &bm->page_list[i];
pfn = page_to_pfn(virt_to_page(buf->virt_addr));
retval = remap_pfn_range(vma, start, pfn, PAGE_SIZE,
- PAGE_SHARED);
+ vma->vm_page_prot);
if (retval)
break;

Looks good, thanks!

Reviewed-by: Ian Abbott <abbotti@xxxxxxxxx>

--
-=( Ian Abbott <abbotti@xxxxxxxxx> || MEV Ltd. is a company )=-
-=( registered in England & Wales. Regd. number: 02862268. )=-
-=( Regd. addr.: S11 & 12 Building 67, Europa Business Park, )=-
-=( Bird Hall Lane, STOCKPORT, SK3 0XA, UK. || www.mev.co.uk )=-