File: mock-sshd.c

package info (click to toggle)
libssh 0.12.0-3
  • links: PTS, VCS
  • area: main
  • in suites: sid
  • size: 7,804 kB
  • sloc: ansic: 124,224; cpp: 421; xml: 226; sh: 206; makefile: 26; python: 9
file content (692 lines) | stat: -rw-r--r-- 17,790 bytes parent folder | download | duplicates (2)
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
287
288
289
290
291
292
293
294
295
296
297
298
299
300
301
302
303
304
305
306
307
308
309
310
311
312
313
314
315
316
317
318
319
320
321
322
323
324
325
326
327
328
329
330
331
332
333
334
335
336
337
338
339
340
341
342
343
344
345
346
347
348
349
350
351
352
353
354
355
356
357
358
359
360
361
362
363
364
365
366
367
368
369
370
371
372
373
374
375
376
377
378
379
380
381
382
383
384
385
386
387
388
389
390
391
392
393
394
395
396
397
398
399
400
401
402
403
404
405
406
407
408
409
410
411
412
413
414
415
416
417
418
419
420
421
422
423
424
425
426
427
428
429
430
431
432
433
434
435
436
437
438
439
440
441
442
443
444
445
446
447
448
449
450
451
452
453
454
455
456
457
458
459
460
461
462
463
464
465
466
467
468
469
470
471
472
473
474
475
476
477
478
479
480
481
482
483
484
485
486
487
488
489
490
491
492
493
494
495
496
497
498
499
500
501
502
503
504
505
506
507
508
509
510
511
512
513
514
515
516
517
518
519
520
521
522
523
524
525
526
527
528
529
530
531
532
533
534
535
536
537
538
539
540
541
542
543
544
545
546
547
548
549
550
551
552
553
554
555
556
557
558
559
560
561
562
563
564
565
566
567
568
569
570
571
572
573
574
575
576
577
578
579
580
581
582
583
584
585
586
587
588
589
590
591
592
593
594
595
596
597
598
599
600
601
602
603
604
605
606
607
608
609
610
611
612
613
614
615
616
617
618
619
620
621
622
623
624
625
626
627
628
629
630
631
632
633
634
635
636
637
638
639
640
641
642
643
644
645
646
647
648
649
650
651
652
653
654
655
656
657
658
659
660
661
662
663
664
665
666
667
668
669
670
671
672
673
674
675
676
677
678
679
680
681
682
683
684
685
686
687
688
689
690
691
692
/*
 * Based on SSH example code found here:
 *
 * http://git.libssh.org/users/milo/libssh.git/plain/examples/samplesshd-full.c?h=sshd
 *
 * Copyright 2003-2011 Aris Adamantiadis
 *
 * This file is part of the SSH Library
 *
 * You are free to copy this file, modify it in any way, consider it being public
 * domain. This does not apply to the rest of the library though, but it is
 * allowed to cut-and-paste working code from this file to any license of
 * program.
 *
 * The goal is to show the API in action. It's not a reference on how terminal
 * clients must be made or how a client should react.
 */

#include <libssh/libssh.h>
#include <libssh/server.h>
#include <libssh/callbacks.h>

#include <glib.h>

#include <sys/socket.h>

#include <errno.h>
#include <stdlib.h>
#include <string.h>
#include <stdio.h>
#include <poll.h>
#include <pty.h>
#include <sys/wait.h>
#include <unistd.h>
#include <fcntl.h>

#define BUFSIZE          (8 * 1024)

static gint auth_methods = SSH_AUTH_METHOD_PASSWORD | SSH_AUTH_METHOD_PUBLICKEY | SSH_AUTH_METHOD_INTERACTIVE;
struct {
  int bind_fd;
  int session_fd;
  ssh_session session;
  ssh_event event;
  ssh_channel channel;
  int childpid;
  const gchar *user;
  const gchar *password;
  ssh_key pkey;
  GByteArray *buffer;
  gboolean buffer_eof;
  gboolean multi_step;
} state;

enum
{
  SUCCESS,
  MORE,
  FAILED,
};

