zkey: enhance file read/write error handling

fread()/fwrite() return the unsigned count of elements read/written or a
short count or zero in case of an error. Check if the number of elements
read/written matches the expectation. In case of fread(), if it does not
match, check if an error occurred and otherwise assume the file to be too
small. In case of fwrite(), if it does not match, assume an error.

Resolves Cppcheck style warnings:
[zkey/pkey.c:161]: (style) Checking if unsigned variable 'count' is less than zero.
[zkey/pkey.c:209]: (style) Checking if unsigned variable 'count' is less than zero.
[zkey/pkey.c:299]: (style) Checking if unsigned variable 'count' is less than zero.

Cc: Ingo Franzki <ifranzki@de.ibm.com>
Signed-off-by: Jens Remus <jremus@linux.ibm.com>
Reviewed-by: Ingo Franzki <ifranzki@linux.ibm.com>
Reviewed-by: Jan Höppner <hoeppner@linux.ibm.com>
Signed-off-by: Jan Höppner <hoeppner@linux.ibm.com>
This commit is contained in:
Jens Remus
2018-07-31 21:21:56 +02:00
committed by Jan Höppner
parent 322d51e5e4
commit a648dbb014

View File

@@ -158,8 +158,8 @@ u8 *read_secure_key(const char *keyfile, size_t *secure_key_size,
buf = util_malloc(size);
count = fread(buf, 1, size, fp);
if (count <= 0) {
msg = feof(fp) ? "File is too small" : strerror(errno);
if (count != size) {
msg = ferror(fp) ? strerror(errno) : "File is too small";
warnx("File '%s': %s", keyfile, msg);
free(buf);
buf = NULL;
@@ -206,7 +206,7 @@ int write_secure_key(const char *keyfile, const u8 *secure_key,
}
count = fwrite(secure_key, 1, secure_key_size, fp);
if (count <= 0) {
if (count != secure_key_size) {
warnx("File '%s': %s", keyfile, strerror(errno));
fclose(fp);
return -EIO;
@@ -296,8 +296,8 @@ static u8 *read_clear_key(const char *keyfile, size_t keybits, bool xts,
buf = util_malloc(size);
count = fread(buf, 1, size, fp);
if (count <= 0) {
msg = feof(fp) ? "File is too small" : strerror(errno);
if (count != size) {
msg = ferror(fp) ? strerror(errno) : "File is too small";
warnx("File '%s': %s", keyfile, msg);
free(buf);
buf = NULL;