session.cc 18.3 KB
Newer Older
1
2
3
4
5

#include "rsmcore/session.hh"
#include "radixbug/bug.hh"

#include <libssh/libssh.h>
6
#include <libssh/sftp.h>
7

8
#include <sys/stat.h>
9
10
11
12
13
14
#include <cassert>
#include <sstream>

#include <QByteArray>
#include <QString>

15
16
17
18
#ifndef S_IRWXU
#define S_IRWXU 0x0700  // read/write/exec by owner only
#endif

19
20
namespace rsm
{
21
void assert_ssh_session(ssh_session session, const char* error_message)
22
23
24
{
  if (session == nullptr)
  {
25
    throw std::runtime_error(error_message);
26
27
  }
}
28
void assert_ssh_channel(ssh_channel channel, const char* error_message)
29
30
31
{
  if (channel == nullptr)
  {
32
    throw std::runtime_error(error_message);
33
34
35
36
37
38
39
40
41
  }
}

class ChannelImpl
{
 public:
  ssh_channel channel = nullptr;
  explicit ChannelImpl(ssh_session session)
  {
42
    radix_tagged_line("ChannelImpl::ChannelImpl()");
43
44
45
46
    channel = ssh_channel_new(session);
  }
  ~ChannelImpl()
  {
47
    radix_tagged_line("ChannelImpl::~ChannelImpl()");
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
    if (channel != nullptr)
    {
      ssh_channel_close(channel);
      ssh_channel_free(channel);
    }
  }
};  // class ChannelImpl

Channel::Channel()
{
  radix_tagged_line("Channel::Channel()");
  p = nullptr;
}
Channel::~Channel()
{
  radix_tagged_line("Channel::~Channel()");
  if (p != nullptr) delete p;
}

bool Channel::open()
{
  assert_ssh_channel(p->channel, "open() -- Channel is not allocated.");
  int rc = ssh_channel_open_session(p->channel);
  return (rc > -1);
}

bool Channel::isOpen() const
{
  // Perhaps we should just return false
  assert_ssh_channel(p->channel, "isOpen() -- Channel is not allocated.");
  int rc = ssh_channel_is_open(p->channel);
  return (rc != 0);
}

void Channel::close()
{
  if (p->channel != nullptr)
  {
    ssh_channel_close(p->channel);
    ssh_channel_free(p->channel);
    p->channel = nullptr;
  }
}

bool Channel::exec(QString command)
{
  assert_ssh_channel(p->channel, "exec() -- Channel is not allocated.");
  int rc = ssh_channel_request_exec(p->channel, command.toStdString().c_str());
  return !(rc < 0);
}

QString Channel::readExecOut()
{
  assert_ssh_channel(p->channel, "readExecOut() -- Channel is not allocated.");
  char buffer[256];
  int nbytes = ssh_channel_read(p->channel, buffer, sizeof(buffer), 0);
104
  if (nbytes > 0)
105
  {
106
107
    buffer[nbytes - 1] = '\0';
    QString result     = buffer;
108
    return result;
109
  }
110
  return QString("");
111
112
113
114
115
116
}
QString Channel::readExecErr()
{
  assert_ssh_channel(p->channel, "readExecErr() -- Channel is not allocated.");
  char buffer[256];
  int nbytes = ssh_channel_read(p->channel, buffer, sizeof(buffer), 1);
117
  if (nbytes > 0)
118
  {
119
120
    buffer[nbytes - 1] = '\0';
    QString result     = buffer;
121
    return result;
122
  }
123
  return QString("");
124
125
}

126
127
128
129
130
131
132
133
// ----------------------------------------------------------------------------
class SFTPSessionImpl
{
 public:
  sftp_session sftpSession = nullptr;
  explicit SFTPSessionImpl(ssh_session sshSession)
  {
    sftpSession = sftp_new(sshSession);
134
    if (nullptr == sftpSession) return;
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
    // SSH_OK, SSH_ERROR, etc; see libssh.h
    int rc = sftp_init(sftpSession);
    if (rc != SSH_OK)
    {
      sftp_free(sftpSession);
      sftpSession = nullptr;
    }
  }

