ssh2_client_fuzzer.cc 2.2 KB

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