static int
auth_interactive (ssh_session session,
                  ssh_message message,
                  gint *round)
{
  static const char *prompts[2] = { "Password", "Token" };
  static char echo[] = { 0, 1 };
  static const char *again[1] = { "So Close" };
  static char again_echo[] = { 0 };
  const char *token;
  int ret = FAILED;
  gint count = 0;
  gint spot = *round;

  g_warning("auth_interactive begin: round %i", *round);

  /* wait for a shell */
  switch (spot)
    {
    case 0:
      if (g_str_equal (ssh_message_auth_user (message), state.user))
        {
          ssh_message_auth_interactive_request (message, "Test Interactive",
                                                state.multi_step ? "Password and Token" : "Password",
                                                state.multi_step ? 2 : 1,
                                                prompts, echo);
          ret = MORE;
        }
      break;
    case 1:
      count = ssh_userauth_kbdint_getnanswers(session);
      if (state.multi_step && count != 2)
        goto out;
      else if (!state.multi_step && count != 1)
        goto out;

      if (!g_str_equal (ssh_userauth_kbdint_getanswer(session, 0), state.password))
        goto out;

      if (state.multi_step)
        {
          token = ssh_userauth_kbdint_getanswer(session, 1);
          if (g_str_equal (token,  "5"))
            {
              ret = SUCCESS;
            }
          else if (g_str_equal (token,  "6"))
            {
              ssh_message_auth_interactive_request (message, "Test Interactive",
                                                    "Again", 1, again, again_echo);
              ret = MORE;
            }
        }
      else
        {
          ret = SUCCESS;
        }
      break;
    case 2:
      count = ssh_userauth_kbdint_getnanswers(session);
      if (count != 1)
        goto out;

      if (g_str_equal (ssh_userauth_kbdint_getanswer(session, 0), "5"))
        ret = SUCCESS;
    }
out:
  if (ret == MORE)
    *round = spot + 1;

  g_warning("auth_interactive round %i, ret %i", *round, ret);
  return ret;
}

static gboolean
auth_password (const gchar *user,
               const gchar *password)
{
  return g_str_equal (user, state.user) &&
         g_str_equal (password, state.password);
}

static int
auth_publickey (ssh_session session,
                const char *user,
                struct ssh_key_struct *pubkey,
                char signature_state,
                void *userdata)
{
  (void)session;
  (void)user;
  (void)userdata;

  gboolean have = ssh_key_cmp (state.pkey,
                               pubkey,
                               SSH_KEY_CMP_PUBLIC) == 0;
  if (have && signature_state == SSH_PUBLICKEY_STATE_VALID)
    return SSH_AUTH_SUCCESS;
  else if (have && signature_state == SSH_PUBLICKEY_STATE_NONE)
    return SSH_AUTH_SUCCESS;

  return SSH_AUTH_DENIED;
}

static int
fd_data (socket_t fd,
         int revents,
         gpointer user_data)
{
  ssh_channel chan = (ssh_channel)user_data;
  guint8 buf[BUFSIZE];
  gint sz = 0;
  gint bytes = 0;
  gint status;
  gint written;
  pid_t pid = 0;
  gboolean end = FALSE;
  gint ret;

  if (revents & POLLIN)
    {
      int ws;
      do
        {
          ws = ssh_channel_window_size (chan);
          ws = ws < BUFSIZE ? ws : BUFSIZE;
          if (ws == 0)
            break;
          bytes = read (fd, buf, ws);
          if (bytes < 0)
            {
              if (errno == EAGAIN)
                break;
              if (errno != ECONNRESET && errno != EBADF)
                g_critical ("couldn't read from process: %m");
              end = TRUE;
              break;
            }
          else if (bytes == 0)
            {
              end = TRUE;
            }
          else
            {
              sz += bytes;
              written = ssh_channel_write (chan, buf, bytes);
              if (written != bytes)
                g_assert_not_reached ();
            }
        }
      while (bytes == ws);
    }
  if ((revents & POLLOUT))
    {
      if (state.buffer->len > 0)
        {
          written = write (fd, state.buffer->data, state.buffer->len);
          if (written < 0 && errno != EAGAIN)
            g_critical ("couldn't write: %s", g_strerror (errno));
          if (written > 0)
            g_byte_array_remove_range (state.buffer, 0, written);
        }
      if (state.buffer_eof && state.buffer->len == 0)
        {
          if (shutdown (fd, SHUT_WR) < 0)
            {
              if (errno != EAGAIN && errno != EBADF)
                g_critical ("couldn't shutdown: %s", g_strerror (errno));
            }
          else
            {
              state.buffer_eof = FALSE;
            }
        }
    }
  if (end || (revents & (POLLHUP | POLLERR | POLLNVAL)))
    {
      ssh_channel_send_eof (chan);
      pid = waitpid (state.childpid, &status, 0);
      if (pid < 0)
        {
          g_critical ("couldn't wait on child process: %m");
        }
      else
        {
          if (WIFSIGNALED (status))
            ssh_channel_request_send_exit_signal (chan, strsignal (WTERMSIG (status)), 0, "", "");
          else
            ssh_channel_request_send_exit_status (chan, WEXITSTATUS (status));
        }
      ret = ssh_blocking_flush (state.session, -1);
      if (ret != SSH_OK && ret != SSH_CLOSED)
        g_message ("ssh_blocking_flush() failed: %d", ret);
      ssh_channel_close (chan);
      ssh_channel_free (chan);
      ret = ssh_blocking_flush (state.session, -1);
      if (ret != SSH_OK && ret != SSH_CLOSED)
        g_message ("ssh_blocking_flush() failed: %d", ret);
      state.channel = NULL;
      ssh_event_remove_fd (state.event, fd);
      sz = -1;
    }

  return sz;
}

