usb: atm: don't use snprintf() for sysfs attrs
Subsystems (6)
PATCH 1/1 usb: atm: don't use snprintf() for sysfs attrs
kernel/cpu.c: don't use snprintf() for sysfs attrs
As per the documentation (Documentation/filesystems/sysfs.rst), snprintf() should not be used for formatting values returned by sysfs.
In all of these cases, sprintf() suffices as we know that the formatted strings will be less than PAGE_SIZE in length.
Issue identified by Coccinelle.
--- drivers/usb/atm/cxacru.c | 27 +++++++++++++-------------- 1 file changed, 13 insertions(+), 14 deletions(-)
drivers/usb/atm/cxacru.c +13 -14
@@ -230,12 +230,12 @@ CXACRU__ATTR_INIT(_name)static ssize_t cxacru_sysfs_showattr_u32 (u32 value,char *buf) { -return snprintf (buf,PAGE_SIZE ,"%u\n" , value); +return sprintf (buf,"%u\n" , value); }static ssize_t cxacru_sysfs_showattr_s8 (s8 value,char *buf) { -return snprintf (buf,PAGE_SIZE ,"%d\n" , value); +return sprintf (buf,"%d\n" , value); }static ssize_t cxacru_sysfs_showattr_dB (s16 value,char *buf)
@@ -255,8 +255,8 @@ static ssize_t cxacru_sysfs_showattr_bool(u32 value, char *buf)static char *str[] = {"no" ,"yes" };if (unlikely (value >=ARRAY_SIZE (str))) -return snprintf (buf,PAGE_SIZE ,"%u\n" , value); -return snprintf (buf,PAGE_SIZE ,"%s\n" , str[value]); +return sprintf (buf,"%u\n" , value); +return sprintf (buf,"%s\n" , str[value]); }static ssize_t cxacru_sysfs_showattr_LINK (u32 value,char *buf)
@@ -264,8 +264,8 @@ static ssize_t cxacru_sysfs_showattr_LINK(u32 value, char *buf)static char *str[] = {NULL ,"not connected" ,"connected" ,"lost" };if (unlikely (value >=ARRAY_SIZE (str) || str[value] ==NULL )) -return snprintf (buf,PAGE_SIZE ,"%u\n" , value); -return snprintf (buf,PAGE_SIZE ,"%s\n" , str[value]); +return sprintf (buf,"%u\n" , value); +return sprintf (buf,"%s\n" , str[value]); }static ssize_t cxacru_sysfs_showattr_LINE (u32 value,char *buf)
@@ -275,8 +275,8 @@ static ssize_t cxacru_sysfs_showattr_LINE(u32 value, char *buf) "waiting", "initialising" };if (unlikely (value >=ARRAY_SIZE (str))) -return snprintf (buf,PAGE_SIZE ,"%u\n" , value); -return snprintf (buf,PAGE_SIZE ,"%s\n" , str[value]); +return sprintf (buf,"%u\n" , value); +return sprintf (buf,"%s\n" , str[value]); }static ssize_t cxacru_sysfs_showattr_MODU (u32 value,char *buf)
@@ -288,8 +288,8 @@ static ssize_t cxacru_sysfs_showattr_MODU(u32 value, char *buf) "ITU-T G.992.2 (G.LITE)" };if (unlikely (value >=ARRAY_SIZE (str))) -return snprintf (buf,PAGE_SIZE ,"%u\n" , value); -return snprintf (buf,PAGE_SIZE ,"%s\n" , str[value]); +return sprintf (buf,"%u\n" , value); +return sprintf (buf,"%s\n" , str[value]); }/*
@@ -309,8 +309,7 @@ static ssize_t mac_address_show(struct device *dev,if (instance ==NULL || instance->usbatm->atm_dev ==NULL )return -ENODEV ; -return snprintf (buf,PAGE_SIZE ,"%pM\n" , - instance->usbatm->atm_dev->esi); +return sprintf (buf,"%pM\n" , instance->usbatm->atm_dev->esi); } static ssize_t adsl_state_show(struct device *dev,
@@ -326,8 +325,8 @@ static ssize_t adsl_state_show(struct device *dev, value = instance->card_info[CXINF_LINE_STARTABLE ];if (unlikely (value >=ARRAY_SIZE (str))) -return snprintf (buf,PAGE_SIZE ,"%u\n" , value); -return snprintf (buf,PAGE_SIZE ,"%s\n" , str[value]); +return sprintf (buf,"%u\n" , value); +return sprintf (buf,"%s\n" , str[value]); } static ssize_t adsl_state_store(struct device *dev,
Signature · 1 line
2.28.0
From: Alex Dewar
Quoted 8 lines
Sent: 24 August 2020 23:23
kernel/cpu.c: don't usesnprintf()for sysfs attrsAs per the documentation (
Documentation/filesystems/sysfs.rst),snprintf()should not be used for formatting values returned by sysfs.In all of these cases,
sprintf()suffices as we know that the formatted strings will be less thanPAGE_SIZEin length.
Hmmmm....
I much prefer to see bounded string ops.
sysfs really ought to be passing through the buffer length. The buffer size should probably be SYSFS_BUF_LEN not PAGE_SIZE (even it happens to typically be the same).
If PAGE_SIZE is big (or small) passing a 4k buffer may be more appropriate than a PAGE_SIZE one.
David
-
Registered Address Lakeside, Bramley Road, Mount Farm, Milton Keynes, MK1 1PT, UK Registration No: 1397386 (Wales)
Quoted 18 lines · David Laight
From: Alex Dewar
Quoted 8 lines
Sent: 24 August 2020 23:23
kernel/cpu.c: don't usesnprintf()for sysfs attrsAs per the documentation (
Documentation/filesystems/sysfs.rst),snprintf()should not be used for formatting values returned by sysfs.In all of these cases,
sprintf()suffices as we know that the formatted strings will be less thanPAGE_SIZEin length.Hmmmm....
I much prefer to see bounded string ops.
sysfs really ought to be passing through the buffer length. The buffer size should probably beSYSFS_BUF_LENnotPAGE_SIZE(even it happens to typically be the same).
IfPAGE_SIZEis big (or small) passing a 4k buffer may be more appropriate than aPAGE_SIZEone.
Quoted 1 line
David
We could use scnprintf() instead I guess. But an expression like:
return sprintf(buf, "%d\n", value);
will never overflow if buf is PAGE_SIZE, right...?
Quoted 5 lines
-
Registered Address Lakeside, Bramley Road, Mount Farm, Milton Keynes, MK1 1PT, UK Registration No: 1397386 (Wales)
From: Alex Dewar
Quoted 20 lines
Sent: 25 August 2020 09:18
Quoted 18 lines · David Laight
From: Alex Dewar
Quoted 8 lines
Sent: 24 August 2020 23:23
kernel/cpu.c: don't usesnprintf()for sysfs attrsAs per the documentation (
Documentation/filesystems/sysfs.rst),snprintf()should not be used for formatting values returned by sysfs.In all of these cases,
sprintf()suffices as we know that the formatted strings will be less thanPAGE_SIZEin length.Hmmmm....
I much prefer to see bounded string ops.
sysfs really ought to be passing through the buffer length. The buffer size should probably beSYSFS_BUF_LENnotPAGE_SIZE(even it happens to typically be the same).
IfPAGE_SIZEis big (or small) passing a 4k buffer may be more appropriate than aPAGE_SIZEone.
Quoted 5 lines
Quoted 1 line
David
We could use
scnprintf()instead I guess. But an expression like:return sprintf(buf, "%d\n", value);will never overflow if buf is
PAGE_SIZE, right...?
Certainly the return value from snprintf() isn't what you want here (it almost never is) - so scnprintf() is much better.
A simple "%d" or "%u" wont overflow, but a "%s" might (even if it is really expected that it shouldn't).
Even a "%*d" can go horribly wrong.
David
-
Registered Address Lakeside, Bramley Road, Mount Farm, Milton Keynes, MK1 1PT, UK Registration No: 1397386 (Wales)
Greg Kroah-Hartman
maintainerQuoted 7 lines · David Laight
From: Alex Dewar
Quoted 6 lines
Sent: 24 August 2020 23:23
kernel/cpu.c: don't usesnprintf()for sysfs attrsAs per the documentation (
Documentation/filesystems/sysfs.rst),snprintf()should not be used for formatting values returned by sysfs.
Quoted 6 lines
Quoted 2 lines
In all of these cases,
sprintf()suffices as we know that the formatted strings will be less thanPAGE_SIZEin length.Hmmmm....
I much prefer to see bounded string ops.
sysfs really ought to be passing through the buffer length.
No.
Quoted 2 lines
The buffer size should probably be
SYSFS_BUF_LENnotPAGE_SIZE(even it happens to typically be the same).
Nope.
Quoted 2 lines
If
PAGE_SIZEis big (or small) passing a 4k buffer may be more appropriate than aPAGE_SIZEone.
Nope, sysfs is supposed to be "one value per file", and the buffer size was specifically not passed in because you should _NEVER_ need to care about it because all you are doing is printing out a single value.
If you really want to print more than just a single value, you should not use sysfs.
So this is designed this way on purpose, you shouldn't have to worry about any of this, and that way, you don't have to "program defensively", it all just works in a simple manner.
thanks,
greg k-h
Quoted 8 lines · Greg Kroah-Hartman
Quoted 7 lines · David Laight
From: Alex Dewar
Quoted 6 lines
Sent: 24 August 2020 23:23
kernel/cpu.c: don't usesnprintf()for sysfs attrsAs per the documentation (
Documentation/filesystems/sysfs.rst),snprintf()should not be used for formatting values returned by sysfs.
Quoted 8 lines
Quoted 6 lines
Quoted 2 lines
In all of these cases,
sprintf()suffices as we know that the formatted strings will be less thanPAGE_SIZEin length.Hmmmm....
I much prefer to see bounded string ops.
sysfs really ought to be passing through the buffer length.No.
It really should, though. I _just_ got burned by this due to having a binattr sysfs reachable through splice[1]. Most sysfs things aren't binattr, but I've always considered this to be a weird fragility in the sysfs implementation.
Quoted 3 lines
So this is designed this way on purpose, you shouldn't have to worry about any of this, and that way, you don't have to "program defensively", it all just works in a simple manner.
Later in this thread there's a suggestion to alter the API to avoid individual calls to sprintf(), which seems like a reasonable first step.
-Kees
Signature · 1 line
Kees Cook
Greg Kroah-Hartman
maintainerQuoted 16 lines · Kees Cook
Quoted 15 lines · Greg Kroah-Hartman
Quoted 13 lines · David Laight
From: Alex Dewar
Quoted 8 lines
Sent: 24 August 2020 23:23
kernel/cpu.c: don't usesnprintf()for sysfs attrsAs per the documentation (
Documentation/filesystems/sysfs.rst),snprintf()should not be used for formatting values returned by sysfs.In all of these cases,
sprintf()suffices as we know that the formatted strings will be less thanPAGE_SIZEin length.Hmmmm....
I much prefer to see bounded string ops.
sysfs really ought to be passing through the buffer length.
Quoted 6 lines
Quoted 1 line
No.
It really should, though. I _just_ got burned by this due to having a binattr sysfs reachable through splice[1]. Most sysfs things aren't binattr, but I've always considered this to be a weird fragility in the sysfs implementation.
binattr attributes do have the buffer size passed to it, for that very reason :)
Quoted 6 lines
Quoted 3 lines
So this is designed this way on purpose, you shouldn't have to worry about any of this, and that way, you don't have to "program defensively", it all just works in a simple manner.
Later in this thread there's a suggestion to alter the API to avoid individual calls to
sprintf(), which seems like a reasonable first step.
I always review any patches submitted, so if someone feels like tackling this, wonderful!
thanks,
greg k-h
Quoted 5 lines · Alex Dewar
kernel/cpu.c: don't usesnprintf()for sysfs attrsAs per the documentation (
Documentation/filesystems/sysfs.rst),snprintf()should not be used for formatting values returned by sysfs.
Sure. But then the security guys come along and send a patch saying "sprintf is evil, always pass a buffer bound". Perhaps with a side of "this code could get copy-pasted, better not promote the use of sprintf more than strictly necessary".
Can we have a sysfs_sprintf() (could just be a macro that does sprintf) to make it clear to the next reader that we know we're in a sysfs show method? It would make auditing uses of sprintf() much easier.
drivers/usb/atm/cxacru.c static ssize_t cxacru_sysfs_showattr_LINE(u32 value, char *buf) · line 280
Quoted 10 lines
static
ssize_tcxacru_sysfs_showattr_LINE(u32 value, char *buf)drivers/usb/atm/cxacru.c +2
-2@@ -275,8 +275,8 @@ static ssize_t cxacru_sysfs_showattr_LINE(u32 value, char *buf) "waiting", "initialising" };if (unlikely (value >=ARRAY_SIZE (str))) -return snprintf (buf,PAGE_SIZE ,"%u\n" , value); -return snprintf (buf,PAGE_SIZE ,"%s\n" , str[value]); +return sprintf (buf,"%u\n" , value); +return sprintf (buf,"%s\n" , str[value]); }
Not this patch in particular, but in some cases the string being printed is not immediately adjacent to the sprintf call, making it rather hard to subsequently verify that yes, that string is certainly reasonably bounded. If you really want to save the few bytes of code that is the practical effect of eliding the PAGE_SIZE argument, how about a sysfs_print_string(buf, str) helper that prints the string and appends a newline; that's another argument saved. And again it would make it obvious to a reader that that particular helper is only to be used in sysfs show methods.
Rasmus
Greg Kroah-Hartman
maintainerQuoted 7 lines · Rasmus Villemoes
Quoted 5 lines · Alex Dewar
kernel/cpu.c: don't usesnprintf()for sysfs attrsAs per the documentation (
Documentation/filesystems/sysfs.rst),snprintf()should not be used for formatting values returned by sysfs.
Quoted 8 lines
Sure. But then the security guys come along and send a patch saying "sprintf is evil, always pass a buffer bound". Perhaps with a side of "this code could get copy-pasted, better not promote the use of sprintf more than strictly necessary".
Can we have a
sysfs_sprintf()(could just be a macro that does sprintf) to make it clear to the next reader that we know we're in a sysfs show method? It would make auditing uses ofsprintf()much easier.
Code churn to keep code checkers quiet for pointless reasons? What could go wrong with that...
It should be pretty obvious to any reader that you are in a sysfs show method, as almost all of them are trivially tiny and obvious. Yes, it doesn't help with those that make blanket statements like "sprintf is evil", but I think that kind of just shows them that they shouldn't be making foolish blanket statements like that :)
Anyway, we've had this for 20 years, if sysfs calls are the only left remaining user of sprintf(), then I'll be glad to consider using a "wrapper" function or macro.
thanks,
greg k-h
Quoted 17 lines · Greg Kroah-Hartman
Quoted 7 lines · Rasmus Villemoes
Quoted 5 lines · Alex Dewar
kernel/cpu.c: don't usesnprintf()for sysfs attrsAs per the documentation (
Documentation/filesystems/sysfs.rst),snprintf()should not be used for formatting values returned by sysfs.Quoted 8 lines
Sure. But then the security guys come along and send a patch saying "sprintf is evil, always pass a buffer bound". Perhaps with a side of "this code could get copy-pasted, better not promote the use of sprintf more than strictly necessary".
Can we have a
sysfs_sprintf()(could just be a macro that does sprintf) to make it clear to the next reader that we know we're in a sysfs show method? It would make auditing uses ofsprintf()much easier.
Quoted 8 lines
Code churn to keep code checkers quiet for pointless reasons? What could go wrong with that...
It should be pretty obvious to any reader that you are in a sysfs show method, as almost all of them are trivially tiny and obvious. Yes, it doesn't help with those that make blanket statements like "sprintf is evil", but I think that kind of just shows them that they shouldn't be making foolish blanket statements like that :)
Perhaps I should have mentioned this in the commit message, but the problem is that snprintf() doesn't return the number of bytes written to the destination buffer, but the number of bytes that *would have been written if they fitted*, which may be more than the bounds specified [1]. So "return snprintf(...)" for sysfs attributes is an antipattern. If you need bounded string ops, scnprintf() is the way to go. Using snprintf() can give a false sense of security, because it isn't necessarily safe.
[1] https://github.com/KSPP/linux/issues/105
Quoted 8 lines
Anyway, we've had this for 20 years, if sysfs calls are the only left remaining user of
sprintf(), then I'll be glad to consider using a "wrapper" function or macro.thanks,
greg k-h
Quoted 9 lines · Alex Dewar
Quoted 8 lines · Greg Kroah-Hartman
Quoted 7 lines · Rasmus Villemoes
Quoted 5 lines · Alex Dewar
kernel/cpu.c: don't usesnprintf()for sysfs attrsAs per the documentation (
Documentation/filesystems/sysfs.rst),snprintf()should not be used for formatting values returned by sysfs.
Quoted 6 lines
Quoted 6 lines
Quoted 3 lines
Can we have a
sysfs_sprintf()(could just be a macro that does sprintf) to make it clear to the next reader that we know we're in a sysfs show method? It would make auditing uses ofsprintf()much easier.Code churn to keep code checkers quiet for pointless reasons? What could go wrong with that...
I did not (mean to) suggest replacing existing sprintf() calls in sysfs show methods. But when changes _are_ being made, such as when replacing snprintf() calls for whatever reasons, can we please not make it harder for people doing manual audits (those are "code checkers" as well, I suppose, but they do tend to only make noise when finding something).
Quoted 2 lines
Quoted 2 lines
It should be pretty obvious to any reader that you are in a sysfs show method, as almost all of them are trivially tiny and obvious.
git grep doesn't immediately show that, not even with a suitable -C argument, as you can't really know the potential callers unless you open the file and see that the function is only assigned as a .show method. And even that can be a pain because it's all hidden behind five levels of magic macros that build identifiers with ##.
Quoted 3 lines
Perhaps I should have mentioned this in the commit message, but the problem is that
snprintf()doesn't return the number of bytes written to the destination buffer,
I'm perfectly well aware of that, TYVM (you may want to 'git log --author Villemoes lib/vsprintf.c').
but the number of bytes that *would have been written if
Quoted 4 lines
they fitted*, which may be more than the bounds specified [1]. So "return snprintf(...)" for sysfs attributes is an antipattern. If you need bounded string ops,
scnprintf()is the way to go. Usingsnprintf()can give a false sense of security, because it isn't necessarily safe.
Huh? This all seems utterly irrelevant WRT a change that replaces PAGE_SIZE by INT_MAX (because that's what sprintf() is going to pretend you passed). You get the same return value.
But I'm not at all concerned about whether one passes the proper buffer size or not in sysfs show methods; with my embedded hat on, I'm all for saving a few bytes of .text here and there. The problem, as far as I'm concerned, is merely that adding sprintf() callers makes it harder to find the problematic sprintf() instances.
Quoted 1 line
Quoted 1 line
Anyway, we've had this for 20 years,
My bad, for a moment I forgot that code and patterns of that vintage cannot have bugs.
Rasmus
Quoted 49 lines · Rasmus Villemoes
Quoted 9 lines · Alex Dewar
Quoted 8 lines · Greg Kroah-Hartman
Quoted 7 lines · Rasmus Villemoes
Quoted 5 lines · Alex Dewar
kernel/cpu.c: don't usesnprintf()for sysfs attrsAs per the documentation (
Documentation/filesystems/sysfs.rst),snprintf()should not be used for formatting values returned by sysfs.Quoted 6 lines
Quoted 6 lines
Quoted 3 lines
Can we have a
sysfs_sprintf()(could just be a macro that does sprintf) to make it clear to the next reader that we know we're in a sysfs show method? It would make auditing uses ofsprintf()much easier.Code churn to keep code checkers quiet for pointless reasons? What could go wrong with that...
I did not (mean to) suggest replacing existing
sprintf()calls in sysfs show methods. But when changes _are_ being made, such as when replacingsnprintf()calls for whatever reasons, can we please not make it harder for people doing manual audits (those are "code checkers" as well, I suppose, but they do tend to only make noise when finding something).Quoted 2 lines
Quoted 2 lines
It should be pretty obvious to any reader that you are in a sysfs show method, as almost all of them are trivially tiny and obvious.
git grep doesn't immediately show that, not even with a suitable -C argument, as you can't really know the potential callers unless you open the file and see that the function is only assigned as a .show method. And even that can be a pain because it's all hidden behind five levels of magic macros that build identifiers with ##.
Quoted 3 lines
Perhaps I should have mentioned this in the commit message, but the problem is that
snprintf()doesn't return the number of bytes written to the destination buffer,I'm perfectly well aware of that, TYVM (you may want to 'git log --author Villemoes
lib/vsprintf.c').but the number of bytes that *would have been written if
Quoted 4 lines
they fitted*, which may be more than the bounds specified [1]. So "return snprintf(...)" for sysfs attributes is an antipattern. If you need bounded string ops,
scnprintf()is the way to go. Usingsnprintf()can give a false sense of security, because it isn't necessarily safe.Huh? This all seems utterly irrelevant WRT a change that replaces
PAGE_SIZEbyINT_MAX(because that's whatsprintf()is going to pretend you passed). You get the same return value.
Quoted 6 lines
But I'm not at all concerned about whether one passes the proper buffer size or not in sysfs show methods; with my embedded hat on, I'm all for saving a few bytes of .text here and there. The problem, as far as I'm concerned, is merely that adding
sprintf()callers makes it harder to find the problematicsprintf()instances.
Apologies, I think I might have expressed myself poorly, being a kernel noob ;-). I know that this is a stylistic change rather than a functional one -- I meant that I was hoping that it would be helpful to get rid of bad uses of snprintf().
I really like your idea of helper methods though :-). If in show() methods we could have something like:
return sysfs_itoa(buf, i); in place of: return sprintf(buf, "%d\n", i);
... then we wouldn't be introducing any new calls to sprintf() as you say, but we'd still be removing a call to snprintf() (which also may be problematic). Plus we'd have type checking on the argument.
For returning strings, we could have a bounded and unbounded variant of the function. As it seems like only single values should be returned via sysfs, if we did things this way then it would only be these string-returning functions which could cause buffer overflow problems and kernel devs could focus their attention accordingly...
What do people think? I'm happy to have a crack, provided this is actually a sensible thing to do! I'm looking for a newbie-level project to get started with.
Thanks for the feedback all,
Alex
Quoted 7 lines
Quoted 2 lines
Quoted 2 lines
Anyway, we've had this for 20 years,
My bad, for a moment I forgot that code and patterns of that vintage cannot have bugs.
Rasmus
Quoted 78 lines · Alex Dewar
Quoted 49 lines · Rasmus Villemoes
Quoted 9 lines · Alex Dewar
Quoted 8 lines · Greg Kroah-Hartman
Quoted 7 lines · Rasmus Villemoes
Quoted 5 lines · Alex Dewar
kernel/cpu.c: don't usesnprintf()for sysfs attrsAs per the documentation (
Documentation/filesystems/sysfs.rst),snprintf()should not be used for formatting values returned by sysfs.Quoted 6 lines
Quoted 6 lines
Quoted 3 lines
Can we have a
sysfs_sprintf()(could just be a macro that does sprintf) to make it clear to the next reader that we know we're in a sysfs show method? It would make auditing uses ofsprintf()much easier.Code churn to keep code checkers quiet for pointless reasons? What could go wrong with that...
I did not (mean to) suggest replacing existing
sprintf()calls in sysfs show methods. But when changes _are_ being made, such as when replacingsnprintf()calls for whatever reasons, can we please not make it harder for people doing manual audits (those are "code checkers" as well, I suppose, but they do tend to only make noise when finding something).Quoted 2 lines
Quoted 2 lines
It should be pretty obvious to any reader that you are in a sysfs show method, as almost all of them are trivially tiny and obvious.
git grep doesn't immediately show that, not even with a suitable -C argument, as you can't really know the potential callers unless you open the file and see that the function is only assigned as a .show method. And even that can be a pain because it's all hidden behind five levels of magic macros that build identifiers with ##.
Quoted 3 lines
Perhaps I should have mentioned this in the commit message, but the problem is that
snprintf()doesn't return the number of bytes written to the destination buffer,I'm perfectly well aware of that, TYVM (you may want to 'git log --author Villemoes
lib/vsprintf.c').but the number of bytes that *would have been written if
Quoted 4 lines
they fitted*, which may be more than the bounds specified [1]. So "return snprintf(...)" for sysfs attributes is an antipattern. If you need bounded string ops,
scnprintf()is the way to go. Usingsnprintf()can give a false sense of security, because it isn't necessarily safe.Huh? This all seems utterly irrelevant WRT a change that replaces
PAGE_SIZEbyINT_MAX(because that's whatsprintf()is going to pretend you passed). You get the same return value.Quoted 6 lines
But I'm not at all concerned about whether one passes the proper buffer size or not in sysfs show methods; with my embedded hat on, I'm all for saving a few bytes of .text here and there. The problem, as far as I'm concerned, is merely that adding
sprintf()callers makes it harder to find the problematicsprintf()instances.Apologies, I think I might have expressed myself poorly, being a kernel noob ;-). I know that this is a stylistic change rather than a functional one -- I meant that I was hoping that it would be helpful to get rid of bad uses of
snprintf().I really like your idea of helper methods though :-). If in
show()methods we could have something like:return sysfs_itoa(buf, i); in place of: return sprintf(buf, "%d\n", i);... then we wouldn't be introducing any new calls to
sprintf()as you say, but we'd still be removing a call tosnprintf()(which also may be problematic). Plus we'd have type checking on the argument.For returning strings, we could have a bounded and unbounded variant of the function. As it seems like only single values should be returned via sysfs, if we did things this way then it would only be these string-returning functions which could cause buffer overflow problems and kernel devs could focus their attention accordingly...
Quoted 3 lines
What do people think? I'm happy to have a crack, provided this is actually a sensible thing to do! I'm looking for a newbie-level project to get started with.
Not a bad idea.
Coccinelle should be able to transform the various .show methods to something sysfs_ prefixed in a fairly automated way.
Quoted 83 lines · Joe Perches
Quoted 78 lines · Alex Dewar
Quoted 49 lines · Rasmus Villemoes
Quoted 9 lines · Alex Dewar
Quoted 8 lines · Greg Kroah-Hartman
Quoted 7 lines · Rasmus Villemoes
Quoted 5 lines · Alex Dewar
kernel/cpu.c: don't usesnprintf()for sysfs attrsAs per the documentation (
Documentation/filesystems/sysfs.rst),snprintf()should not be used for formatting values returned by sysfs.Quoted 6 lines
Quoted 6 lines
Quoted 3 lines
Can we have a
sysfs_sprintf()(could just be a macro that does sprintf) to make it clear to the next reader that we know we're in a sysfs show method? It would make auditing uses ofsprintf()much easier.Code churn to keep code checkers quiet for pointless reasons? What could go wrong with that...
I did not (mean to) suggest replacing existing
sprintf()calls in sysfs show methods. But when changes _are_ being made, such as when replacingsnprintf()calls for whatever reasons, can we please not make it harder for people doing manual audits (those are "code checkers" as well, I suppose, but they do tend to only make noise when finding something).Quoted 2 lines
Quoted 2 lines
It should be pretty obvious to any reader that you are in a sysfs show method, as almost all of them are trivially tiny and obvious.
git grep doesn't immediately show that, not even with a suitable -C argument, as you can't really know the potential callers unless you open the file and see that the function is only assigned as a .show method. And even that can be a pain because it's all hidden behind five levels of magic macros that build identifiers with ##.
Quoted 3 lines
Perhaps I should have mentioned this in the commit message, but the problem is that
snprintf()doesn't return the number of bytes written to the destination buffer,I'm perfectly well aware of that, TYVM (you may want to 'git log --author Villemoes
lib/vsprintf.c').but the number of bytes that *would have been written if
Quoted 4 lines
they fitted*, which may be more than the bounds specified [1]. So "return snprintf(...)" for sysfs attributes is an antipattern. If you need bounded string ops,
scnprintf()is the way to go. Usingsnprintf()can give a false sense of security, because it isn't necessarily safe.Huh? This all seems utterly irrelevant WRT a change that replaces
PAGE_SIZEbyINT_MAX(because that's whatsprintf()is going to pretend you passed). You get the same return value.Quoted 6 lines
But I'm not at all concerned about whether one passes the proper buffer size or not in sysfs show methods; with my embedded hat on, I'm all for saving a few bytes of .text here and there. The problem, as far as I'm concerned, is merely that adding
sprintf()callers makes it harder to find the problematicsprintf()instances.Apologies, I think I might have expressed myself poorly, being a kernel noob ;-). I know that this is a stylistic change rather than a functional one -- I meant that I was hoping that it would be helpful to get rid of bad uses of
snprintf().I really like your idea of helper methods though :-). If in
show()methods we could have something like:return sysfs_itoa(buf, i); in place of: return sprintf(buf, "%d\n", i);... then we wouldn't be introducing any new calls to
sprintf()as you say, but we'd still be removing a call tosnprintf()(which also may be problematic). Plus we'd have type checking on the argument.For returning strings, we could have a bounded and unbounded variant of the function. As it seems like only single values should be returned via sysfs, if we did things this way then it would only be these string-returning functions which could cause buffer overflow problems and kernel devs could focus their attention accordingly...
Quoted 3 lines
What do people think? I'm happy to have a crack, provided this is actually a sensible thing to do! I'm looking for a newbie-level project to get started with.
Quoted 5 lines
Not a bad idea.
Coccinelle should be able to transform the various .show methods to something
sysfs_prefixed in a fairly automated way.
Something like
identifier f;
fresh identifier = "sysfs" ## f;
may be useful. Let me know if further help is needed.
julia
Quoted 9 lines
_______________________________________________
Cocci mailing list
[email protected]
https://systeme.lip6.fr/mailman/listinfo/cocci
Quoted 92 lines · Julia Lawall
Quoted 83 lines · Joe Perches
Quoted 78 lines · Alex Dewar
Quoted 49 lines · Rasmus Villemoes
Quoted 9 lines · Alex Dewar
Quoted 8 lines · Greg Kroah-Hartman
Quoted 7 lines · Rasmus Villemoes
Quoted 5 lines · Alex Dewar
kernel/cpu.c: don't usesnprintf()for sysfs attrsAs per the documentation (
Documentation/filesystems/sysfs.rst),snprintf()should not be used for formatting values returned by sysfs.Quoted 6 lines
Quoted 6 lines
Quoted 3 lines
Can we have a
sysfs_sprintf()(could just be a macro that does sprintf) to make it clear to the next reader that we know we're in a sysfs show method? It would make auditing uses ofsprintf()much easier.Code churn to keep code checkers quiet for pointless reasons? What could go wrong with that...
I did not (mean to) suggest replacing existing
sprintf()calls in sysfs show methods. But when changes _are_ being made, such as when replacingsnprintf()calls for whatever reasons, can we please not make it harder for people doing manual audits (those are "code checkers" as well, I suppose, but they do tend to only make noise when finding something).Quoted 2 lines
Quoted 2 lines
It should be pretty obvious to any reader that you are in a sysfs show method, as almost all of them are trivially tiny and obvious.
git grep doesn't immediately show that, not even with a suitable -C argument, as you can't really know the potential callers unless you open the file and see that the function is only assigned as a .show method. And even that can be a pain because it's all hidden behind five levels of magic macros that build identifiers with ##.
Quoted 3 lines
Perhaps I should have mentioned this in the commit message, but the problem is that
snprintf()doesn't return the number of bytes written to the destination buffer,I'm perfectly well aware of that, TYVM (you may want to 'git log --author Villemoes
lib/vsprintf.c').but the number of bytes that *would have been written if
Quoted 4 lines
they fitted*, which may be more than the bounds specified [1]. So "return snprintf(...)" for sysfs attributes is an antipattern. If you need bounded string ops,
scnprintf()is the way to go. Usingsnprintf()can give a false sense of security, because it isn't necessarily safe.Huh? This all seems utterly irrelevant WRT a change that replaces
PAGE_SIZEbyINT_MAX(because that's whatsprintf()is going to pretend you passed). You get the same return value.Quoted 6 lines
But I'm not at all concerned about whether one passes the proper buffer size or not in sysfs show methods; with my embedded hat on, I'm all for saving a few bytes of .text here and there. The problem, as far as I'm concerned, is merely that adding
sprintf()callers makes it harder to find the problematicsprintf()instances.Apologies, I think I might have expressed myself poorly, being a kernel noob ;-). I know that this is a stylistic change rather than a functional one -- I meant that I was hoping that it would be helpful to get rid of bad uses of
snprintf().I really like your idea of helper methods though :-). If in
show()methods we could have something like:return sysfs_itoa(buf, i); in place of: return sprintf(buf, "%d\n", i);... then we wouldn't be introducing any new calls to
sprintf()as you say, but we'd still be removing a call tosnprintf()(which also may be problematic). Plus we'd have type checking on the argument.For returning strings, we could have a bounded and unbounded variant of the function. As it seems like only single values should be returned via sysfs, if we did things this way then it would only be these string-returning functions which could cause buffer overflow problems and kernel devs could focus their attention accordingly...
Quoted 3 lines
What do people think? I'm happy to have a crack, provided this is actually a sensible thing to do! I'm looking for a newbie-level project to get started with.
Quoted 5 lines
Not a bad idea.
Coccinelle should be able to transform the various .show methods to something
sysfs_prefixed in a fairly automated way.
Quoted 6 lines
Something like
identifier f;
fresh identifier = "sysfs" ## f;may be useful. Let me know if further help is needed.
Perhaps it's a bit more complicated.
Perhaps what's necessary is to find any appropriate .show function and change any use of strcpy/sprintf within those function to some other name.
For instance:
drivers/isdn/mISDN/core.c-static ssize_t name_show(struct device *dev,drivers/isdn/mISDN/core.c- struct device_attribute *attr, char *buf)drivers/isdn/mISDN/core.c-{drivers/isdn/mISDN/core.c: strcpy(buf, dev_name(dev));drivers/isdn/mISDN/core.c- return strlen(buf);drivers/isdn/mISDN/core.c-} drivers/isdn/mISDN/core.c-static DEVICE_ATTR_RO(name);
and macroized uses like:
drivers/base/node.c-#define CACHE_ATTR(name, fmt) \drivers/base/node.c-static ssize_t name##_show(struct device *dev, \
drivers/base/node.c- struct device_attribute *attr, \
drivers/base/node.c- char *buf) \
drivers/base/node.c-{ \drivers/base/node.c- return sprintf(buf, fmt "\n", to_cache_info(dev)->cache_attrs.name);\drivers/base/node.c-} \
drivers/base/node.c:DEVICE_ATTR_RO(name); drivers/base/node.c- drivers/base/node.c-CACHE_ATTR(size, "%llu") drivers/base/node.c-CACHE_ATTR(line_size, "%u") drivers/base/node.c-CACHE_ATTR(indexing, "%u") drivers/base/node.c-CACHE_ATTR(write_policy, "%u")
Quoted 92 lines · Joe Perches
Quoted 91 lines · Julia Lawall
Quoted 88 lines · Joe Perches
Quoted 78 lines · Alex Dewar
Quoted 49 lines · Rasmus Villemoes
Quoted 9 lines · Alex Dewar
Quoted 8 lines · Greg Kroah-Hartman
Quoted 7 lines · Rasmus Villemoes
Quoted 5 lines · Alex Dewar
kernel/cpu.c: don't usesnprintf()for sysfs attrsAs per the documentation (
Documentation/filesystems/sysfs.rst),snprintf()should not be used for formatting values returned by sysfs.Quoted 6 lines
Quoted 6 lines
Quoted 3 lines
Can we have a
sysfs_sprintf()(could just be a macro that does sprintf) to make it clear to the next reader that we know we're in a sysfs show method? It would make auditing uses ofsprintf()much easier.Code churn to keep code checkers quiet for pointless reasons? What could go wrong with that...
I did not (mean to) suggest replacing existing
sprintf()calls in sysfs show methods. But when changes _are_ being made, such as when replacingsnprintf()calls for whatever reasons, can we please not make it harder for people doing manual audits (those are "code checkers" as well, I suppose, but they do tend to only make noise when finding something).Quoted 2 lines
Quoted 2 lines
It should be pretty obvious to any reader that you are in a sysfs show method, as almost all of them are trivially tiny and obvious.
git grep doesn't immediately show that, not even with a suitable -C argument, as you can't really know the potential callers unless you open the file and see that the function is only assigned as a .show method. And even that can be a pain because it's all hidden behind five levels of magic macros that build identifiers with ##.
Quoted 3 lines
Perhaps I should have mentioned this in the commit message, but the problem is that
snprintf()doesn't return the number of bytes written to the destination buffer,I'm perfectly well aware of that, TYVM (you may want to 'git log --author Villemoes
lib/vsprintf.c').but the number of bytes that *would have been written if
Quoted 4 lines
they fitted*, which may be more than the bounds specified [1]. So "return snprintf(...)" for sysfs attributes is an antipattern. If you need bounded string ops,
scnprintf()is the way to go. Usingsnprintf()can give a false sense of security, because it isn't necessarily safe.Huh? This all seems utterly irrelevant WRT a change that replaces
PAGE_SIZEbyINT_MAX(because that's whatsprintf()is going to pretend you passed). You get the same return value.Quoted 6 lines
But I'm not at all concerned about whether one passes the proper buffer size or not in sysfs show methods; with my embedded hat on, I'm all for saving a few bytes of .text here and there. The problem, as far as I'm concerned, is merely that adding
sprintf()callers makes it harder to find the problematicsprintf()instances.Apologies, I think I might have expressed myself poorly, being a kernel noob ;-). I know that this is a stylistic change rather than a functional one -- I meant that I was hoping that it would be helpful to get rid of bad uses of
snprintf().I really like your idea of helper methods though :-). If in
show()methods we could have something like:return sysfs_itoa(buf, i); in place of: return sprintf(buf, "%d\n", i);... then we wouldn't be introducing any new calls to
sprintf()as you say, but we'd still be removing a call tosnprintf()(which also may be problematic). Plus we'd have type checking on the argument.For returning strings, we could have a bounded and unbounded variant of the function. As it seems like only single values should be returned via sysfs, if we did things this way then it would only be these string-returning functions which could cause buffer overflow problems and kernel devs could focus their attention accordingly...
Quoted 3 lines
What do people think? I'm happy to have a crack, provided this is actually a sensible thing to do! I'm looking for a newbie-level project to get started with.
Not a bad idea.
Coccinelle should be able to transform the various .show methods to something
sysfs_prefixed in a fairly automated way.
Quoted 6 lines
Quoted 6 lines
Something like
identifier f;
fresh identifier = "sysfs" ## f;may be useful. Let me know if further help is needed.
cocci syntax eludes me, but I imagine something like:
@@
identifier f_show =~ "^.*_show$";
@@ssize_t f_show(struct kobject *kobj, struct kobj_attribute *attr, char *buf) {
- sprintf
+ kobj_sprintf
(...);
Quoted 124 lines · Joe Perches
Quoted 92 lines · Julia Lawall
Quoted 83 lines · Joe Perches
Quoted 78 lines · Alex Dewar
Quoted 49 lines · Rasmus Villemoes
Quoted 9 lines · Alex Dewar
Quoted 8 lines · Greg Kroah-Hartman
Quoted 7 lines · Rasmus Villemoes
Quoted 5 lines · Alex Dewar
kernel/cpu.c: don't usesnprintf()for sysfs attrsAs per the documentation (
Documentation/filesystems/sysfs.rst),snprintf()should not be used for formatting values returned by sysfs.Quoted 6 lines
Quoted 6 lines
Quoted 3 lines
Can we have a
sysfs_sprintf()(could just be a macro that does sprintf) to make it clear to the next reader that we know we're in a sysfs show method? It would make auditing uses ofsprintf()much easier.Code churn to keep code checkers quiet for pointless reasons? What could go wrong with that...
I did not (mean to) suggest replacing existing
sprintf()calls in sysfs show methods. But when changes _are_ being made, such as when replacingsnprintf()calls for whatever reasons, can we please not make it harder for people doing manual audits (those are "code checkers" as well, I suppose, but they do tend to only make noise when finding something).Quoted 2 lines
Quoted 2 lines
It should be pretty obvious to any reader that you are in a sysfs show method, as almost all of them are trivially tiny and obvious.
git grep doesn't immediately show that, not even with a suitable -C argument, as you can't really know the potential callers unless you open the file and see that the function is only assigned as a .show method. And even that can be a pain because it's all hidden behind five levels of magic macros that build identifiers with ##.
Quoted 3 lines
Perhaps I should have mentioned this in the commit message, but the problem is that
snprintf()doesn't return the number of bytes written to the destination buffer,I'm perfectly well aware of that, TYVM (you may want to 'git log --author Villemoes
lib/vsprintf.c').but the number of bytes that *would have been written if
Quoted 4 lines
they fitted*, which may be more than the bounds specified [1]. So "return snprintf(...)" for sysfs attributes is an antipattern. If you need bounded string ops,
scnprintf()is the way to go. Usingsnprintf()can give a false sense of security, because it isn't necessarily safe.Huh? This all seems utterly irrelevant WRT a change that replaces
PAGE_SIZEbyINT_MAX(because that's whatsprintf()is going to pretend you passed). You get the same return value.Quoted 6 lines
But I'm not at all concerned about whether one passes the proper buffer size or not in sysfs show methods; with my embedded hat on, I'm all for saving a few bytes of .text here and there. The problem, as far as I'm concerned, is merely that adding
sprintf()callers makes it harder to find the problematicsprintf()instances.Apologies, I think I might have expressed myself poorly, being a kernel noob ;-). I know that this is a stylistic change rather than a functional one -- I meant that I was hoping that it would be helpful to get rid of bad uses of
snprintf().I really like your idea of helper methods though :-). If in
show()methods we could have something like:return sysfs_itoa(buf, i); in place of: return sprintf(buf, "%d\n", i);... then we wouldn't be introducing any new calls to
sprintf()as you say, but we'd still be removing a call tosnprintf()(which also may be problematic). Plus we'd have type checking on the argument.For returning strings, we could have a bounded and unbounded variant of the function. As it seems like only single values should be returned via sysfs, if we did things this way then it would only be these string-returning functions which could cause buffer overflow problems and kernel devs could focus their attention accordingly...
Quoted 3 lines
What do people think? I'm happy to have a crack, provided this is actually a sensible thing to do! I'm looking for a newbie-level project to get started with.
Quoted 5 lines
Not a bad idea.
Coccinelle should be able to transform the various .show methods to something
sysfs_prefixed in a fairly automated way.Quoted 6 lines
Something like
identifier f;
fresh identifier = "sysfs" ## f;may be useful. Let me know if further help is needed.
Perhaps it's a bit more complicated.
Perhaps what's necessary is to find any appropriate .show function and change any use of strcpy/sprintf within those function to some other name.
For instance:
drivers/isdn/mISDN/core.c-staticssize_tname_show(struct device *dev,drivers/isdn/mISDN/core.c-structdevice_attribute*attr, char *buf)drivers/isdn/mISDN/core.c-{drivers/isdn/mISDN/core.c:strcpy(buf, dev_name(dev));drivers/isdn/mISDN/core.c-return strlen(buf);drivers/isdn/mISDN/core.c-}drivers/isdn/mISDN/core.c-staticDEVICE_ATTR_RO(name);and macroized uses like:
drivers/base/node.c-#define
CACHE_ATTR(name, fmt)\drivers/base/node.c-staticssize_tname##_show(struct device *dev, \drivers/base/node.c- struct device_attribute *attr, \ drivers/base/node.c- char *buf) \ drivers/base/node.c-{ \
Quoted 8 lines
drivers/base/node.c-returnsprintf(buf, fmt "\n", to_cache_info(dev)->cache_attrs.name);\drivers/base/node.c-} \
drivers/base/node.c:DEVICE_ATTR_RO(name);drivers/base/node.c-drivers/base/node.c-CACHE_ATTR(size, "%llu") drivers/base/node.c-CACHE_ATTR(line_size, "%u") drivers/base/node.c-CACHE_ATTR(indexing, "%u") drivers/base/node.c-CACHE_ATTR(write_policy, "%u")
Coccinelle would fail on these.
julia
From: Joe Perches
Quoted 1 line
Sent: 27 August 2020 21:30
...
Quoted 7 lines
Perhaps what's necessary is to find any appropriate .show function and change any use of strcpy/sprintf within those function to some other name.
For instance:
Quoted 7 lines
drivers/isdn/mISDN/core.c-staticssize_tname_show(struct device *dev,drivers/isdn/mISDN/core.c-structdevice_attribute*attr, char *buf)drivers/isdn/mISDN/core.c-{drivers/isdn/mISDN/core.c:strcpy(buf, dev_name(dev));drivers/isdn/mISDN/core.c-return strlen(buf);drivers/isdn/mISDN/core.c-}drivers/isdn/mISDN/core.c-staticDEVICE_ATTR_RO(name);
That form ends up calculating the string length twice. Better would be:
len = strlen(msg); memcpy(buf, msg, len); return len; David
-
Registered Address Lakeside, Bramley Road, Mount Farm, Milton Keynes, MK1 1PT, UK Registration No: 1397386 (Wales)
Quoted 18 lines · David Laight
From: Joe Perches
Quoted 1 line
Sent: 27 August 2020 21:30
...
Quoted 7 lines
Perhaps what's necessary is to find any appropriate .show function and change any use of strcpy/sprintf within those function to some other name.
For instance:
Quoted 7 lines
drivers/isdn/mISDN/core.c-staticssize_tname_show(struct device *dev,drivers/isdn/mISDN/core.c-structdevice_attribute*attr, char *buf)drivers/isdn/mISDN/core.c-{drivers/isdn/mISDN/core.c:strcpy(buf, dev_name(dev));drivers/isdn/mISDN/core.c-return strlen(buf);drivers/isdn/mISDN/core.c-}drivers/isdn/mISDN/core.c-staticDEVICE_ATTR_RO(name);
Quoted 5 lines
That form ends up calculating the string length twice. Better would be:
len = strlen(msg); memcpy(buf, msg, len); return len;
or given clang's requirement for stpcpy
return stpcpy(buf, dev_name(dev)) - buf;
(I do not advocate for this ;)
Quoted 25 lines · Joe Perches
Quoted 18 lines · David Laight
From: Joe Perches
Quoted 1 line
Sent: 27 August 2020 21:30
...
Quoted 7 lines
Perhaps what's necessary is to find any appropriate .show function and change any use of strcpy/sprintf within those function to some other name.
For instance:
Quoted 7 lines
drivers/isdn/mISDN/core.c-staticssize_tname_show(struct device *dev,drivers/isdn/mISDN/core.c-structdevice_attribute*attr, char *buf)drivers/isdn/mISDN/core.c-{drivers/isdn/mISDN/core.c:strcpy(buf, dev_name(dev));drivers/isdn/mISDN/core.c-return strlen(buf);drivers/isdn/mISDN/core.c-}drivers/isdn/mISDN/core.c-staticDEVICE_ATTR_RO(name);Quoted 5 lines
That form ends up calculating the string length twice. Better would be:
len = strlen(msg); memcpy(buf, msg, len); return len;
Quoted 5 lines
or given clang's requirement for stpcpy
return stpcpy(buf, dev_name(dev)) - buf;(I do not advocate for this ;)
Heh. And humans aren't allowed to use stpcpy() in the kernel. :)
Signature · 1 line
Kees Cook
Hi all,
Quoted 6 lines · Julia Lawall
Quoted 2 lines · Joe Perches
Quoted 1 line · Alex Dewar
On Thu, Aug 27, 2020 at 03:41:06PM +0200, Rasmus Villemoes wrote:
Quoted 8 lines
Quoted 8 lines
Quoted 8 lines
Quoted 8 lines · Alex Dewar
Quoted 7 lines · Greg Kroah-Hartman
Quoted 6 lines · Rasmus Villemoes
Quoted 5 lines · Alex Dewar
Quoted 4 lines
kernel/cpu.c: don't usesnprintf()for sysfs attrsAs per the documentation (
Documentation/filesystems/sysfs.rst),snprintf()should not be used for formatting values returned by sysfs.
Just FYI, I've send an addition to the device_attr_show.cocci script[1] to turn simple cases of snprintf (e.g. "%i") to sprintf. Looks like many developers would like it more than changing snprintf to scnprintf. As for me, I don't like the idea of automated altering of the original logic from bounded snprint to unbouded one with sprintf.
[1] https://lkml.org/lkml/2020/8/13/786
Regarding current device_attr_show.cocci implementation, it detects the functions by declaration:ssize_t any_name(struct device *dev, struct device_attribute *attr, char *buf)
and I limited the check to:
"return snprintf"
pattern because there are already too many warnings.
Actually, it looks more correct to check for:ssize_t show(struct device *dev, struct device_attribute *attr, char *buf)
{
<...
* snprintf@p(...);
...>
}This pattern should also highlight the snprintf calls there we save returned value in a var, e.g.:
ret += snprintf(...);
...
ret += snprintf(...);
...
ret += snprintf(...);
return ret;
Quoted 7 lines
Something like
identifier f;
fresh identifier = "sysfs" ## f;may be useful. Let me know if further help is needed.
Initially, I wrote the rule to search for DEVICE_ATTR(..., ..., func_name, ...) functions. However, it looks like matching function prototype is enough. At least, I failed to find false positives. I rejected the initial DEVICE_ATTR() searching because I thought that it's impossible to handle DEVICE_ATTR_RO()/DEVICE_ATTR_RW() macroses with coccinelle as they "generate" function names internally with "##". "fresh identifier" should really help here, but now I doubt it's required in device_attr_show.cocci, function prototype is enough.
Thanks,
Denis
Quoted 54 lines · Denis Efremov
Hi all,
Quoted 6 lines · Julia Lawall
Quoted 2 lines · Joe Perches
Quoted 1 line · Alex Dewar
On Thu, Aug 27, 2020 at 03:41:06PM +0200, Rasmus Villemoes wrote:
Quoted 8 lines
Quoted 8 lines
Quoted 8 lines
Quoted 8 lines · Alex Dewar
Quoted 7 lines · Greg Kroah-Hartman
Quoted 6 lines · Rasmus Villemoes
Quoted 5 lines · Alex Dewar
Quoted 4 lines
kernel/cpu.c: don't usesnprintf()for sysfs attrsAs per the documentation (
Documentation/filesystems/sysfs.rst),snprintf()should not be used for formatting values returned by sysfs.Just FYI, I've send an addition to the
device_attr_show.cocciscript[1] to turn simple cases of snprintf (e.g. "%i") to sprintf. Looks like many developers would like it more than changing snprintf to scnprintf. As for me, I don't like the idea of automated altering of the original logic from bounded snprint to unbouded one with sprintf.[1] https://lkml.org/lkml/2020/8/13/786
Regarding current
device_attr_show.cocciimplementation, it detects the functions by declaration:ssize_tany_name(struct device *dev, struct device_attribute *attr, char *buf)and I limited the check to:
"return snprintf"
pattern because there are already too many warnings.Actually, it looks more correct to check for:
ssize_tshow(struct device *dev, struct device_attribute *attr, char *buf){ <... * snprintf@p(...); ...> }This pattern should also highlight the snprintf calls there we save returned value in a var, e.g.:
ret += snprintf(...);
...
ret += snprintf(...);
...
ret += snprintf(...);return ret;
Quoted 1 line
Quoted 8 lines
Quoted 6 lines
Something like
identifier f;
fresh identifier = "sysfs" ## f;may be useful. Let me know if further help is needed.
Initially, I wrote the rule to search for
DEVICE_ATTR(..., ..., func_name, ...)
This is what I would have expected.
Quoted 6 lines
functions. However, it looks like matching function prototype is enough. At least, I failed to find false positives. I rejected the initial
DEVICE_ATTR()searching because I thought that it's impossible to handle DEVICE_ATTR_RO()/DEVICE_ATTR_RW() macroses with coccinelle as they "generate" function names internally with "##". "fresh identifier" should really help here, but now I doubt it's required indevice_attr_show.cocci, function prototype is enough.
It's true that it is probably unique enough.
julia
Quoted 1 line · Julia Lawall
On Fri, 28 Aug 2020, Denis Efremov wrote:
[]
Quoted 38 lines
Regarding current
device_attr_show.cocciimplementation, it detects the functionsQuoted 26 lines
by declaration:
ssize_tany_name(struct device *dev, struct device_attribute *attr, char *buf)and I limited the check to:
"return snprintf"
pattern because there are already too many warnings.Actually, it looks more correct to check for:
ssize_tshow(struct device *dev, struct device_attribute *attr, char *buf){ <... * snprintf@p(...); ...> }This pattern should also highlight the snprintf calls there we save returned value in a var, e.g.:
ret += snprintf(...);
...
ret += snprintf(...);
...
ret += snprintf(...);return ret;
Quoted 8 lines
Quoted 6 lines
Something like
identifier f;
fresh identifier = "sysfs" ## f;may be useful. Let me know if further help is needed.
Initially, I wrote the rule to search for
DEVICE_ATTR(..., ..., func_name, ...)This is what I would have expected.
Quoted 8 lines
Quoted 6 lines
functions. However, it looks like matching function prototype is enough. At least, I failed to find false positives. I rejected the initial
DEVICE_ATTR()searching because I thought that it's impossible to handle DEVICE_ATTR_RO()/DEVICE_ATTR_RW() macroses with coccinelle as they "generate" function names internally with "##". "fresh identifier" should really help here, but now I doubt it's required indevice_attr_show.cocci, function prototype is enough.It's true that it is probably unique enough.
I tried:
@@
identifier f_show =~ "^.*_show$";
identifier dev, attr, buf;
const char *chr;
@@ssize_t f_show(struct device *dev, struct device_attribute *attr, char *buf)
{
<...
(
- sprintf
+ sysfs_sprintf
(...);
|
- snprintf(buf, PAGE_SIZE,
+ sysfs_sprintf(buf,
...);
|
- scnprintf(buf, PAGE_SIZE,
+ sysfs_sprintf(buf,
...);
|
strcpy(buf, chr);
sysfs_strcpy(buf, chr);
)
...>
}which finds direct statements without an assign
but that doesn't find
arch/arm/common/dmabounce.c:static ssize_t dmabounce_show(struct device *dev, struct device_attribute *attr, char *buf) arch/arm/common/dmabounce.c-{arch/arm/common/dmabounce.c- struct dmabounce_device_info *device_info = dev->archdata.dmabounce;arch/arm/common/dmabounce.c- return sprintf(buf, "%lu %lu %lu %lu %lu %lu\n",
arch/arm/common/dmabounce.c- device_info->small.allocs, arch/arm/common/dmabounce.c- device_info->large.allocs, arch/arm/common/dmabounce.c- device_info->total_allocs - device_info->small.allocs - arch/arm/common/dmabounce.c- device_info->large.allocs, arch/arm/common/dmabounce.c- device_info->total_allocs, arch/arm/common/dmabounce.c- device_info->map_op_count, arch/arm/common/dmabounce.c- device_info->bounce_count);
arch/arm/common/dmabounce.c-}
Quoted 4 lines
I tried:
@@
identifierf_show=~ "^.*_show$";
This will miss this kind of functions:
./drivers/gpu/drm/amd/amdgpu/amdgpu_atombios.c:1953:static DEVICE_ATTR(vbios_version, 0444, amdgpu_atombios_get_vbios_version, ./drivers/gpu/drm/amd/amdgpu/df_v3_6.c:266:static DEVICE_ATTR(df_cntr_avail, S_IRUGO, df_v3_6_get_df_cntr_avail, NULL); ./drivers/input/touchscreen/melfas_mip4.c:1348:static DEVICE_ATTR(fw_version, S_IRUGO, mip4_sysfs_read_fw_version, NULL); ./drivers/input/touchscreen/melfas_mip4.c:1373:static DEVICE_ATTR(hw_version, S_IRUGO, mip4_sysfs_read_hw_version, NULL); ./drivers/input/touchscreen/melfas_mip4.c:1392:static DEVICE_ATTR(product_id, S_IRUGO, mip4_sysfs_read_product_id, NULL);
...
Quoted 33 lines
identifier dev, attr, buf;
const char *chr;
@@ssize_tf_show(struct device *dev, struct device_attribute *attr, char *buf){ <...(
(quoted diff) +1
-1- sprintf + sysfs_sprintf(...);|
(quoted diff) +1
-1- snprintf(buf, PAGE_SIZE, + sysfs_sprintf(buf,...);|
(quoted diff) +1
-1- scnprintf(buf, PAGE_SIZE, + sysfs_sprintf(buf,...); | strcpy(buf, chr); sysfs_strcpy(buf, chr); ) ...> }which finds direct statements without an assign
but that doesn't findarch/arm/common/dmabounce.c:static
ssize_tdmabounce_show(struct device *dev, struct device_attribute *attr, char *buf)arch/arm/common/dmabounce.c-{arch/arm/common/dmabounce.c-structdmabounce_device_info*device_info=dev->archdata.dmabounce;arch/arm/common/dmabounce.c-return sprintf(buf, "%lu %lu %lu %lu %lu %lu\n",
Quoted 9 lines
arch/arm/common/dmabounce.c- device_info->small.allocs, arch/arm/common/dmabounce.c- device_info->large.allocs, arch/arm/common/dmabounce.c- device_info->total_allocs - device_info->small.allocs - arch/arm/common/dmabounce.c- device_info->large.allocs, arch/arm/common/dmabounce.c- device_info->total_allocs, arch/arm/common/dmabounce.c- device_info->map_op_count, arch/arm/common/dmabounce.c- device_info->bounce_count);
arch/arm/common/dmabounce.c-}
This will match it (the difference is in the ';'):
@@
identifier f_show =~ "^.*_show$"; identifier dev, attr, buf;
@@
ssize_t f_show(struct device *dev, struct device_attribute *attr, char *buf)
{
<... - sprintf + sysfs_sprintf (...) ...> }
Regards,
Denis
Quoted 1 line · Denis Efremov
Quoted 1 line
This will match it (the difference is in the ';'):
thanks.
Quoted 5 lines · Denis Efremov
Just FYI, I've send an addition to the
device_attr_show.cocciscript[1] to turn simple cases of snprintf (e.g. "%i") to sprintf. Looks like many developers would like it more than changing snprintf to scnprintf. As for me, I don't like the idea of automated altering of the original logic from bounded snprint to unbouded one with sprintf.
Agreed. This just makes me cringe. If the API design declares that when a show() callback starts, buf has been allocated with PAGE_SIZE bytes, then that's how the logic should proceed, and it should be using scnprintf...
show(...) {
size_t remaining = PAGE_SIZE;
...
remaining -= scnprintf(buf, remaining, "fmt", var args ...);
remaining -= scnprintf(buf, remaining, "fmt", var args ...);
remaining -= scnprintf(buf, remaining, "fmt", var args ...);
return PAGE_SIZE - remaining;
}Signature · 1 line
Kees Cook
Quoted 12 lines · Kees Cook
Quoted 5 lines · Denis Efremov
Just FYI, I've send an addition to the
device_attr_show.cocciscript[1] to turn simple cases of snprintf (e.g. "%i") to sprintf. Looks like many developers would like it more than changing snprintf to scnprintf. As for me, I don't like the idea of automated altering of the original logic from bounded snprint to unbouded one with sprintf.Agreed. This just makes me cringe. If the API design declares that when a
show()callback starts, buf has been allocated withPAGE_SIZEbytes, then that's how the logic should proceed, and it should be using scnprintf...
Quoted 10 lines
show(...) {
size_t remaining = PAGE_SIZE;
...
remaining -= scnprintf(buf, remaining, "fmt", var args ...);
remaining -= scnprintf(buf, remaining, "fmt", var args ...);
remaining -= scnprintf(buf, remaining, "fmt", var args ...);
return PAGE_SIZE - remaining;
}It seems likely that coccinelle could do those transform with any of sprintf/snprintf/scnprint too.
Though my bikeshed would use a single function and have that function know the maximum output size
Something like:
With single line use:
return sysfs_emit(buf, buf, fmt, ...) - buf;
and multi-line use:
char *pos = buf; pos = sysfs_emit(buf, pos, fmt1, ...); pos = sysfs_emit(buf, pos, fmt2, ...); ... return pos - buf;
Quoted 21 lines · Joe Perches
Quoted 20 lines · Kees Cook
Quoted 5 lines · Denis Efremov
Just FYI, I've send an addition to the
device_attr_show.cocciscript[1] to turn simple cases of snprintf (e.g. "%i") to sprintf. Looks like many developers would like it more than changing snprintf to scnprintf. As for me, I don't like the idea of automated altering of the original logic from bounded snprint to unbouded one with sprintf.Agreed. This just makes me cringe. If the API design declares that when a
show()callback starts, buf has been allocated withPAGE_SIZEbytes, then that's how the logic should proceed, and it should be using scnprintf...show(...) { size_t remaining = PAGE_SIZE; ... remaining -= scnprintf(buf, remaining, "fmt", var args ...); remaining -= scnprintf(buf, remaining, "fmt", var args ...); remaining -= scnprintf(buf, remaining, "fmt", var args ...);
Quoted 8 lines
Quoted 2 lines
return PAGE_SIZE - remaining; }It seems likely that coccinelle could do those transform with any of sprintf/snprintf/scnprint too.
Though my bikeshed would use a single function and have that function know the maximum output size
Perhaps something like the below with a sample conversion that uses single and multiple sysfs_emit uses.
I believe coccinelle can _mostly_ automated this.
--- fs/sysfs/file.c | 30 ++++++++++++++++++++++++++++++ include/linux/sysfs.h | 8 ++++++++ kernel/power/main.c | 49 ++++++++++++++++++++++++++----------------------- 3 files changed, 64 insertions(+), 23 deletions(-)
fs/sysfs/file.c +30 -0
@@ -707,3 +707,33 @@ int sysfs_change_owner(struct kobject *kobj, kuid_t kuid, kgid_t kgid)return 0 ; }EXPORT_SYMBOL_GPL (sysfs_change_owner); + +/** +* sysfs_emit - scnprintf equivalent, aware of PAGE_SIZE buffer. +* @buf: start of PAGE_SIZE buffer. +* @pos: current position in buffer +* (pos - buf) must always be < PAGE_SIZE +* @fmt: format +* @...: arguments to format +* +* +* Returns number of characters written at pos. +*/ +int sysfs_emit (char *buf,char *pos,const char *fmt, ...) +{ +int len; +va_list args; + +WARN (pos < buf,"pos < buf\n" ); +WARN (pos - buf >=PAGE_SIZE ,"pos >= PAGE_SIZE (%tu > %lu)\n" , + pos - buf,PAGE_SIZE ); +if (pos < buf || pos - buf >=PAGE_SIZE ) +return 0 ; + +va_start (args, fmt); + len =vscnprintf (pos,PAGE_SIZE - (pos - buf), fmt, args); +va_end (args); + +return len; +} +EXPORT_SYMBOL_GPL (sysfs_emit);
include/linux/sysfs.h +8 -0
@@ -329,6 +329,8 @@ int sysfs_groups_change_owner(struct kobject *kobj,int sysfs_group_change_owner (struct kobject *kobj,const struct attribute_group *groups,kuid_t kuid,kgid_t kgid); +__printf(3, 4) +int sysfs_emit (char *buf,char *pos,const char *fmt, ...);#else /* CONFIG_SYSFS */
@@ -576,6 +578,12 @@ static inline int sysfs_group_change_owner(struct kobject *kobj,return 0 ; } +__printf(3, 4) +static inline int sysfs_emit(char *buf, char *pos, const char *fmt, ...) +{ +return 0 ; +} +#endif /* CONFIG_SYSFS */ static inline int __must_check sysfs_create_file(struct kobject *kobj,
kernel/power/main.c +26 -23
144 lines not on this page · raw message
Quoted 2 lines · Joe Perches
Perhaps something like the below with a sample conversion that uses single and multiple
sysfs_emituses.
On quick review, I like it. :)
fs/sysfs/file.c int sysfs_change_owner(struct kobject *kobj, kuid_t kuid, kgid_t kgid) · line 731
Quoted 11 lines
[...]
fs/sysfs/file.c +10
-0+int sysfs_emit (char *buf,char *pos,const char *fmt, ...) +{ +int len; +va_list args; + +WARN (pos < buf,"pos < buf\n" ); +WARN (pos - buf >=PAGE_SIZE ,"pos >= PAGE_SIZE (%tu > %lu)\n" , + pos - buf,PAGE_SIZE ); +if (pos < buf || pos - buf >=PAGE_SIZE ) +return 0 ;
This can be:
if (WARN(pos < buf, "pos < buf\n") || WARN(pos - buf >= PAGE_SIZE, "pos >= PAGE_SIZE (%tu > %lu)\n", pos - buf, PAGE_SIZE)) return 0;
Signature · 1 line
Kees Cook
Quoted 20 lines · Kees Cook
Quoted 2 lines · Joe Perches
Perhaps something like the below with a sample conversion that uses single and multiple
sysfs_emituses.On quick review, I like it. :)
fs/sysfs/file.c int sysfs_change_owner(struct kobject *kobj, kuid_t kuid, kgid_t kgid) · line 731
Quoted 11 lines
[...]
fs/sysfs/file.c +10
-0+int sysfs_emit (char *buf,char *pos,const char *fmt, ...) +{ +int len; +va_list args; + +WARN (pos < buf,"pos < buf\n" ); +WARN (pos - buf >=PAGE_SIZE ,"pos >= PAGE_SIZE (%tu > %lu)\n" , + pos - buf,PAGE_SIZE ); +if (pos < buf || pos - buf >=PAGE_SIZE ) +return 0 ;This can be:
Quoted 4 lines
if (WARN(pos < buf, "pos < buf\n") || WARN(pos - buf >= PAGE_SIZE, "pos >= PAGE_SIZE (%tu > %lu)\n", pos - buf, PAGE_SIZE)) return 0;
I had some vague recollection that WARN could be compiled away to nothing somehow. True or false?
If false, sure, of course, it'd be faster too.
Quoted 26 lines · Joe Perches
Quoted 20 lines · Kees Cook
Quoted 2 lines · Joe Perches
Perhaps something like the below with a sample conversion that uses single and multiple
sysfs_emituses.On quick review, I like it. :)
fs/sysfs/file.c int sysfs_change_owner(struct kobject *kobj, kuid_t kuid, kgid_t kgid) · line 731
Quoted 11 lines
[...]
fs/sysfs/file.c +10
-0+int sysfs_emit (char *buf,char *pos,const char *fmt, ...) +{ +int len; +va_list args; + +WARN (pos < buf,"pos < buf\n" ); +WARN (pos - buf >=PAGE_SIZE ,"pos >= PAGE_SIZE (%tu > %lu)\n" , + pos - buf,PAGE_SIZE ); +if (pos < buf || pos - buf >=PAGE_SIZE ) +return 0 ;This can be:
Quoted 4 lines
if (WARN(pos < buf, "pos < buf\n") || WARN(pos - buf >= PAGE_SIZE, "pos >= PAGE_SIZE (%tu > %lu)\n", pos - buf, PAGE_SIZE)) return 0;
Quoted 4 lines
I have some vague recollection that WARN could be compiled away to nothing somehow. True or false?
If false, sure, of course, it'd be faster too.
I can't find an instance where WARN doesn't return the condition.
And likely even faster would be to just show "invalid pos" instead of specific messages.
if (WARN(pos < buf || (pos - buf) >= PAGE_SIZE, "Invalid pos\n"); return 0;
or maybe use WARN_ONCE or no WARN at all.
From: Kees Cook
Quoted 1 line
Sent: 27 August 2020 23:21
...
Quoted 6 lines
Agreed. This just makes me cringe. If the API design declares that when a
show()callback starts, buf has been allocated withPAGE_SIZEbytes, then that's how the logic should proceed, and it should be using scnprintf...
Quoted 7 lines
show(...) {
size_t remaining = PAGE_SIZE;
...
remaining -= scnprintf(buf, remaining, "fmt", var args ...);
remaining -= scnprintf(buf, remaining, "fmt", var args ...);
remaining -= scnprintf(buf, remaining, "fmt", var args ...);Not quite what you had in mind, maybe:
char *end = buf + PAGE_SIZE; buf += scnprintf(buf, end - buf, ...); return PAGE_SIZE - (end - buf); David
-
Registered Address Lakeside, Bramley Road, Mount Farm, Milton Keynes, MK1 1PT, UK Registration No: 1397386 (Wales)
From: Joe Perches
Quoted 8 lines
Sent: 27 August 2020 17:59
To: Alex Dewar <[email protected]>; Rasmus Villemoes <[email protected]>; cocci <[email protected]>
Cc: Greg Kroah-Hartman <[email protected]>; Kees Cook <[email protected]>; Gustavo A. R. Silva <[email protected]>; [email protected]; [email protected]; [email protected]
Subject: Re: [PATCH] usb: atm: don't usesnprintf()for sysfs attrs
Quoted 82 lines
Quoted 81 lines · Alex Dewar
Quoted 49 lines · Rasmus Villemoes
Quoted 9 lines · Alex Dewar
Quoted 8 lines · Greg Kroah-Hartman
Quoted 7 lines · Rasmus Villemoes
Quoted 5 lines · Alex Dewar
kernel/cpu.c: don't usesnprintf()for sysfs attrsAs per the documentation (
Documentation/filesystems/sysfs.rst),snprintf()should not be used for formatting values returned by sysfs.Quoted 6 lines
Quoted 6 lines
Quoted 3 lines
Can we have a
sysfs_sprintf()(could just be a macro that does sprintf) to make it clear to the next reader that we know we're in a sysfs show method? It would make auditing uses ofsprintf()much easier.Code churn to keep code checkers quiet for pointless reasons? What could go wrong with that...
I did not (mean to) suggest replacing existing
sprintf()calls in sysfs show methods. But when changes _are_ being made, such as when replacingsnprintf()calls for whatever reasons, can we please not make it harder for people doing manual audits (those are "code checkers" as well, I suppose, but they do tend to only make noise when finding something).Quoted 2 lines
Quoted 2 lines
It should be pretty obvious to any reader that you are in a sysfs show method, as almost all of them are trivially tiny and obvious.
git grep doesn't immediately show that, not even with a suitable -C argument, as you can't really know the potential callers unless you open the file and see that the function is only assigned as a .show method. And even that can be a pain because it's all hidden behind five levels of magic macros that build identifiers with ##.
Quoted 3 lines
Perhaps I should have mentioned this in the commit message, but the problem is that
snprintf()doesn't return the number of bytes written to the destination buffer,I'm perfectly well aware of that, TYVM (you may want to 'git log --author Villemoes
lib/vsprintf.c').but the number of bytes that *would have been written if
Quoted 4 lines
they fitted*, which may be more than the bounds specified [1]. So "return snprintf(...)" for sysfs attributes is an antipattern. If you need bounded string ops,
scnprintf()is the way to go. Usingsnprintf()can give a false sense of security, because it isn't necessarily safe.Huh? This all seems utterly irrelevant WRT a change that replaces
PAGE_SIZEbyINT_MAX(because that's whatsprintf()is going to pretend you passed). You get the same return value.Quoted 6 lines
But I'm not at all concerned about whether one passes the proper buffer size or not in sysfs show methods; with my embedded hat on, I'm all for saving a few bytes of .text here and there. The problem, as far as I'm concerned, is merely that adding
sprintf()callers makes it harder to find the problematicsprintf()instances.Apologies, I think I might have expressed myself poorly, being a kernel noob ;-). I know that this is a stylistic change rather than a functional one -- I meant that I was hoping that it would be helpful to get rid of bad uses of
snprintf().I really like your idea of helper methods though :-). If in
show()methods we could have something like:return sysfs_itoa(buf, i); in place of: return sprintf(buf, "%d\n", i);... then we wouldn't be introducing any new calls to
sprintf()as you say, but we'd still be removing a call tosnprintf()(which also may be problematic). Plus we'd have type checking on the argument.For returning strings, we could have a bounded and unbounded variant of the function. As it seems like only single values should be returned via sysfs, if we did things this way then it would only be these string-returning functions which could cause buffer overflow problems and kernel devs could focus their attention accordingly...
What do people think? I'm happy to have a crack, provided this is actually a sensible thing to do! I'm looking for a newbie-level project to get started with.
The problem with that idea is that is the code needs to merge the output of two values or split an integer as nnn.nn then it needs to do something different from the 'normal' code.
If the buffer is always PAGE_SIZE the why not embed it in a structure.
The generated code will be the same, but it will be absolutely explicit that the size is PAGE_SIZE if the code filling in the buffer decides it needs to check.
David
-
Registered Address Lakeside, Bramley Road, Mount Farm, Milton Keynes, MK1 1PT, UK Registration No: 1397386 (Wales)