tpm: Reject reads outside the response buffer
Subsystems (4)
PATCH 1/1 tpm: Reject reads outside the response buffer
tpm_common_read() clamps the transfer length to priv->response_length but does not validate the file offset (*off) before using it to index the fixed TPM_BUFSIZE-byte priv->data_buffer:
ret_size = min_t(ssize_t, size, priv->response_length); copy_to_user(buf, priv->data_buffer + *off, ret_size); memset(priv->data_buffer + *off, 0, ret_size);
Sequential read() keeps *off in range, but the fops use the legacy .read callback and neither tpm_open() nor tpmrm_open() calls nonseekable_open(), so FMODE_PREAD stays set and pread(2) passes an arbitrary offset straight into *off. An out-of-range offset then accesses memory beyond data_buffer, causing an out-of-bounds read through copy_to_user() and, when the copy succeeds, an out-of-bounds zero-write through memset().
Reject any read whose offset and length leave the response buffer.
---
Notes for reviewers (not part of the commit):
Reproduced on a KASAN 6.12 build with a swtpm TPM2 device. After a command leaves a response pending, pread(fd, buf, 16, 0x1400) triggers two slab-out-of-bounds reports, one for the copy_to_user() read and one for the memset() write; on that x86-64 build the faulting access was 962 bytes past a 4344-byte struct tpmrm_priv served from kmalloc-8k. With this patch, out-of-range preads (offset past the buffer, at the end, or an in-range offset whose length crosses the end) return -EINVAL with no KASAN report, while sequential partial reads still return the full response and a normal read after a rejected pread still works.
Reaching it needs a process that can open the TPM device and send a command. Access depends on the device-node permissions; the upstream tpm2-tss udev rules set tpmrm devices to mode 0660 with group tss. My reproduction ran as root, so I have not shown non-root reach on a specific distribution or built a privilege-escalation chain.
I searched public archives on 2026-07-10 and found no matching report, which does not rule out a private, very recent, or unindexed one. Found through AI-assisted source review; the code path and reproduction were verified by hand. A reproducer and full logs are available on request.
drivers/char/tpm/tpm-dev-common.c | 10 ++++++++++ 1 file changed, 10 insertions(+)
drivers/char/tpm/tpm-dev-common.c +10 -0
@@ -145,6 +145,16 @@ ssize_t tpm_common_read(struct file *file, char __user *buf, goto out; } +/* +* Reject reads whose offset and length fall outside the fixed +* response buffer. +*/ +if (*off <0 || *off >=TPM_BUFSIZE || + ret_size >TPM_BUFSIZE - *off) { + ret_size = -EINVAL ; + goto out; + } + rc =copy_to_user (buf, priv->data_buffer + *off, ret_size);if (rc) {memset (priv->data_buffer,0 ,TPM_BUFSIZE );
Signature · 1 line
2.43.0
Jarkko Sakkinen
maintainerQuoted 39 lines · Jaewon Yang
tpm_common_read()clamps the transfer length topriv->response_lengthbut does not validate the file offset (*off) before using it to index the fixed TPM_BUFSIZE-bytepriv->data_buffer:ret_size = min_t(ssize_t, size, priv->response_length); copy_to_user(buf, priv->data_buffer + *off, ret_size); memset(priv->data_buffer + *off, 0, ret_size);Sequential
read()keeps *off in range, but the fops use the legacy .read callback and neithertpm_open()nortpmrm_open()callsnonseekable_open(), soFMODE_PREADstays set and pread(2) passes an arbitrary offset straight into *off. An out-of-range offset then accesses memory beyonddata_buffer, causing an out-of-bounds read throughcopy_to_user()and, when the copy succeeds, an out-of-bounds zero-write throughmemset().Reject any read whose offset and length leave the response buffer.
Fixes 9488585b21be ("tpm: add support for partial reads")Signed-off-by Jaewon Yang <[email protected]>---
Notes for reviewers (not part of the commit):Reproduced on a KASAN 6.12 build with a swtpm TPM2 device. After a command leaves a response pending,
pread(fd, buf, 16, 0x1400)triggers two slab-out-of-bounds reports, one for thecopy_to_user()read and one for thememset()write; on that x86-64 build the faulting access was 962 bytes past a 4344-byte structtpmrm_privserved from kmalloc-8k. With this patch, out-of-range preads (offset past the buffer, at the end, or an in-range offset whose length crosses the end) return-EINVALwith no KASAN report, while sequential partial reads still return the full response and a normal read after a rejected pread still works.Reaching it needs a process that can open the TPM device and send a command. Access depends on the device-node permissions; the upstream tpm2-tss udev rules set tpmrm devices to mode 0660 with group tss. My reproduction ran as root, so I have not shown non-root reach on a specific distribution or built a privilege-escalation chain.
Quoted 4 lines
I searched public archives on 2026-07-10 and found no matching report, which does not rule out a private, very recent, or unindexed one. Found through AI-assisted source review; the code path and reproduction were verified by hand. A reproducer and full logs are available on request.
I will choose to skip reading most of the text as already commit message had zero relevant information.
Thus, NAK.
Please don't delegate the work for me that you should doing i.e. looking at your reproducer and describing the scenario/sequence that would lead to infeasible consequence.
Quoted 28 lines
drivers/char/tpm/tpm-dev-common.c | 10 ++++++++++ 1 file changed, 10 insertions(+)drivers/char/tpm/tpm-dev-common.c +10
-0@@ -145,6 +145,16 @@ ssize_t tpm_common_read(struct file *file, char __user *buf, goto out; } +/* +* Reject reads whose offset and length fall outside the fixed +* response buffer. +*/ +if (*off <0 || *off >=TPM_BUFSIZE || + ret_size >TPM_BUFSIZE - *off) { + ret_size = -EINVAL ; + goto out; + } + rc =copy_to_user (buf, priv->data_buffer + *off, ret_size);if (rc) {memset (priv->data_buffer,0 ,TPM_BUFSIZE );Signature · 1 line
2.43.0
BR, Jarkko
Quoted 4 lines · Jarkko Sakkinen
Please don't delegate the work for me that you should doing i.e. looking at your reproducer and describing the scenario/sequence that would lead to infeasible consequence.
I don't understand this reply.
The original email had all the relevant information: how to trigger the condition, what the bug is, and what's going on.
The bug seems straightforward: the tpm code appears to blindly use a user-supplied 'loff_t' that is simply not checked. The email you responded to seems very clear on the issue:
Sequential read() keeps *off in range, but the fops use the legacy .read callback and neither tpm_open() nor tpmrm_open() calls nonseekable_open(), so FMODE_PREAD stays set and pread(2) passes an arbitrary offset straight into *off.
So what's the problem here?
Now, honestly, I think this tpm code is badly written to begin with, and the patch doesn't fix that fundamental issue.
The code simply shouldn't change response_length by how much have been read, it should just use the fixed size of the buffer and compare it to the offset.
And once the buffer has been fully used, we clean it up.
Something ENTIRELY UNTESTED like the attached patch. But I do want to point out that this patch is
(a) UNTESTED
(b) bigger and more invasive than the simple "just check the offset"
That said, I really don't like how the original patch by Jaewon depends on TPM_BUFSIZE when the real limit is that "response_length", but that's a direct result of the tpm code being disgustign and changing response_length as a response to partial reads.
So the attached patch tries to fix that fundamental mistake, and in the process I think it makes the code more readable, but whatever. I probably think that primarily because I wrote the patch.
Comments? But this "dismiss a patch based on bogus reasons" seems like a huge mistake.
Again. The attached patch is UNTESTED.
Linus
drivers/char/tpm/tpm-dev-common.c | 67 ++++++++++++++++++++++----------------- 1 file changed, 38 insertions(+), 29 deletions(-)
drivers/char/tpm/tpm-dev-common.c +38 -29
@@ -127,44 +127,53 @@ void tpm_common_open(struct file *file, struct tpm_chip *chip, file->private_data = priv; } +static inline ssize_t tpm_common_read_cleanup (struct file_priv *priv,loff_t *off,ssize_t ret) +{ + *off =0 ; +timer_delete_sync (&priv->user_read_timer); +flush_work (&priv->timeout_work); +return ret; +} +ssize_t tpm_common_read (struct file *file,char __user *buf,size_t size,loff_t *off) {struct file_priv *priv = file->private_data; -ssize_t ret_size =0 ; -int rc; +ssize_t response_length; +u64 offset; -mutex_lock (&priv->buffer_mutex); +if (!size) +return 0 ; -if (priv->response_length) { - priv->response_read = true; +guard (mutex)(&priv->buffer_mutex); + response_length = priv->response_length; - ret_size =min_t (ssize_t, size, priv->response_length); -if (ret_size <=0 ) { - priv->response_length =0 ; - goto out; - } +// Error or nothing to read? +if (response_length <=0 ) +return tpm_common_read_cleanup (priv, off, response_length); - rc =copy_to_user (buf, priv->data_buffer + *off, ret_size); -if (rc) { -memset (priv->data_buffer,0 ,TPM_BUFSIZE ); - priv->response_length =0 ; - ret_size = -EFAULT ; - }else { -memset (priv->data_buffer + *off,0 , ret_size); - priv->response_length -= ret_size; - *off += ret_size; - } - } + offset = *off; -out: -if (!priv->response_length) { - *off =0 ; -timer_delete_sync (&priv->user_read_timer); -flush_work (&priv->timeout_work); - } -mutex_unlock (&priv->buffer_mutex); -return ret_size; +// Have we already read everything? Return EOF +if (offset >= response_length) +return tpm_common_read_cleanup (priv, off,0 ); + +// Do the potentially partial read + size =min_t (size_t, size, response_length - offset); + size -=copy_to_user (buf, priv->data_buffer + offset, size); +if (!size) +return -EFAULT ; + offset += size; + +// Are we all done with the response? +if (offset >= response_length) +return tpm_common_read_cleanup (priv, off, size); + +// We still have some data left, update the offset +// and be ready to read the rest later - don't do +// the cleanup. + *off = offset; +return size; } ssize_t tpm_common_write(struct file *file, const char __user *buf,
PATCH v2 1/1 tpm: Make the TPM character devices non-seekable
The TPM character devices expose a sequential command/response interface, but their open handlers leave FMODE_PREAD and FMODE_PWRITE enabled.
After a command leaves a response pending, pread(fd, buf, 16, 0x1400) passes 0x1400 as *off to tpm_common_read(). The transfer length is bounded by response_length, but the offset is used unchecked when forming data_buffer + *off. A sufficiently large offset therefore causes an out-of-bounds heap read through copy_to_user() and, if the copy succeeds, an out-of-bounds zero-write through the following memset().
Positional I/O does not provide coherent semantics for this interface. An arbitrary pread offset cannot represent how much of a response has been consumed sequentially. The write callback always stores a command at the start of data_buffer, while pwrite() does not update file->f_pos and can leave the sequential read cursor stale.
Call nonseekable_open() from both open handlers. This removes FMODE_PREAD and FMODE_PWRITE, causing positional reads and writes to fail with -ESPIPE before reaching the TPM callbacks, and explicitly marks the files non-seekable. Normal read() and write() continue to use the existing sequential f_pos cursor, leaving the response state machine unchanged.
Tested on Linux 6.12 with KASAN and a swtpm TPM2 device:
- sequential partial reads returned the complete response;
- pread() and preadv() with offset 0x1400 returned -ESPIPE;
- pwrite() and pwritev() with offset zero returned -ESPIPE;
- the pending response remained intact after the rejected operations;
- a subsequent normal command/response cycle completed normally; and
- no KASAN report was produced.
---
Changes in v2:
- replace the response-buffer bounds check with nonseekable_open();
- reject positional read and write at open time;
- preserve the existing sequential read/write state machine.
The alternative response_length rework proposed during review was tested and not taken: a read-until-EOF loop hangs because cleanup resets *off without clearing response_length. It also treats an arbitrary positional offset as the consumption cursor; for example,
pread(fd, &c, 1, 99)
on a 100-byte response can discard bytes 0 through 98 without returning them.
drivers/char/tpm/tpm-dev.c | 2 +- drivers/char/tpm/tpmrm-dev.c | 2 +- 2 files changed, 2 insertions(+), 2 deletions(-)
drivers/char/tpm/tpm-dev.c +1 -1
@@ -36,7 +36,7 @@ static int tpm_open(struct inode *inode, struct file *file)tpm_common_open (file, chip, priv,NULL ); -return 0 ; +return nonseekable_open (inode, file); out:clear_bit (0 , &chip->is_open);
drivers/char/tpm/tpmrm-dev.c +1 -1
@@ -29,7 +29,7 @@ static int tpmrm_open(struct inode *inode, struct file *file)tpm_common_open (file, chip, &priv->priv, &priv->space); -return 0 ; +return nonseekable_open (inode, file); }static int tpmrm_release (struct inode *inode,struct file *file)
Signature · 1 line
2.43.0
Re: [PATCH v2] tpm: Make the TPM character devices non-seekable
Quoted 2 lines · Jaewon Yang
Call
nonseekable_open()from both open handlers.
Ack, this seems to be the simplest approach. I'll just commit it as-is,
Linus
Re: [PATCH v2] tpm: Make the TPM character devices non-seekable
In reply to Jaewon YangQuoted 87 lines · Jaewon Yang
The TPM character devices expose a sequential command/response interface, but their open handlers leave
FMODE_PREADandFMODE_PWRITEenabled.After a command leaves a response pending,
pread(fd, buf, 16, 0x1400)passes0x1400as *off totpm_common_read(). The transfer length is bounded byresponse_length, but the offset is used unchecked when formingdata_buffer+ *off. A sufficiently large offset therefore causes an out-of-bounds heap read throughcopy_to_user()and, if the copy succeeds, an out-of-bounds zero-write through the followingmemset().Positional I/O does not provide coherent semantics for this interface. An arbitrary pread offset cannot represent how much of a response has been consumed sequentially. The write callback always stores a command at the start of
data_buffer, whilepwrite()does not updatefile->f_posand can leave the sequential read cursor stale.Call
nonseekable_open()from both open handlers. This removesFMODE_PREADandFMODE_PWRITE, causing positional reads and writes to fail with-ESPIPEbefore reaching the TPM callbacks, and explicitly marks the files non-seekable. Normalread()andwrite()continue to use the existing sequentialf_poscursor, leaving the response state machine unchanged.Tested on Linux 6.12 with KASAN and a swtpm TPM2 device:
- sequential partial reads returned the complete response;
-pread()andpreadv()with offset0x1400returned-ESPIPE;
-pwrite()andpwritev()with offset zero returned-ESPIPE;
- the pending response remained intact after the rejected operations;
- a subsequent normal command/response cycle completed normally; and
- no KASAN report was produced.Fixes 9488585b21be ("tpm: add support for partial reads")Signed-off-by Jaewon Yang <[email protected]>---
Changes in v2:
- replace the response-buffer bounds check withnonseekable_open();
- reject positional read and write at open time;
- preserve the existing sequential read/write state machine.The alternative
response_lengthrework proposed during review was tested and not taken: a read-until-EOF loop hangs because cleanup resets *off without clearingresponse_length. It also treats an arbitrary positional offset as the consumption cursor; for example,pread(fd, &c, 1, 99)on a 100-byte response can discard bytes 0 through 98 without returning them.
drivers/char/tpm/tpm-dev.c | 2 +- drivers/char/tpm/tpmrm-dev.c | 2 +- 2 files changed, 2 insertions(+), 2 deletions(-)drivers/char/tpm/tpm-dev.c +1
-1@@ -36,7 +36,7 @@ static int tpm_open(struct inode *inode, struct file *file)tpm_common_open (file, chip, priv,NULL ); -return 0 ; +return nonseekable_open (inode, file); out:clear_bit (0 , &chip->is_open);drivers/char/tpm/tpmrm-dev.c +1
-1@@ -29,7 +29,7 @@ static int tpmrm_open(struct inode *inode, struct file *file)tpm_common_open (file, chip, &priv->priv, &priv->space); -return 0 ; +return nonseekable_open (inode, file); }static int tpmrm_release (struct inode *inode,struct file *file)Signature · 1 line
2.43.0
LGTM
BR, Jarkko
Jarkko Sakkinen
maintainerRe: [PATCH v2] tpm: Make the TPM character devices non-seekable
Quoted 92 lines · Jarkko Sakkinen
Quoted 87 lines · Jaewon Yang
The TPM character devices expose a sequential command/response interface, but their open handlers leave
FMODE_PREADandFMODE_PWRITEenabled.After a command leaves a response pending,
pread(fd, buf, 16, 0x1400)passes0x1400as *off totpm_common_read(). The transfer length is bounded byresponse_length, but the offset is used unchecked when formingdata_buffer+ *off. A sufficiently large offset therefore causes an out-of-bounds heap read throughcopy_to_user()and, if the copy succeeds, an out-of-bounds zero-write through the followingmemset().Positional I/O does not provide coherent semantics for this interface. An arbitrary pread offset cannot represent how much of a response has been consumed sequentially. The write callback always stores a command at the start of
data_buffer, whilepwrite()does not updatefile->f_posand can leave the sequential read cursor stale.Call
nonseekable_open()from both open handlers. This removesFMODE_PREADandFMODE_PWRITE, causing positional reads and writes to fail with-ESPIPEbefore reaching the TPM callbacks, and explicitly marks the files non-seekable. Normalread()andwrite()continue to use the existing sequentialf_poscursor, leaving the response state machine unchanged.Tested on Linux 6.12 with KASAN and a swtpm TPM2 device:
- sequential partial reads returned the complete response;
-pread()andpreadv()with offset0x1400returned-ESPIPE;
-pwrite()andpwritev()with offset zero returned-ESPIPE;
- the pending response remained intact after the rejected operations;
- a subsequent normal command/response cycle completed normally; and
- no KASAN report was produced.Fixes 9488585b21be ("tpm: add support for partial reads")Signed-off-by Jaewon Yang <[email protected]>---
Changes in v2:
- replace the response-buffer bounds check withnonseekable_open();
- reject positional read and write at open time;
- preserve the existing sequential read/write state machine.The alternative
response_lengthrework proposed during review was tested and not taken: a read-until-EOF loop hangs because cleanup resets *off without clearingresponse_length. It also treats an arbitrary positional offset as the consumption cursor; for example,pread(fd, &c, 1, 99)on a 100-byte response can discard bytes 0 through 98 without returning them.
drivers/char/tpm/tpm-dev.c | 2 +- drivers/char/tpm/tpmrm-dev.c | 2 +- 2 files changed, 2 insertions(+), 2 deletions(-)drivers/char/tpm/tpm-dev.c +1
-1@@ -36,7 +36,7 @@ static int tpm_open(struct inode *inode, struct file *file)tpm_common_open (file, chip, priv,NULL ); -return 0 ; +return nonseekable_open (inode, file); out:clear_bit (0 , &chip->is_open);drivers/char/tpm/tpmrm-dev.c +1
-1@@ -29,7 +29,7 @@ static int tpmrm_open(struct inode *inode, struct file *file)tpm_common_open (file, chip, &priv->priv, &priv->space); -return 0 ; +return nonseekable_open (inode, file); }static int tpmrm_release (struct inode *inode,struct file *file)Signature · 1 line
2.43.0LGTM
Quoted 1 line
Acked-by Jarkko Sakkinen <[email protected]>
[A slow response time due on holiday until end of this Month.]
BR, Jarkko
PATCH 1/1 tpm: track the response read position internally, not via the file offset
Commit f20d61c22bca ("tpm: Make the TPM character devices non-seekable") made pread() fail with -ESPIPE, but tpm_common_read() still indexes data_buffer with *off, and io_uring can still set it: IORING_OP_READ copies sqe->off into ki_pos without checking FMODE_PREAD, and loop_rw_iter() passes it to ->read(). With sqe->off = 0x1400 the read copies heap memory past data_buffer to user space and then zeroes it:
BUG: KASAN: slab-out-of-bounds in _copy_to_user+0x4b/0x70 Read of size 16 by task iou-wrk-148/149 Call Trace: _copy_to_user+0x4b/0x70 tpm_common_read+0x16e/0x2c0 loop_rw_iter+0x235/0x5a0 __io_read+0xc6e/0x11a0 io_read+0x8a/0x180
Keep the read position in file_priv, protected by buffer_mutex, and ignore *off. This also closes a race where read() samples f_pos before taking buffer_mutex and a concurrent write() replaces the response in between.
---
- A C reproducer for the io_uring path is available on request.
- nonseekable_open() only closes the VFS doors (lseek(), pread()); io_uring bypasses both, so with this patch an IORING_OP_READ that passes an explicit sqe->off ignores the offset and reads sequentially.
drivers/char/tpm/tpm-dev-common.c | 11 ++++++----- drivers/char/tpm/tpm-dev.h | 1 + 2 files changed, 7 insertions(+), 5 deletions(-)
drivers/char/tpm/tpm-dev-common.c +6 -5
@@ -107,6 +107,7 @@ static void tpm_timeout_work(struct work_struct *work)mutex_lock (&priv->buffer_mutex); priv->response_read = true; priv->response_length =0 ; + priv->read_pos =0 ;memset (priv->data_buffer,0 ,sizeof (priv->data_buffer));mutex_unlock (&priv->buffer_mutex);wake_up_interruptible (&priv->async_wait);
@@ -149,21 +150,21 @@ ssize_t tpm_common_read(struct file *file, char __user *buf, goto out; } - rc =copy_to_user (buf, priv->data_buffer + *off, ret_size); + rc =copy_to_user (buf, priv->data_buffer + priv->read_pos, ret_size);if (rc) {memset (priv->data_buffer,0 ,TPM_BUFSIZE ); priv->response_length =0 ; ret_size = -EFAULT ; }else { -memset (priv->data_buffer + *off,0 , ret_size); +memset (priv->data_buffer + priv->read_pos,0 , ret_size); priv->response_length -= ret_size; - *off += ret_size; + priv->read_pos += ret_size; } } out:if (!priv->response_length) { - *off =0 ; + priv->read_pos =0 ;timer_delete_sync (&priv->user_read_timer); flush = true; }
@@ -214,7 +215,7 @@ ssize_t tpm_common_write(struct file *file, const char __user *buf, priv->response_length =0 ; priv->response_read = false; - *off =0 ; + priv->read_pos =0 ;/* * If in nonblocking mode schedule an async job to send
drivers/char/tpm/tpm-dev.h +1 -0
@@ -15,6 +15,7 @@ struct file_priv {struct work_struct async_work;wait_queue_head_t async_wait;ssize_t response_length; +size_t read_pos;bool response_read;bool command_enqueued;
Signature · 1 line
2.52.0
Jarkko Sakkinen
maintainerRe: [PATCH] tpm: track the response read position internally, not via the file offset
Please remove that claude'ism from short summary (, not.. uaargh).
Quoted 1 line · Rustam Mustafin
Commit
f20d61c22bca("tpm: Make the TPM character devices non-seekable")
Duplicate information to fixes tag.
Quoted 2 lines
made
pread()fail with-ESPIPE, buttpm_common_read()still indexesdata_bufferwith *off, andio_uringcan still set it:IORING_OP_READ
io_uring is a data structure, not an active actor and IORING_OP_READ is a constant.
Quoted 13 lines
copies
sqe->offintoki_poswithout checkingFMODE_PREAD, andloop_rw_iter()passes it to ->read(). Withsqe->off=0x1400the read copies heap memory pastdata_bufferto user space and then zeroes it:BUG: KASAN: slab-out-of-bounds in _copy_to_user+0x4b/0x70 Read of size 16 by task iou-wrk-148/149 Call Trace: _copy_to_user+0x4b/0x70 tpm_common_read+0x16e/0x2c0 loop_rw_iter+0x235/0x5a0 __io_read+0xc6e/0x11a0 io_read+0x8a/0x180
Quoted 1 line
Keep the read position in
file_priv, protected bybuffer_mutex, and
Why open code variable names in English?
Quoted 8 lines
ignore *off. This also closes a race where
read()samplesf_posbefore takingbuffer_mutexand a concurrentwrite()replaces the response in between.Fixes 9488585b21be ("tpm: add support for partial reads")Link https://lore.kernel.org/r/CAHk-=wi8aXM9=Y8othMb1oxTv-PDw4isj-FPbXu0MXsm_EPE1g@mail.gmail.com/ open hereSigned-off-by Rustam Mustafin <[email protected]>
Quoted 5 lines
---
- A C reproducer for theio_uringpath is available on request.
-nonseekable_open()only closes the VFS doors (lseek(),pread());io_uringbypasses both, so with this patch anIORING_OP_READthat passes an explicitsqe->offignores the offset and reads sequentially.
Why weren't you able to realize this in the kselftest?
Quoted 10 lines
drivers/char/tpm/tpm-dev-common.c | 11 ++++++----- drivers/char/tpm/tpm-dev.h | 1 + 2 files changed, 7 insertions(+), 5 deletions(-)drivers/char/tpm/tpm-dev-common.c +0
-0
drivers/char/tpm/tpm-dev-common.c static void tpm_timeout_work(struct work_struct *work) · line 110
Quoted 4 lines
drivers/char/tpm/tpm-dev-common.c +1
-0@@ -107,6 +107,7 @@ static void tpm_timeout_work(struct work_struct *work)mutex_lock (&priv->buffer_mutex); priv->response_read = true; priv->response_length =0 ; + priv->read_pos =0 ;
I did search read_pos but it had zero hits in the commit message.
Quoted 53 lines
drivers/char/tpm/tpm-dev-common.c +5
-5memset (priv->data_buffer,0 ,sizeof (priv->data_buffer));mutex_unlock (&priv->buffer_mutex);wake_up_interruptible (&priv->async_wait);@@ -149,21 +150,21 @@ ssize_t tpm_common_read(struct file *file, char __user *buf, goto out; } - rc =copy_to_user (buf, priv->data_buffer + *off, ret_size); + rc =copy_to_user (buf, priv->data_buffer + priv->read_pos, ret_size);if (rc) {memset (priv->data_buffer,0 ,TPM_BUFSIZE ); priv->response_length =0 ; ret_size = -EFAULT ; }else { -memset (priv->data_buffer + *off,0 , ret_size); +memset (priv->data_buffer + priv->read_pos,0 , ret_size); priv->response_length -= ret_size; - *off += ret_size; + priv->read_pos += ret_size; } } out:if (!priv->response_length) { - *off =0 ; + priv->read_pos =0 ;timer_delete_sync (&priv->user_read_timer); flush = true; }@@ -214,7 +215,7 @@ ssize_t tpm_common_write(struct file *file, const char __user *buf, priv->response_length =0 ; priv->response_read = false; - *off =0 ; + priv->read_pos =0 ;/* * If in nonblocking mode schedule an async job to send drivers/char/tpm/tpm-dev.h +1
-0@@ -15,6 +15,7 @@ struct file_priv {struct work_struct async_work;wait_queue_head_t async_wait;ssize_t response_length; +size_t read_pos;bool response_read;bool command_enqueued;Signature · 1 line
2.52.0
Br, Jarkko
Jarkko Sakkinen
maintainerRe: [PATCH] tpm: track the response read position internally, not via the file offset
Quoted 1 line · Jarkko Sakkinen
...
I think this would be more feasible:
if (current->flags & PF_IO_WORKER)
return -EIO;
if ((current->flags & PF_KTHREAD) && current->io_uring)
return -EIO;I.e., block io_uring entirely.
Br, Jarkko
Jarkko Sakkinen
maintainerRe: [PATCH] tpm: track the response read position internally, not via the file offset
Quoted 5 lines · Jarkko Sakkinen
Quoted 1 line · Jarkko Sakkinen
...
I think this would be more feasible:
Quoted 7 lines
if (current->flags & PF_IO_WORKER) return -EIO; if ((current->flags & PF_KTHREAD) && current->io_uring) return -EIO;I.e., block
io_uringentirely.
And kselftest can then be extended to address this case (as a separate patch) making this two-patch patch set.
Short summary would be e.g. (or use your imagination):
"tpm: Do not allow io_uring for /dev/tpm{,rm0}"
Br, Jarkko
Re: [PATCH] tpm: track the response read position internally, not via the file offset
Quoted 10 lines · Jarkko Sakkinen
Quoted 9 lines · Jarkko Sakkinen
I think this would be more feasible:
if (current->flags & PF_IO_WORKER) return -EIO; if ((current->flags & PF_KTHREAD) && current->io_uring) return -EIO;I.e., block
io_uringentirely.
Hi Jarkko, thanks for the review.
These checks do not fully block io_uring. With O_NONBLOCK set and a response ready, io_uring calls ->read() inline from the caller's own task, where neither PF_IO_WORKER nor PF_KTHREAD is set. loop_rw_iter() declines the inline attempt only when the file lacks O_NONBLOCK:
if ((kiocb->ki_flags & IOCB_NOWAIT) &&
!(kiocb->ki_filp->f_flags & O_NONBLOCK))
return -EAGAIN;I built a kernel with both checks applied and the injected offset still reaches tpm_common_read():
BUG: KASAN: slab-out-of-bounds in _copy_to_user+0x4b/0x70
Read of size 16 at addr ffff88810c3455d2 by task python3/134
Call Trace:
_copy_to_user+0x4b/0x70
tpm_common_read+0x1e6/0x360
loop_rw_iter+0x235/0x5a0
__io_read+0xc6e/0x11a0
io_read+0x8a/0x180Reproducer:
- open("/dev/tpm0", O_RDWR | O_NONBLOCK)
- write() a command, then poll() until POLLIN
- submit IORING_OP_READ with sqe->off = 0x1400, without IOSQE_ASYNC (this is how tpm2-tss opens the device O_RDWR | O_NONBLOCK).
Checking current->io_uring alone would catch the inline path, but then a process that uses io_uring for anything else would also lose plain read()/write() on the device.
For v2 I propose:
1. The read position fix, with your review comments applied.
2. stream_open() instead of nonseekable_open(), on top of 1. With FMODE_STREAM both the VFS and io_uring pass a NULL offset to the driver. This follows c5bf68fe0c86 ("*: convert stream-like files from nonseekable_open -> stream_open").
3. A kselftest: lseek() and pread() fail with -ESPIPE, chunked reads of a TPM2_GetCapability(TPM_PT_FAMILY_INDICATOR) response match a one-shot read, and an io_uring read with an explicit sqe->off returns the start of the response.
Br,
Rustam
A message that is not in the archive (sent off-list or not yet received): CAG6=z5sxUo1x6mpotkNZXk=nQYvD2AyMLSDhzD3B3kqxJ1=iaw@mail.gmail.com
Jarkko Sakkinen
maintainerRe: [PATCH] tpm: track the response read position internally, not via the file offset
Quoted 58 lines · Rustam Mustafin
Quoted 10 lines · Jarkko Sakkinen
Quoted 9 lines · Jarkko Sakkinen
I think this would be more feasible:
if (
current->flags&PF_IO_WORKER)
return-EIO;if ((
current->flags&PF_KTHREAD) &¤t->io_uring) return-EIO;I.e., block
io_uringentirely.Hi Jarkko, thanks for the review.
These checks do not fully block
io_uring. WithO_NONBLOCKset and a response ready,io_uringcalls ->read() inline from the caller's own task, where neitherPF_IO_WORKERnorPF_KTHREADis set.loop_rw_iter()declines the inline attempt only when the file lacksO_NONBLOCK:if ((
kiocb->ki_flags&IOCB_NOWAIT) &&
!(kiocb->ki_filp->f_flags &O_NONBLOCK))
return-EAGAIN;I built a kernel with both checks applied and the injected offset still reaches
tpm_common_read():BUG: KASAN: slab-out-of-bounds in _copy_to_user+0x4b/0x70 Read of size 16 at addr ffff88810c3455d2 by task python3/134 Call Trace: _copy_to_user+0x4b/0x70 tpm_common_read+0x1e6/0x360 loop_rw_iter+0x235/0x5a0 __io_read+0xc6e/0x11a0 io_read+0x8a/0x180Reproducer:
-open("/dev/tpm0", O_RDWR | O_NONBLOCK)
-write()a command, thenpoll()until POLLIN
- submitIORING_OP_READwithsqe->off=0x1400, withoutIOSQE_ASYNC(this is how tpm2-tss opens the deviceO_RDWR|O_NONBLOCK).Checking
current->io_uringalone would catch the inline path, but then a process that usesio_uringfor anything else would also lose plain read()/write() on the device.For v2 I propose:
1. The read position fix, with your review comments applied.
2.stream_open()instead ofnonseekable_open(), on top of 1. WithFMODE_STREAMboth the VFS andio_uringpass a NULL offset to the driver. This followsc5bf68fe0c86("*: convert stream-like files fromnonseekable_open->stream_open").
3. A kselftest:lseek()andpread()fail with-ESPIPE, chunked reads of aTPM2_GetCapability(TPM_PT_FAMILY_INDICATOR)response match a one-shot read, and anio_uringread with an explicitsqe->offreturns the start of the response.
Quoted 2 lines
Br,
Rustam
I wrote that out of my memory. I did not expect to be exactly out.
Block uring.
Br, Jarkko
Re: [PATCH] tpm: track the response read position internally, not via the file offset
Quoted 3 lines · Jarkko Sakkinen
I wrote that out of my memory. I did not expect to be exactly out.
Block uring.
Hi Jarkko,
I looked at three ways to do it:
1. ->read_iter and ->write_iter that just return -EINVAL.
Simple, but readv() and single-iovec writev() stop working.
2. ->read_iter and ->write_iter that keep readv()/writev() working and fail with:
if (!is_sync_kiocb(iocb) ||
(iocb->ki_flags & IOCB_NOWAIT) ||
(current->flags & PF_IO_WORKER))
return -EINVAL; The first check catches normal io_uring reads/writes and AIO. The other two are for IORING_OP_READ_MULTISHOT, which uses a sync kiocb.
3. A new per-request flag set by io_uring and checked by TPM.
Needs io_uring/VFS changes and is harder to backport.
With 2 and 3, vfs_iter_read() callers such as Coda (which forwards reads to a file passed in by its userspace daemon) can reach tpm_common_read() with their own offset. Today these calls fail, because the TPM files have no ->read_iter.
I have 2 implemented and tested. It would also need a check of *off in tpm_common_read(), because of the above.
Which one do you prefer?
Br,
Rustam
Jarkko Sakkinen
maintainerRe: [PATCH] tpm: track the response read position internally, not via the file offset
Quoted 5 lines · Rustam Mustafin
Quoted 3 lines · Jarkko Sakkinen
I wrote that out of my memory. I did not expect to be exactly out.
Block uring.
Quoted 7 lines
Hi Jarkko,
I looked at three ways to do it:
1. ->read_iter and ->write_iter that just return
-EINVAL.Simple, but
readv()and single-iovecwritev()stop working.
So. What would be the use case for this?
Quoted 11 lines
2. ->read_iter and ->write_iter that keep readv()/writev() working and fail with:
if (!is_sync_kiocb(iocb) || (iocb->ki_flags & IOCB_NOWAIT) || (current->flags & PF_IO_WORKER)) return -EINVAL;The first check catches normal
io_uringreads/writes and AIO. The other two are forIORING_OP_READ_MULTISHOT, which uses a sync kiocb.
So given how TPM works (reserved for only one process) I tend to prefer this. But -EIO should be used. It's as IO failure as it gets.
Quoted 9 lines
3. A new per-request flag set by
io_uringand checked by TPM.Needs
io_uring/VFSchanges and is harder to backport.With 2 and 3,
vfs_iter_read()callers such as Coda (which forwards reads to a file passed in by its userspace daemon) can reachtpm_common_read()with their own offset. Today these calls fail, because the TPM files have no ->read_iter.
2 is a bug fix, enabling is a feature. I guess this is the confusion.
Quoted 8 lines
I have 2 implemented and tested. It would also need a check of *off in
tpm_common_read(), because of the above.Which one do you prefer?
Br,
Rustam
/Jarkko
Re: [PATCH] tpm: track the response read position internally, not via the file offset
Quoted 5 lines · Jarkko Sakkinen
Quoted 3 lines
1. ->read_iter and ->write_iter that just return
-EINVAL.Simple, but
readv()and single-iovecwritev()stop working.So. What would be the use case for this?
I don't know of a real user, tpm2-tss uses read() and write(). It is about compatibility: readv() works today and can split a response, e.g. the 10-byte header into one buffer and the body into another. writev() is less useful, since a command must fit in one iovec.
Quoted 1 line
2 is a bug fix, enabling is a feature. I guess this is the confusion.
Adding ->read_iter for 2 also lets vfs_iter_read() callers such as Coda reach tpm_common_read(). Their requests look the same as readv(), so the checks in 2 cannot tell them apart. That's why I sent the read position fix as v2 first:
https://lore.kernel.org/all/[email protected]/
With it, tpm_common_read() ignores *off, so io_uring reads and writes work correctly. I'm not sure about blocking io_uring on top of that:
it works today, and I can't rule out users, especially of /dev/tpmrm0, which many processes can open at once. I have 2 implemented and tested, with -EIO, and can send it if it's needed.
Br,
Rustam
Jarkko Sakkinen
maintainerQuoted 47 lines · Linus Torvalds
Quoted 4 lines · Jarkko Sakkinen
Please don't delegate the work for me that you should doing i.e. looking at your reproducer and describing the scenario/sequence that would lead to infeasible consequence.
I don't understand this reply.
The original email had all the relevant information: how to trigger the condition, what the bug is, and what's going on.
The bug seems straightforward: the tpm code appears to blindly use a user-supplied '
loff_t' that is simply not checked. The email you responded to seems very clear on the issue:Sequential
read()keeps *off in range, but the fops use the legacy .read callback and neithertpm_open()nortpmrm_open()callsnonseekable_open(), soFMODE_PREADstays set and pread(2) passes an arbitrary offset straight into *off.So what's the problem here?
Now, honestly, I think this tpm code is badly written to begin with, and the patch doesn't fix that fundamental issue.
The code simply shouldn't change
response_lengthby how much have been read, it should just use the fixed size of the buffer and compare it to the offset.And once the buffer has been fully used, we clean it up.
Something ENTIRELY UNTESTED like the attached patch. But I do want to point out that this patch is
(a) UNTESTED
(b) bigger and more invasive than the simple "just check the offset"
That said, I really don't like how the original patch by Jaewon depends on
TPM_BUFSIZEwhen the real limit is that "response_length", but that's a direct result of the tpm code being disgustign and changingresponse_lengthas a response to partial reads.So the attached patch tries to fix that fundamental mistake, and in the process I think it makes the code more readable, but whatever. I probably think that primarily because I wrote the patch.
Quoted 6 lines
Comments? But this "dismiss a patch based on bogus reasons" seems like a huge mistake.
Again. The attached patch is UNTESTED.
Linus
I hear you. I was probably too quick draw with this one.
Quoted 80 lines
drivers/char/tpm/tpm-dev-common.c | 67 ++++++++++++++++++++++----------------- 1 file changed, 38 insertions(+), 29 deletions(-)drivers/char/tpm/tpm-dev-common.c +31
-29@@ -127,44 +127,53 @@ void tpm_common_open(struct file *file, struct tpm_chip *chip, file->private_data = priv; } +static inline ssize_t tpm_common_read_cleanup (struct file_priv *priv,loff_t *off,ssize_t ret) +{ + *off =0 ; +timer_delete_sync (&priv->user_read_timer); +flush_work (&priv->timeout_work); +return ret; +} +ssize_t tpm_common_read (struct file *file,char __user *buf,size_t size,loff_t *off) {struct file_priv *priv = file->private_data; -ssize_t ret_size =0 ; -int rc; +ssize_t response_length; +u64 offset; -mutex_lock (&priv->buffer_mutex); +if (!size) +return 0 ; -if (priv->response_length) { - priv->response_read = true; +guard (mutex)(&priv->buffer_mutex); + response_length = priv->response_length; - ret_size =min_t (ssize_t, size, priv->response_length); -if (ret_size <=0 ) { - priv->response_length =0 ; - goto out; - } +// Error or nothing to read? +if (response_length <=0 ) +return tpm_common_read_cleanup (priv, off, response_length); - rc =copy_to_user (buf, priv->data_buffer + *off, ret_size); -if (rc) { -memset (priv->data_buffer,0 ,TPM_BUFSIZE ); - priv->response_length =0 ; - ret_size = -EFAULT ; - }else { -memset (priv->data_buffer + *off,0 , ret_size); - priv->response_length -= ret_size; - *off += ret_size; - } - } + offset = *off; -out: -if (!priv->response_length) { - *off =0 ; -timer_delete_sync (&priv->user_read_timer); -flush_work (&priv->timeout_work); - } -mutex_unlock (&priv->buffer_mutex); -return ret_size; +// Have we already read everything? Return EOF +if (offset >= response_length) +return tpm_common_read_cleanup (priv, off,0 ); + +// Do the potentially partial read + size =min_t (size_t, size, response_length - offset); + size -=copy_to_user (buf, priv->data_buffer + offset, size); +if (!size) +return -EFAULT ; + offset += size; + +// Are we all done with the response? +if (offset >= response_length)
drivers/char/tpm/tpm-dev-common.c void tpm_common_open(struct file *file, struct tpm_chip *chip, · line 179
Quoted 10 lines
drivers/char/tpm/tpm-dev-common.c +7
-0+return tpm_common_read_cleanup (priv, off, size); + +// We still have some data left, update the offset +// and be ready to read the rest later - don't do +// the cleanup. + *off = offset; +return size; } ssize_t tpm_common_write(struct file *file, const char __user *buf,
BR, Jarkko