static int
chan_data (ssh_session session,
           ssh_channel channel,
           gpointer data,
           guint32 len,
           int is_stderr,
           gpointer user_data)
{
  g_byte_array_append (state.buffer, data, len);
  return len;
}

static void
chan_eof (ssh_session session,
          ssh_channel channel,
          gpointer user_data)
{
  state.buffer_eof = TRUE;
}

static void
chan_close (ssh_session session,
            ssh_channel channel,
            gpointer user_data)
{
  int fd = GPOINTER_TO_INT (user_data);
  close (fd);
}

struct ssh_channel_callbacks_struct cb = {
    .channel_data_function = chan_data,
    .channel_eof_function = chan_eof,
    .channel_close_function = chan_close,
    .userdata = NULL
};

static int
do_shell (ssh_event event,
          ssh_channel chan)
{
  socket_t fd;
  struct termios *term = NULL;
  struct winsize *win = NULL;
  short events;
  int fd_status;

  state.childpid = forkpty (&fd, NULL, term, win);
  if (state.childpid == 0)
    {
      close (state.bind_fd);
      close (state.session_fd);
      execl ("/bin/bash", "/bin/bash", NULL);
      _exit (127);
    }
  else if (state.childpid < 0)
    {
      g_critical ("forkpty failed: %s", g_strerror (errno));
      return -1;
    }

  fd_status = fcntl (fd, F_GETFL, 0);
  if (fcntl (fd, F_SETFL, fd_status | O_NONBLOCK) < 0)
    {
      g_critical ("couldn't set non-blocking mode");
      return -1;
    }

  cb.userdata = (gpointer)(long)fd;
  ssh_callbacks_init(&cb);
  ssh_set_channel_callbacks (chan, &cb);

  events = POLLIN | POLLOUT | POLLPRI | POLLERR | POLLHUP | POLLNVAL;
  if (ssh_event_add_fd (event, fd, events, fd_data, chan) != SSH_OK)
    g_return_val_if_reached(-1);

  return 0;
}

static int
fork_exec (const gchar *cmd)
{
  int spair[2];
  int fd_status;

  if (socketpair (AF_UNIX, SOCK_STREAM, 0, spair) < 0)
    {
      g_critical ("socketpair failed: %s", g_strerror (errno));
      return -1;
    }

  state.childpid = fork ();
  if (state.childpid == 0)
    {
      close (state.bind_fd);
      close (state.session_fd);

      close (0);
      close (1);
      close (spair[1]);
      dup2 (spair[0], 0);
      dup2 (spair[0], 1);
      close (spair[0]);
      execl ("/bin/sh", "/bin/sh", "-c", cmd, NULL);
      _exit (127);
    }
  else if (state.childpid < 0)
    {
      g_critical ("fork failed: %s", g_strerror (errno));
      return -1;
    }

  close (spair[0]);

  fd_status = fcntl (spair[1], F_GETFL, 0);
  if (fcntl (spair[1], F_SETFL, fd_status | O_NONBLOCK) < 0)
    {
      g_critical ("couldn't set non-blocking mode: %s", g_strerror (errno));
      return -1;
    }
  return spair[1];
}

