[Info-vax] ChatGPT solved it for me, again...

Johnny Billquist bqt at softjar.se
Mon Feb 20 05:08:27 EST 2023


On 2023-02-17 14:55, Simon Clubley wrote:
> On 2023-02-17, Arne Vajhøj <arne at vajhoej.dk> wrote:
>> On 2/17/2023 8:20 AM, Simon Clubley wrote:
>>> On 2023-02-17, Slo <slovuj at gmail.com> wrote:
>>>> Sorry Arne, I don't trust your coding skills and an ancient language :-)
>>>
>>> That ancient language is more secure than C. :-)
>>>
>>>> Me: Convert this code to C
>>>> ============================
>>>> #include <stdio.h>
>>>> #include <stdlib.h>
>>>> #include <string.h>
>>>> #include <time.h>
>>>> int get_wattage(char *sys) {
>>>>       return (rand() % 20) * 50 + 200;
>>>> }
>>>> int main() {
>>>>       char sys1[256], sys2[256];
>>>>       int watt1, watt2;
>>>>       srand(time(NULL));
>>>>       printf("Utility to check power supply compatibility.\n");
>>>>       printf("Enter name of system #1: ");
>>>>       fgets(sys1, 256, stdin);
>>>>       printf("Enter name of system #2: ");
>>>>       fgets(sys2, 256, stdin);
>>>>       sys1[strcspn(sys1, "\n")] = '\0';
>>>>       sys2[strcspn(sys2, "\n")] = '\0';
>>>
>>> OUCH! OUCH! OUCH!!!!!
>>>
>>> fgets() is not guaranteed to return a newline character.
>>
>> And?
>>
> 
> Take a closer look Arne.
> 
> That code will continue searching memory for a byte with the value of
> a newline character and will then modify the first such byte it finds.
> 
> In other words, an out of bounds write vulnerability that may be
> exploitable in some circumstances when the code is part of a larger
> program.
> 
> Even worse, the generated code _appears_ to work ok for normal inputs.

No. You are incorrect. fgets() will put into the buffer up to n-1 
characters, and *always* put a NUL in at the end.
strcspn() will search the string for a specific character, and return 
the index for that character if found, or the index to the NUL character 
that terminates the string, if character is not found. It will never 
search beyond the string read by fgets().

   Johnny




More information about the Info-vax mailing list