Skip to content

Commit

Permalink
examples/echo: do not leak an opened file when an error happens
Browse files Browse the repository at this point in the history
In both `echo_load_private_key` and `echo_load_public_key`, when
`len > MAX_DH_KEY_LEN`, the opened file is not closed before the
function returns.

Fix this possible resource leak by opening the file after checking `len`.

This bug was found using clang's static analyzer:

    scan-build -enable-checker alpha.unix.Stream make
  • Loading branch information
niooss-ledger committed Jun 17, 2021
1 parent 9379e58 commit 1758c27
Showing 1 changed file with 4 additions and 2 deletions.
6 changes: 4 additions & 2 deletions examples/echo/echo-server/echo-common.c
Original file line number Diff line number Diff line change
Expand Up @@ -211,13 +211,14 @@ int echo_to_noise_protocol_id(NoiseProtocolId *nid, const EchoProtocolId *id)
/* Loads a binary private key from a file. Returns non-zero if OK. */
int echo_load_private_key(const char *filename, uint8_t *key, size_t len)
{
FILE *file = fopen(filename, "rb");
FILE *file;
size_t posn = 0;
int ch;
if (len > MAX_DH_KEY_LEN) {
fprintf(stderr, "private key length is not supported\n");
return 0;
}
file = fopen(filename, "rb");
if (!file) {
perror(filename);
return 0;
Expand All @@ -242,7 +243,7 @@ int echo_load_private_key(const char *filename, uint8_t *key, size_t len)
/* Loads a base64-encoded public key from a file. Returns non-zero if OK. */
int echo_load_public_key(const char *filename, uint8_t *key, size_t len)
{
FILE *file = fopen(filename, "rb");
FILE *file;
uint32_t group = 0;
size_t group_size = 0;
uint32_t digit = 0;
Expand All @@ -252,6 +253,7 @@ int echo_load_public_key(const char *filename, uint8_t *key, size_t len)
fprintf(stderr, "public key length is not supported\n");
return 0;
}
file = fopen(filename, "rb");
if (!file) {
perror(filename);
return 0;
Expand Down

0 comments on commit 1758c27

Please sign in to comment.