static int
do_exec (ssh_event event,
         ssh_channel chan,
         const gchar *cmd)
{
  socket_t fd;
  short events;

  fd = fork_exec (cmd);
  if (fd < 0)
    return -1;

  cb.userdata = GINT_TO_POINTER (fd);
  ssh_callbacks_init(&cb);
  ssh_set_channel_callbacks (chan, &cb);

  events = POLLIN | POLLOUT | POLLPRI | POLLERR | POLLHUP | POLLNVAL;
  if (ssh_event_add_fd (event, fd, events, fd_data, chan) != SSH_OK)
    g_return_val_if_reached(-1);

  return 0;
}

static int
channel_request_callback (ssh_session session,
                          ssh_message message,
                          gpointer user_data)
{
  const gchar *cmd;

  /* wait for a shell */
  switch (ssh_message_type (message))
    {
    case SSH_REQUEST_CHANNEL:
      switch (ssh_message_subtype (message))
        {
        case SSH_CHANNEL_REQUEST_SHELL:
          if (do_shell (state.event, state.channel) < 0)
            goto deny;
          goto accept_end;
        case SSH_CHANNEL_REQUEST_EXEC:
          cmd = ssh_message_channel_request_command (message);
          if (do_exec (state.event, state.channel, cmd) < 0)
            goto deny;
          goto accept_end;
        case SSH_CHANNEL_REQUEST_PTY:
        case SSH_CHANNEL_REQUEST_ENV:
          goto accept;
        default:
          g_message ("message subtype unknown: %d", ssh_message_subtype (message));
          goto deny;
        }
    default:
      g_message ("message type unknown: %d", ssh_message_type (message));
      goto deny;
    }

deny:
  return 1;

accept_end:
accept:
  ssh_message_channel_request_reply_success (message);
  return 0;
}

static ssh_channel
channel_open_callback (ssh_session session,
                       void *userdata)
{
  (void)userdata;

  g_message ("Allocated session channel");
  state.channel = ssh_channel_new (session);
  ssh_set_message_callback (state.session, channel_request_callback, NULL);
  return state.channel;
}

static int
auth_password_callback (ssh_session session,
                        const char *user,
                        const char *password,
                        void *userdata)
{
  (void)session;
  (void)userdata;

  if (auth_password (user, password))
    return SSH_AUTH_SUCCESS;

  return SSH_AUTH_DENIED;
}

static int
auth_interactive_callback (ssh_message message,
                           ssh_session session,
                           void *userdata)
{
  int rc;
  int *round = userdata;

  g_warning("auth_interactive_callback: round %i", *round);
  rc = auth_interactive (session, message, round);
  if (rc == SUCCESS)
    return SSH_AUTH_SUCCESS;
  else if (rc == MORE)
    return SSH_AUTH_INFO;

  return SSH_AUTH_DENIED;
}

