Coverage Report

Created: 2025-07-01 07:11

/src/libssh/tests/fuzz/ssh_known_hosts_fuzzer.c
Line
Count
Source (jump to first uncovered line)
1
/*
2
 * Copyright 2022 Jakub Jelen <jjelen@redhat.com>
3
 *
4
 * Licensed under the Apache License, Version 2.0 (the "License");
5
 * you may not use this file except in compliance with the License.
6
 * You may obtain a copy of the License at
7
 *
8
 *      http://www.apache.org/licenses/LICENSE-2.0
9
 *
10
 * Unless required by applicable law or agreed to in writing, software
11
 * distributed under the License is distributed on an "AS IS" BASIS,
12
 * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
13
 * See the License for the specific language governing permissions and
14
 * limitations under the License.
15
 */
16
17
#include <assert.h>
18
#include <stdio.h>
19
#include <stdlib.h>
20
#include <string.h>
21
22
#define LIBSSH_STATIC 1
23
#include "libssh/libssh.h"
24
#include "knownhosts.c"
25
26
int LLVMFuzzerTestOneInput(const uint8_t *data, size_t size)
27
2.53k
{
28
2.53k
    char *hostname = NULL;
29
2.53k
    const uint8_t *hostname_end = NULL;
30
2.53k
    size_t hostname_len = 0;
31
2.53k
    char filename[256];
32
2.53k
    struct ssh_list *entries = NULL;
33
2.53k
    struct ssh_iterator *it = NULL;
34
2.53k
    FILE *fp = NULL;
35
36
    /* Interpret the first part of the string (until the first NULL byte)
37
     * as a hostname we are searching for in the file */
38
2.53k
    hostname_end = memchr(data, '\0', size);
39
2.53k
    if (hostname_end == NULL) {
40
1
        return 1;
41
1
    }
42
2.53k
    hostname_len = hostname_end - data + 1;
43
2.53k
    if (hostname_len > 253) {
44
        /* This is the maximum valid length of a hostname */
45
13
        return 1;
46
13
    }
47
2.52k
    hostname = malloc(hostname_len);
48
2.52k
    if (hostname == NULL) {
49
0
        return 1;
50
0
    }
51
2.52k
    memcpy(hostname, data, hostname_len);
52
53
2.52k
    snprintf(filename, sizeof(filename), "/tmp/libfuzzer.%d", getpid());
54
2.52k
    fp = fopen(filename, "wb");
55
2.52k
    if (!fp) {
56
0
        free(hostname);
57
0
        return 1;
58
0
    }
59
2.52k
    fwrite(data + hostname_len, size - hostname_len, 1, fp);
60
2.52k
    fclose(fp);
61
62
2.52k
    ssh_init();
63
64
2.52k
    ssh_known_hosts_read_entries(hostname, filename, &entries);
65
2.52k
    for (it = ssh_list_get_iterator(entries);
66
4.54k
         it != NULL;
67
2.52k
         it = ssh_list_get_iterator(entries)) {
68
2.01k
        struct ssh_knownhosts_entry *entry = NULL;
69
70
2.01k
        entry = ssh_iterator_value(struct ssh_knownhosts_entry *, it);
71
2.01k
        ssh_knownhosts_entry_free(entry);
72
2.01k
        ssh_list_remove(entries, it);
73
2.01k
    }
74
2.52k
    ssh_list_free(entries);
75
76
2.52k
    ssh_finalize();
77
78
2.52k
    free(hostname);
79
2.52k
    unlink(filename);
80
81
2.52k
    return 0;
82
2.52k
}