ln.skyscanner/crawl/service/SSH.cs

131 lines
4.0 KiB
C#

// /**
// * File: SSH.cs
// * Author: haraldwolff
// *
// * This file and it's content is copyrighted by the Author and / or copyright holder.
// * Any use wihtout proper permission is illegal and may lead to legal actions.
// *
// *
// **/
using System;
using Renci.SshNet;
using ln.types;
using Renci.SshNet.Common;
using System.Net.Sockets;
using ln.types.net;
namespace ln.skyscanner.crawl.tests
{
public static class SSH
{
static string[] defaultPasswords = new string[]
{
"MNX3oTzhp9am",
"f1whWdj5E2Mo",
"f1whWdj5",
"0Sl71eGw",
"0Sl71eGwVdjI6WeW",
"67E3xpTc",
"67E3xpTcMbwR",
"v1kXbeCux0Td",
"v1kXbeCu",
"YNZRtVUFH94b",
"67E3xpTcMbwR",
"v1kXbeCux0Td",
"DVqxof1JQ9at"
};
public static bool CanConnect(CrawledHost crawledHost)
{
int sshPort = crawledHost.GetHint<int>("ssh.port", -1);
IPv4 sshIP = crawledHost.GetHint<IPv4>("ssh.ip", null);
string sshUser = crawledHost.GetHint<string>("ssh.login", null);
string sshPassword = crawledHost.GetHint<string>("ssh.password", null);
if ((sshPort == -1) || !CanConnect(crawledHost,sshIP,sshPort,sshUser,sshPassword))
{
if (!Scan(crawledHost))
{
crawledHost.SetHint("ssh.port", -1);
crawledHost.SetHint("ssh.ip", null);
crawledHost.SetHint("ssh.login", null);
crawledHost.SetHint("ssh.password", null);
crawledHost.SetHint("ssh.version", null);
return false;
}
}
return true;
}
private static bool Scan(CrawledHost crawledHost)
{
foreach (IPv4 ip in crawledHost.IPAddresses)
{
foreach (int port in new int[] { 13022, 22 })
{
try
{
foreach (string password in defaultPasswords)
{
if (CanConnect(crawledHost, ip, port, "skytron", password, true))
return true;
}
} catch (SocketException)
{
continue;
}
}
}
return false;
}
private static bool CanConnect(CrawledHost crawledHost, IPv4 host, int port, string username, string password,bool throwe = false)
{
using (TcpClient tcp = new TcpClient())
{
try
{
tcp.Connect(host.ToString(), port);
if (!tcp.Connected)
return false;
tcp.Close();
} catch (SocketException)
{
if (throwe)
throw;
return false;
}
}
using (SshClient client = new SshClient(host.ToString(), port, username, password))
{
client.ConnectionInfo.Timeout = TimeSpan.FromSeconds(1);
try
{
client.Connect();
crawledHost.SetHint("ssh.port", client.ConnectionInfo.Port);
crawledHost.SetHint("ssh.ip", host);
crawledHost.SetHint("ssh.login", client.ConnectionInfo.Username);
crawledHost.SetHint("ssh.password", password);
crawledHost.SetHint("ssh.version", client.ConnectionInfo.ServerVersion);
client.Disconnect();
return true;
}
catch (SshException)
{
}
catch (SocketException)
{
return false;
}
}
return false;
}
}
}