Re: [PATCH] Fix buffer not null terminated on (ecpg lib)

From: Kyotaro Horiguchi <horikyota(dot)ntt(at)gmail(dot)com>
To: ranier(dot)vf(at)gmail(dot)com
Cc: pgsql-hackers(at)lists(dot)postgresql(dot)org
Subject: Re: [PATCH] Fix buffer not null terminated on (ecpg lib)
Date: 2020-04-23 02:27:25
Message-ID: 20200423.112725.603704621067276073.horikyota.ntt@gmail.com
Views: Raw Message | Whole Thread | Download mbox | Resend email
Thread:
Lists: pgsql-hackers

Hello.

At Wed, 22 Apr 2020 19:48:07 -0300, Ranier Vilela <ranier(dot)vf(at)gmail(dot)com> wrote in
> Hi,
> strncpy, it is not a safe function and has the risk of corrupting memory.
> On ecpg lib, two sources, make use of strncpy risk, this patch tries to fix.
>
> 1. Make room for the last null-characte;
> 2. Copies Maximum number of characters - 1.
>
> per Coverity.

- strncpy(sqlca->sqlstate, sqlstate, sizeof(sqlca->sqlstate));
+ sqlca->sqlstate[sizeof(sqlca->sqlstate) - 1] = '\0';
+ strncpy(sqlca->sqlstate, sqlstate, sizeof(sqlca->sqlstate) - 1);

Did you look at the definition and usages of the struct member?
sqlstate is a char[5], which is to be filled with 5-letter SQLSTATE
code not terminated by NUL, which can be shorter if NUL is found
anywhere (I'm not sure there's actually a case of a shorter state
code). If you put NUL to the 5th element of the array, you break the
content. The existing code looks perfect to me.

- strncpy(sqlca->sqlerrm.sqlerrmc, message, sizeof(sqlca->sqlerrm.sqlerrmc));
- sqlca->sqlerrm.sqlerrmc[sizeof(sqlca->sqlerrm.sqlerrmc) - 1] = 0;
+ sqlca->sqlerrm.sqlerrmc[sizeof(sqlca->sqlerrm.sqlerrmc) - 1] = '\0';
+ strncpy(sqlca->sqlerrm.sqlerrmc, message, sizeof(sqlca->sqlerrm.sqlerrmc) - 1);

The existing strncpy then terminating by NUL works fine. I don't think
there's any point in doing the reverse way. Actually
sizeof(sqlca->sqlerrm.sqlerrmc) - 1 is enough for the length but the
existing code is not necessarily a bug.

regards.

--
Kyotaro Horiguchi
NTT Open Source Software Center

In response to

Responses

Browse pgsql-hackers by date

  From Date Subject
Next Message Fujii Masao 2020-04-23 02:33:46 Re: backup manifests
Previous Message Robert Haas 2020-04-23 02:11:03 Re: More efficient RI checks - take 2