static gint
mock_ssh_server (const gchar *server_addr,
                 gint server_port,
                 const gchar *user,
                 const gchar *password,
                 gboolean multi_step)
{
  char portname[16];
  char addrname[16];
  struct sockaddr_storage addr;
  socklen_t addrlen;
  ssh_bind sshbind;
  pid_t pid;
  const char *msg;
  int r;
  gint rounds = 0;
  struct ssh_server_callbacks_struct server_cb = {
    .userdata = &rounds,
    .auth_password_function = auth_password_callback,
    .auth_pubkey_function = auth_publickey,
    .auth_kbdint_function = auth_interactive_callback,
    .channel_open_request_session_function = channel_open_callback
  };

  state.event = ssh_event_new ();
  if (state.event == NULL)
    g_return_val_if_reached (-1);

  sshbind = ssh_bind_new ();
  state.session = ssh_new ();

  if (server_addr == NULL)
    server_addr = "127.0.0.1";

  ssh_bind_options_set (sshbind, SSH_BIND_OPTIONS_BINDADDR, server_addr);
  ssh_bind_options_set (sshbind, SSH_BIND_OPTIONS_BINDPORT, &server_port);
  ssh_bind_options_set (sshbind, SSH_BIND_OPTIONS_RSAKEY, "mock_rsa_key");

  if (ssh_bind_listen (sshbind) < 0)
    {
      g_critical ("couldn't listen on socket: %s", ssh_get_error (sshbind));
      return 1;
    }

  /* run in the background, and print server pid */
  pid = fork ();
  if (pid < 0) {
      g_critical ("couldn't fork: %m");
      return 1;
  } else if (pid > 0) {
      g_print("%u\n", (unsigned) pid);
      return 0;
  }

  state.bind_fd = ssh_bind_get_fd (sshbind);
  state.user = user;
  state.password = password;
  state.multi_step = multi_step;
  ssh_pki_import_pubkey_file ("test_rsa.pub",
                              &state.pkey);
  state.buffer = g_byte_array_new ();

  /* Print out the port */
  if (server_port == 0)
    {
      addrlen = sizeof (addr);
      if (getsockname (state.bind_fd, (struct sockaddr *)&addr, &addrlen) < 0)
        {
          g_critical ("couldn't get local address: %s", g_strerror (errno));
          return 1;
        }
      r = getnameinfo ((struct sockaddr *)&addr, addrlen, addrname, sizeof (addrname),
                       portname, sizeof (portname), NI_NUMERICHOST | NI_NUMERICSERV);
      if (r != 0)
        {
          g_critical ("couldn't get local port: %s", gai_strerror (r));
          return 1;
        }

      /* Caller wants to know the port */
      g_print ("%s\n", portname);
    }

  /* Close stdout (once above info is printed) */
  close (1);

  ssh_callbacks_init (&server_cb);
  ssh_set_server_callbacks (state.session, &server_cb);
  ssh_set_auth_methods (state.session, auth_methods);

  r = ssh_bind_accept (sshbind, state.session);
  if (r == SSH_ERROR)
    {
      g_critical ("accepting connection failed: %s", ssh_get_error (sshbind));
      return 1;
    }

  state.session_fd = ssh_get_fd (state.session);

  if (ssh_handle_key_exchange (state.session))
    {
      msg = ssh_get_error (state.session);
      if (!strstr (msg, "_DISCONNECT"))
        g_critical ("key exchange failed: %s", msg);
      return 1;
    }

  if (ssh_event_add_session (state.event, state.session) != SSH_OK)
    g_return_val_if_reached (-1);

  do
    {
      ssh_event_dopoll (state.event, 10000);
    }
  while (ssh_is_connected (state.session));

  ssh_event_remove_session (state.event, state.session);
  ssh_event_free (state.event);
  ssh_free (state.session);
  ssh_key_free (state.pkey);
  g_byte_array_free (state.buffer, TRUE);
  ssh_bind_free (sshbind);

  return 0;
}

int
main (int argc,
      char *argv[])
{
  GOptionContext *context;
  gchar *user = NULL;
  gchar *password = NULL;
  gchar *bind = NULL;
  GError *error = NULL;
  gboolean verbose = FALSE;
  gboolean broken_auth = FALSE;
  gboolean multi_step = FALSE;
  gint port = 0;
  int ret;

  GOptionEntry entries[] = {
    { "user", 0, 0, G_OPTION_ARG_STRING, &user, "User name to expect", "name" },
    { "password", 0, 0, G_OPTION_ARG_STRING, &password, "Password to expect", "xxx" },
    { "bind", 0, 0, G_OPTION_ARG_STRING, &bind, "Address to bind to", "addr" },
    { "port", 'p', 0, G_OPTION_ARG_INT, &port, "Port to bind to", "NN" },
    { "verbose", 'v', 0, G_OPTION_ARG_NONE, &verbose, "Verbose info", NULL },
    { "multi-step", 'm', 0, G_OPTION_ARG_NONE, &multi_step, "Multi Step Auth", NULL },
    { "broken-auth", 0, 0, G_OPTION_ARG_NONE, &broken_auth, "Break authentication", NULL },
    { NULL }
  };

#ifdef __linux
#include <sys/prctl.h>
  prctl (PR_SET_PDEATHSIG, 15);
#endif

  if (signal (SIGPIPE, SIG_IGN) == SIG_ERR)
    g_assert_not_reached ();

  ssh_init ();

  context = g_option_context_new ("- mock ssh server");
  g_option_context_add_main_entries (context, entries, "");
  if (!g_option_context_parse (context, &argc, &argv, &error))
    {
      g_printerr ("mock-sshd: %s\n", error->message);
      g_error_free (error);
      ret = 2;
    }
  else if (argc != 1)
    {
      g_printerr ("mock-sshd: extra arguments on command line\n");
      ret = 2;
    }
  else
    {
      if (broken_auth)
        auth_methods = SSH_AUTH_METHOD_HOSTBASED;
      if (verbose)
        ssh_set_log_level (SSH_LOG_PROTOCOL);
      ret = mock_ssh_server (bind, port, user, password, multi_step);
    }

  g_option_context_free (context);
  g_free (password);
  g_free (user);
  g_free (bind);

  ssh_finalize ();
  return ret;
}