| 1 |
/* Copyright (C) The libssh2 project and its contributors. |
| 2 |
* |
| 3 |
* SPDX-License-Identifier: BSD-3-Clause |
| 4 |
*/ |
| 5 |
#include <assert.h> |
| 6 |
#include <errno.h> |
| 7 |
#include <stdbool.h> |
| 8 |
#include <stdio.h> |
| 9 |
#include <stdlib.h> |
| 10 |
#include <string.h> |
| 11 |
#include <sys/socket.h> |
| 12 |
#include <unistd.h> |
| 13 |
#include <libssh2.h> |
| 14 |
#include "testinput.h" |
| 15 |
|
| 16 |
#define FUZZ_ASSERT(COND) \ |
| 17 |
if(!(COND)) \ |
| 18 |
{ \ |
| 19 |
fprintf(stderr, "Assertion failed: " #COND "\n%s", \ |
| 20 |
strerror(errno)); \ |
| 21 |
assert((COND)); \ |
| 22 |
} |
| 23 |
|
| 24 |
extern "C" int LLVMFuzzerTestOneInput(const uint8_t *data, size_t size) |
| 25 |
{ |
| 26 |
int socket_fds[2] = {-1, -1}; |
| 27 |
ssize_t written; |
| 28 |
int rc; |
| 29 |
LIBSSH2_SESSION *session = NULL; |
| 30 |
int handshake_completed = 0; |
| 31 |
|
| 32 |
rc = libssh2_init(0); |
| 33 |
|
| 34 |
if(rc) { |
| 35 |
fprintf(stderr, "libssh2 initialization failed (%d)\n", rc); |
| 36 |
goto EXIT_LABEL; |
| 37 |
} |
| 38 |
|
| 39 |
// Create a socket pair so data can be sent in. |
| 40 |
rc = socketpair(AF_UNIX, SOCK_STREAM, 0, socket_fds); |
| 41 |
FUZZ_ASSERT(rc == 0); |
| 42 |
|
| 43 |
written = send(socket_fds[1], data, size, 0); |
| 44 |
|
| 45 |
if(written != size) |
| 46 |
{ |
| 47 |
// Handle whatever error case we're in. |
| 48 |
fprintf(stderr, "send() of %zu bytes returned %zu (%d)\n", |
| 49 |
size, |
| 50 |
written, |
| 51 |
errno); |
| 52 |
goto EXIT_LABEL; |
| 53 |
} |
| 54 |
|
| 55 |
rc = shutdown(socket_fds[1], SHUT_WR); |
| 56 |
if(rc) |
| 57 |
{ |
| 58 |
fprintf(stderr, "socket shutdown failed (%d)\n", rc); |
| 59 |
goto EXIT_LABEL; |
| 60 |
} |
| 61 |
|
| 62 |
// Create a session and start the handshake using the fuzz data passed in. |
| 63 |
session = libssh2_session_init(); |
| 64 |
if(session) { |
| 65 |
libssh2_session_set_blocking(session, 1); |
| 66 |
} |
| 67 |
else { |
| 68 |
goto EXIT_LABEL; |
| 69 |
} |
| 70 |
|
| 71 |
if(libssh2_session_handshake(session, socket_fds[0])) { |
| 72 |
goto EXIT_LABEL; |
| 73 |
} |
| 74 |
|
| 75 |
// If we get here the handshake actually completed. |
| 76 |
handshake_completed = 1; |
| 77 |
|
| 78 |
EXIT_LABEL: |
| 79 |
|
| 80 |
if(session) |
| 81 |
{ |
| 82 |
if(handshake_completed) |
| 83 |
{ |
| 84 |
libssh2_session_disconnect(session, |
| 85 |
"Normal Shutdown, Thank you for playing"); |
| 86 |
} |
| 87 |
|
| 88 |
libssh2_session_free(session); |
| 89 |
} |
| 90 |
|
| 91 |
libssh2_exit(); |
| 92 |
|
| 93 |
close(socket_fds[0]); |
| 94 |
close(socket_fds[1]); |
| 95 |
|
| 96 |
return 0; |
| 97 |
} |