  ~SFTPSessionImpl()
  {
    if (sftpSession != nullptr) sftp_free(sftpSession);
  }
};  // class SFTPSessionImpl

150
SFTPSession::SFTPSession() { p = nullptr; }
151
152
153
154
155
156
157
158

SFTPSession::~SFTPSession()
{
  if (p != nullptr) delete p;
}

bool SFTPSession::mkdir(QString dirName)
{
159
  if (nullptr == p->sftpSession) return false;
160
161
162
163
164
165
166
167
168
169
170
  int rc = sftp_mkdir(p->sftpSession, dirName.toStdString().c_str(), S_IRWXU);
  if (rc != SSH_OK)
  {
    if (sftp_get_error(p->sftpSession) != SSH_FX_FILE_ALREADY_EXISTS)
      return false;
  }
  return true;
}

bool SFTPSession::rmdir(QString dirName)
{
171
  if (nullptr == p->sftpSession) return false;
172
173
174
175
176
177
178
179
180
  int rc = sftp_rmdir(p->sftpSession, dirName.toStdString().c_str());
  if (rc != SSH_OK)
  {
    if (sftp_get_error(p->sftpSession) != SSH_FX_FILE_ALREADY_EXISTS)
      return false;
  }
  return true;
}

181
SFTPFile* SFTPSession::openFile(QString filename, int accessType)
182
{
183
  return new SFTPFile(this, filename.toStdString().c_str(), accessType);
184
185
}

186
SFTPDir* SFTPSession::openDir(QString dirName)
187
{
188
189
  SFTPDir* sftpDir = new SFTPDir(this, dirName.toStdString().c_str());
  return sftpDir;
190
191
}

192
QString SFTPSession::error() { return QString(ssh_get_error(p->sftpSession)); }
193
194
195
196
197

QString SFTPSession::canonicalize(QString path)
{
  char* str =
      sftp_canonicalize_path(p->sftpSession, path.toStdString().c_str());
198
199
200
201
202
203
204
205
  if (nullptr == str)
  {
    ssh_string_free_char(str);
    return "";
  }
  QString retVal = QString(str);
  ssh_string_free_char(str);
  return retVal;
206
207
208
209
210
211
212
213
214
215
216
}

// ----------------------------------------------------------------------------
class SFTPFileImpl
{
 public:
  sftp_file file = nullptr;

  explicit SFTPFileImpl(sftp_session sftpSession, QString filename,
                        int accessType)
  {
217
    if (nullptr == sftpSession) return;
218
219
220
221
222
223
224
225
226
227
    file = sftp_open(sftpSession, filename.toStdString().c_str(), accessType,
                     S_IRWXU);
  }

  ~SFTPFileImpl()
  {
    if (file != nullptr) sftp_close(file);
  }
};  // class SFTPFileImpl

228
SFTPFile::SFTPFile(SFTPSession* sftpSession, QString filename, int accessType)
229
{
230
  p = new SFTPFileImpl(sftpSession->p->sftpSession, filename, accessType);
231
232
}

233
234
235
236
237
238
239
240
241
SFTPFile::~SFTPFile()
{
  if (p != nullptr) delete p;
}

bool SFTPFile::isOpen() { return (p->file != nullptr); }

// returns number of bytes written on success
// on error, returns < 0 and ssh and sftp session errors are set
242
int64_t SFTPFile::write(QString str)
243
{
244
  if (nullptr == p->file) return -1;
Huff, Israel's avatar
Huff, Israel committed
245
246
247
  std::string stdStr = str.toStdString();
  const char* buf    = stdStr.c_str();
  size_t count       = strlen(buf);
248
  int64_t nwritten   = sftp_write(p->file, buf, count);
249
250
251
252
253
254
255
  return nwritten;
}

// returns empty string and closes file on error; isOpen() can be used to verify
// success
QString SFTPFile::read(size_t nBytes)
{
256
  if (nullptr == p->file || nBytes == 0) return QString();
257
258
  char* buf = new char[nBytes + 1];
  // initialize buff
259
260
  memset(buf, 0, nBytes + 1);
  int64_t nBytesRead = sftp_read(p->file, buf, nBytes);
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
  if (nBytesRead < 0)
  {
    close();
    return QString();
  }
  QString str(buf);
  delete[] buf;
  return str;
}

bool SFTPFile::close()
{
  int rc = sftp_close(p->file);
  if (SSH_NO_ERROR == rc)
  {
    p->file = nullptr;
    return true;
  }
  return false;
}

bool SFTPFile::seek(size_t offset)
{
  int rc = sftp_seek64(p->file, offset);
  if (rc < 0) return false;
  return true;
}

289
int64_t SFTPFile::tell()
290
{
291
  int64_t result = static_cast<int64_t>(sftp_tell64(p->file));
292
293
294
  return result;
}

295
296
297
298
// ----------------------------------------------------------------------------
class SFTPDirImpl
{
 public:
299
300
  sftp_dir dir      = nullptr;
  sftp_session sftp = nullptr;
301
302
303

  explicit SFTPDirImpl(sftp_session sftpSession, QString dirName)
  {
304
    if (nullptr == sftpSession) return;
305
306
    dir  = sftp_opendir(sftpSession, dirName.toStdString().c_str());
    sftp = sftpSession;
307
308
309
310
311
312
313
314
  }

  ~SFTPDirImpl()
  {
    if (dir != nullptr) sftp_closedir(dir);
  }
};  // class SFTPDirImpl

315
SFTPDir::SFTPDir(SFTPSession* sftpSession, QString dirName)
316
{
317
  p = new SFTPDirImpl(sftpSession->p->sftpSession, dirName);
318
319
}

320
321
322
323
324
325
326
SFTPDir::~SFTPDir()
{
  if (p != nullptr) delete p;
}

bool SFTPDir::isOpen() { return (p->dir != nullptr); }

Huff, Israel's avatar
Huff, Israel committed
327
328
329
330
331
bool SFTPDir::hasNext()
{
  if (nullptr == p->dir) return false;
  return (0 == sftp_dir_eof(p->dir));
}
332
333
334
335
336

// returns SFTPAttributes structure on success or nullptr on failure
// caller is responsible for deleting returned SFTPAttributes structure
SFTPAttributes* SFTPDir::next()
{
337
  sftp_attributes sftpResult = sftp_readdir(p->sftp, p->dir);
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
  if (nullptr == sftpResult) return nullptr;

  SFTPAttributes* retVal = new SFTPAttributes;

  retVal->name                = QString(sftpResult->name);
  retVal->longname            = QString(sftpResult->longname);
  retVal->flags               = sftpResult->flags;
  retVal->type                = sftpResult->type;
  retVal->size                = sftpResult->size;
  retVal->uid                 = sftpResult->uid;
  retVal->gid                 = sftpResult->gid;
  retVal->owner               = QString(sftpResult->owner);
  retVal->group               = QString(sftpResult->group);
  retVal->permissions         = sftpResult->permissions;
  retVal->atime64             = sftpResult->atime64;
  retVal->atime               = sftpResult->atime;
  retVal->atime_nseconds      = sftpResult->atime_nseconds;
  retVal->createtime          = sftpResult->createtime;
  retVal->createtime_nseconds = sftpResult->createtime_nseconds;
  retVal->mtime64             = sftpResult->mtime64;
  retVal->mtime               = sftpResult->mtime;
  retVal->mtime_nseconds      = sftpResult->mtime_nseconds;
  retVal->acl                 = QString(ssh_string_get_char(sftpResult->acl));
  retVal->extended_count      = sftpResult->extended_count;
  retVal->extended_type =
      QString(ssh_string_get_char(sftpResult->extended_type));
  retVal->extended_data =
      QString(ssh_string_get_char(sftpResult->extended_data));

367
368
369
  // release memory
  sftp_attributes_free(sftpResult);

370
371
372
373
374
  return retVal;
}

bool SFTPDir::close()
{
Huff, Israel's avatar
Huff, Israel committed
375
  if (nullptr == p->dir) return true;
376
377
378
  int rc = sftp_closedir(p->dir);
  if (SSH_NO_ERROR == rc)
  {
379
380
    p->dir  = nullptr;
    p->sftp = nullptr;
381
382
383
384
385
    return true;
  }
  return false;
}

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
class SessionImpl
{
 public:
  ssh_session session = nullptr;
  SessionImpl()
  {
    session = ssh_new();
    assert_ssh_session(session, "Failed to allocate new ssh session.");
  }
  ~SessionImpl()
  {
    if (session != nullptr)
    {
      ssh_free(session);
    }
  }
};  // class SessionImpl

Session::Session() { p = new SessionImpl(); }

Session::Session(QString host)
{
  p = new SessionImpl();
  setHost(host);
}

Session::~Session()
{
  if (p != nullptr) delete p;
}

void Session::setHost(QString host)
{
  assert_ssh_session(p->session, "setHost() -- Session is not allocated.");
  ssh_options_set(p->session, SSH_OPTIONS_HOST, host.toStdString().c_str());
}

424
QString Session::host() const
425
426
427
{
  // This may not be necessary
  assert_ssh_session(p->session, "host() -- Session is not allocated.");
428
429
  char* host_name = nullptr;
  QString host;
430
431
432
  int rv = ssh_options_get(p->session, SSH_OPTIONS_HOST, &host_name);
  if (rv == SSH_OK)
  {
433
    host = host_name;
434
  }
435
436
437

  if (host_name != nullptr) ssh_string_free_char(host_name);
  return host;
438
439
440
441
442
443
444
445
446
447
448
449
450
451
452
453
454
455
456
}
void Session::setLogVerbosity(SessionVerbosity level)
{
  assert_ssh_session(p->session,
                     "setLogVerbosity() -- Session is not allocated.");
  int verbosity = static_cast<int>(level);
  ssh_options_set(p->session, SSH_OPTIONS_LOG_VERBOSITY, &verbosity);
}
void Session::setPort(int port)
{
  assert_ssh_session(p->session, "setPort() -- Session is not allocated.");
  ssh_options_set(p->session, SSH_OPTIONS_PORT, &port);
}
void Session::setUser(QString name)
{
  assert_ssh_session(p->session, "setName() -- Session is not allocated.");
  ssh_options_set(p->session, SSH_OPTIONS_USER, name.toStdString().c_str());
}

457
QString Session::user() const
458
459
460
{
  // This may not be necessary
  assert_ssh_session(p->session, "user() -- Session is not allocated.");
461
462
  char* user_name = nullptr;
  QString user;
463
464
465
  int rv = ssh_options_get(p->session, SSH_OPTIONS_USER, &user_name);
  if (rv == SSH_OK)
  {
466
    user = user_name;
467
  }
468
469
  if (user_name != nullptr) ssh_string_free_char(user_name);
  return user;
470
471
472
473
474
475
476
477
478
479
480
481
482
}

void Session::setProxyCommand(QString command)
{
  assert_ssh_session(p->session,
                     "setProxyCommand() -- Session is not allocated.");
  ssh_options_set(p->session, SSH_OPTIONS_PROXYCOMMAND,
                  command.toStdString().c_str());
}
bool Session::connect()
{
  assert_ssh_session(p->session, "connect() -- Session is not allocated.");
  radix_tagged_line("connect()");
483
  if (isConnected())
484
485
486
487
488
489
490
491
  {
    radix_tagged_line("session already connected. disconnectinng.");
    ssh_disconnect(p->session);
  }
  {
    radix_tagged_line("Attempting connection.");
    // attempt a connection
    int rc = ssh_connect(p->session);
492
    radix_tagged_line("\tConnect return: " << rc);
493
494
495
496
497
498
499
    return (rc == SSH_OK);
  }
}

bool Session::isConnected() const
{
  assert_ssh_session(p->session, "isConnected() -- Session is not allocated.");
500
  return (ssh_is_connected(p->session) == 1);
501
502
}

503
QString Session::getError() const
504
505
506
507
508
509
510
511
{
  assert_ssh_session(p->session, "getError() -- Session is not allocated.");
  return ssh_get_error(p->session);
}
bool Session::disconnect()
{
  assert_ssh_session(p->session, "disconnect() -- Session is not allocated.");
  radix_tagged_line("disconnect()");
512
  if (isConnected())
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
  {
    radix_tagged_line("Disconnecting session.");
    ssh_disconnect(p->session);
    // copy options in preparation for deletion
    ssh_session new_session = ssh_new();
    ssh_options_copy(p->session, &new_session);
    ssh_free(p->session);
    p->session = new_session;
  }
  return true;
}

QString Session::getHexa() const
{
  assert_ssh_session(p->session, "getHexa() -- Session is not allocated.");
  unsigned char* hash       = nullptr;
  ssh_key server_public_key = nullptr;
  char* hexa;
  size_t hlen;
  QString qhexa;
  int rc = ssh_get_server_publickey(p->session, &server_public_key);
  if (rc < 0)
  {
    return QString();
  }

  // Probably should remove hardwired HASH_SHA1
  rc = ssh_get_publickey_hash(server_public_key, SSH_PUBLICKEY_HASH_SHA1, &hash,
                              &hlen);
  ssh_key_free(server_public_key);
  if (rc < 0)
  {
    return QString();
  }

  hexa  = ssh_get_hexa(hash, hlen);
  qhexa = hexa;
  ssh_clean_pubkey_hash(&hash);
  ssh_string_free_char(hexa);
  return qhexa;
}

SessionHostState Session::verifyKnownHost() const
{
  assert_ssh_session(p->session,
                     "verifyKnownHost() -- Session is not allocated.");
  enum ssh_known_hosts_e state;
  unsigned char* hash       = nullptr;
  ssh_key server_public_key = nullptr;
  size_t hlen;
  QString qhexa;

  radix_tagged_line("verifyKnownHost()");
  int rc = ssh_get_server_publickey(p->session, &server_public_key);
  if (rc < 0)
  {
569
    return SessionHostState::ERROR_STATE;
570
571
572
573
574
575
576
577
  }

  rc = ssh_get_publickey_hash(server_public_key, SSH_PUBLICKEY_HASH_SHA1, &hash,
                              &hlen);
  ssh_clean_pubkey_hash(&hash);
  ssh_key_free(server_public_key);
  if (rc < 0)
  {
578
    return SessionHostState::ERROR_STATE;
579
580
581
582
583
584
585
586
587
588
589
590
591
592
593
594
595
596
597
598
  }

  state = ssh_session_is_known_server(p->session);
  return static_cast<SessionHostState>(state);
}

bool Session::updateKnownHosts()
{
  assert_ssh_session(p->session,
                     "updateKnownHosts() -- Session is not allocated.");
  radix_tagged_line("updateKnownHosts()");
  int rc = ssh_session_update_known_hosts(p->session);
  return (rc == SSH_OK);
}

int Session::authenticationMethodList() const
{
  assert_ssh_session(p->session,
                     "authenticationMethodList() -- Session is not allocated.");

599
600
601
602
603
604
  // required method to be called before auth list is called
  int rc = ssh_userauth_none(p->session, nullptr);
  if (rc == SSH_AUTH_ERROR)
  {
    return SSH_AUTH_METHOD_UNKNOWN;
  }
605
606
607
608
609
610
611
  // get acceptable methods
  int method = ssh_userauth_list(p->session, nullptr);
  return method;
}

SessionAuthState Session::authenticateWithPublicKey()
{
612
613
  assert_ssh_session(
      p->session, "authenticateWithPublicKey() -- Session is not allocated.");
614
615
616
617
  int rc = ssh_userauth_publickey_auto(p->session, nullptr, nullptr);
  return static_cast<SessionAuthState>(rc);
}

618
619
620
621
622
623
624
625
SessionAuthState Session::authenticateInteractively()
{
  assert_ssh_session(
      p->session, "authenticateInteractively() -- Session is not allocated.");
  int rc = ssh_userauth_kbdint(p->session, nullptr, nullptr);
  return static_cast<SessionAuthState>(rc);
}

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
693
694
QString Session::keyboardInteractiveName() const
{
  assert_ssh_session(p->session,
                     "keyboardInteractiveName() -- Session is not allocated.");
  QString name = ssh_userauth_kbdint_getname(p->session);
  return name;
}

QString Session::keyboardInteractiveInstruction() const
{
  assert_ssh_session(
      p->session,
      "keyboardInteractiveInstruction() -- Session is not allocated.");
  QString instruction = ssh_userauth_kbdint_getinstruction(p->session);
  return instruction;
}

QStringList Session::keyboardInteractivePrompts() const
{
  int num_prompts = ssh_userauth_kbdint_getnprompts(p->session);
  // build list of prompts
  QStringList prompts;
  char echo;
  for (int i = 0; i < num_prompts; ++i)
  {
    QString prompt = ssh_userauth_kbdint_getprompt(
        p->session, static_cast<unsigned int>(i), &echo);
    radix_tagged_line(i << ". " << prompt.toStdString());
    if (prompt.isEmpty()) break;
    prompts << prompt;
  }
  return prompts;
}

SessionAuthState Session::authenticateWithPassword(QString pswd)
{
  assert_ssh_session(p->session,
                     "authenticateWithPassword() -- Session is not allocated.");
  radix_tagged_line("Authenticate with password.");
  int rc =
      ssh_userauth_password(p->session, nullptr, pswd.toStdString().c_str());
  return static_cast<SessionAuthState>(rc);
}

QString Session::loginIssueBanner() const
{
  char* banner = ssh_get_issue_banner(p->session);
  if (banner)
  {
    QString qbanner = banner;
    delete banner;
    return qbanner;
  }
  return QString("");
}

SessionAuthState Session::authenticatePrompts(QStringList responses)
{
  int err;
  radix_tagged_line("authenticatePrompts()");
  for (int i = 0; i < responses.size(); ++i)
  {
    radix_tagged_line("Setting response " << i);
    const char* answer = responses.at(i).toStdString().c_str();
    err                = ssh_userauth_kbdint_setanswer(p->session,
                                        static_cast<unsigned int>(i), answer);
    if (err < 0)
    {
      ssh_disconnect(p->session);
695
      return SessionAuthState::ERROR_STATE;
696
697
698
699
700
701
702
703
704
705
706
707
708
    }
  }
  // check status
  err = ssh_userauth_kbdint(p->session, nullptr, nullptr);

  SessionAuthState state = static_cast<SessionAuthState>(err);
  if (state == SessionAuthState::DENIED)
  {
    ssh_disconnect(p->session);
  }
  return state;
}

709
Channel* Session::newChannel()
710
711
{
  assert_ssh_session(p->session, "newChannel() -- Session is not allocated.");
712
713
  Channel* channel = new Channel;
  channel->p       = new ChannelImpl(p->session);
714
715
716
  return channel;
}

717
SFTPSession* Session::newSFTPSession()
718
719
720
{
  assert_ssh_session(p->session,
                     "newSFTPSession() -- SSH Session is not allocated.");
721
722
  SFTPSession* sftpSession = new SFTPSession;
  sftpSession->p           = new SFTPSessionImpl(p->session);
723
724
725
  return sftpSession;
}

726
}  // namespace rsm