Пример #1
0
        private void Connect()
        {
            NetworkDevice host = (NetworkDevice)lstBox_devices.SelectedItem;

            try
            {
                sshClient = new SshClient(host.Name, txtBox_username.Text, txtBox_password.Text);
                sshClient.Connect();
            }
            catch (ArgumentException)
            {
                MessageBox.Show("Username is required.");
                return;
            }
            catch (Exception exception)
            {
                MessageBox.Show(exception.Message);
                return;
            }

            controllerForm              = new ControllerForm(sshClient, host);
            btn_Connect.Enabled         = false;
            controllerForm.FormClosing += ControllerForm_FormClosing;
            controllerForm.Show();
        }
Пример #2
0
        public static void SendTcpSyn(NetworkDevice dev)
        {
            byte[] bytes = new byte[54];

            TCPPacket tcp = new TCPPacket(lLen, bytes, true);

            //Ethernet fields
            tcp.SourceHwAddress      = dev.MacAddress;                  //Set the source mac of the local device
            tcp.DestinationHwAddress = destMAC;                         //Set the dest MAC of the gateway
            tcp.EthernetProtocol     = EthernetProtocols_Fields.IP;

            //IP fields
            tcp.DestinationAddress = destIP;                                    //The IP of the destination host
            tcp.SourceAddress      = dev.IpAddress;                             //The IP of the local device
            tcp.IPProtocol         = IPProtocols_Fields.TCP;
            tcp.TimeToLive         = 20;
            tcp.Id             = 100;
            tcp.Version        = 4;
            tcp.IPTotalLength  = bytes.Length - lLen;                           //Set the correct IP length
            tcp.IPHeaderLength = IPFields_Fields.IP_HEADER_LEN;

            //TCP fields
            tcp.SourcePort            = sourcePort;                             //The TCP source port
            tcp.DestinationPort       = destPort;                               //The TCP dest port
            tcp.Syn                   = true;                                   //Set the SYN flag on
            tcp.WindowSize            = 555;
            tcp.AcknowledgementNumber = 1000;
            tcp.SequenceNumber        = 1000;
            tcp.TCPHeaderLength       = TCPFields_Fields.TCP_HEADER_LEN;                        //Set the correct TCP header length

            //tcp.SetData( System.Text.Encoding.ASCII.GetBytes("HELLO") );

            //Calculate checksums
            tcp.ComputeIPChecksum();
            tcp.ComputeTCPChecksum();

            dev.PcapOpen(true, 20);

            //Set a filter to capture only replies
            dev.PcapSetFilter("ip src " + destIP + " and ip dst " +
                              dev.IpAddress + " and tcp src port " + destPort + " and tcp dst port " + sourcePort);

            //Send the packet
            Console.Write("Sending packet: " + tcp + "...");
            dev.PcapSendPacket(tcp);
            Console.WriteLine("Packet sent.");

            //Holds the reply
            Packet reply;

            //Wait till you get a reply
            while ((reply = dev.PcapGetNextPacket()) == null)
            {
                ;
            }
            //print the reply
            Console.WriteLine("Reply received: " + reply);

            dev.PcapClose();
        }
Пример #3
0
    public void ModifyLevel(int level, bool open)
    {
        NetworkDevice   device = TerminalNetwork.GetCurrentDevice();
        NetworkFirewall wall   = device.networkNode.FireWall;

        wall.Level[level].Unlocked = open;
    }
Пример #4
0
    void OpenPort()
    {
        NetworkDevice device = TerminalNetwork.GetCurrentDevice();

        TerminalCore.AddMessage("\t" + portToOpen + " - Access Granted.");
        device.networkNode.OpenPort(portToOpen);
    }
Пример #5
0
    public void CrackFirewall()
    {
        TerminalCore.PauseTerminal(0.3f);
        NetworkDevice   device = TerminalNetwork.GetCurrentDevice();
        NetworkFirewall wall   = device.networkNode.FireWall;

        NetworkFirewall.FirewallLevel level = wall.GetNextClosedFirewall();
        if (!IsCracked(level.CurrentGuess))
        {
            int    r     = GetRandomLetter(level.CurrentGuess);
            char[] guess = new char[level.CurrentGuess.Length];

            for (int i = 0; i < level.CurrentGuess.Length; i++)
            {
                if (i == r)
                {
                    guess[i] = level.Password[i];
                }
                else
                {
                    guess[i] = level.CurrentGuess[i];
                }
            }

            level.CurrentGuess = new string(guess);
        }

        consoleLine.ConsoleLine = "\t- Guess: " + TerminalColourScheme.FormatText(level.CurrentGuess, TerminalStyle.INFO);
        consoleLine             = null;
    }
Пример #6
0
    public void initDeviceConnection(TcpConnection _conn, string[] _formatData)
    {
        NetworkDevice tempDevice = _enabledConnections.Find(x => x.id == _formatData[2]);

        if (tempDevice != null)
        {
            _enabledConnections.Remove(tempDevice);
            tempDevice.stop();
            tempDevice = null;
        }

        _disabledConnections.Remove(_conn);
        NetworkDevice device = new NetworkDevice(_conn, _formatData[2], _formatData[3]);

        _enabledConnections.Add(device);

        _conn.OnRecieveTcpPackage += (string _data) => {
            string[] formatData = _data.Split(';');
            Console.WriteLine(string.Format("[SERVER] DEVICE[{0}] recieved data: {1}", _conn.networkId, _data));

            if (formatData[0] == "COMPLETE")
            {
                foreach (NetworkUser user in _userConnections)
                {
                    user.updateDevice(device);
                }
            }
            else if (formatData[0] == "RET")
            {
                foreach (NetworkUser user in _userConnections)
                {
                    user.send("DEVUPD;" + device.id + ";" + _data);
                }
                Setting_Device_Commmand[] list = SettingsController.commands;
                if (list != null)
                {
                    foreach (Setting_Device_Commmand comm in list)
                    {
                        if (comm.deviceName == device.id && comm.id == formatData[1])
                        {
                            if (comm.type == SettingDeviceCommandType.SET)
                            {
                                TreeLightController.set(new Setting_RGB(), false);
                            }
                            else
                            {
                                TreeLightController.blink(new Setting_RGB(), 3);
                            }
                        }
                    }
                }
            }
        };

        _conn.OnConnectionClosed += () => {
            _enabledConnections.Remove(device);
        };

        _conn.send("INIT");
    }
Пример #7
0
    public void SolveCommand(string[] args)
    {
        NetworkDevice   device = TerminalNetwork.GetCurrentDevice();
        NetworkFirewall wall   = device.networkNode.FireWall;

        NetworkFirewall.FirewallLevel level = wall.GetNextClosedFirewall();
        int levelIndex = wall.GetNextClosedFirewallIndex();

        if (args.Length > 0)
        {
            if (args[0].ToUpper() == level.Password.ToUpper())
            {
                TerminalCore.AddLoadingBar(0.5f, AttemptSolve, "\n\tAttempting Solution: " + level.Password, "\n\tSolution Accepted.");

                level.CurrentGuess = level.Password;
                return;
            }

            char   guess        = args[0].ToUpper()[0];
            char[] CurrentGuess = level.CurrentGuess.ToCharArray();
            for (int i = 0; i < level.Password.Length; i++)
            {
                if (level.Password.ToUpper()[i] == guess)
                {
                    CurrentGuess[i] = level.Password[i];
                }
            }

            level.CurrentGuess = new string(CurrentGuess);
            TerminalCore.AddMessage("");
            string[] array = level.CurrentGuess.ToCharArray().Select(a => a.ToString()).ToArray();
            array[0] = "\t - Guess: " + array[0];
            TerminalCore.AddLoadingBar(0.5f, AttemptSolve, array);
        }
    }
Пример #8
0
    public void AttemptSolve()
    {
        NetworkDevice   device = TerminalNetwork.GetCurrentDevice();
        NetworkFirewall wall   = device.networkNode.FireWall;

        NetworkFirewall.FirewallLevel level = wall.GetNextClosedFirewall();
        int levelIndex = wall.GetNextClosedFirewallIndex();

        if (level.CurrentGuess == level.Password)
        {
            level.Unlocked = true;

            ModifyLevel(levelIndex, true);

            TerminalCore.AddMessage(
                string.Format("\t- Firewall Cracked:" + TerminalColourScheme.FormatText("{0}/{1}", TerminalStyle.INFO),
                              wall.GetSolvedLevels(),
                              wall.GetTotalLevels()
                              ));


            if (wall.GetSolvedLevels() == wall.GetTotalLevels())
            {
                TerminalCore.AddMessage(TerminalColourScheme.FormatText("\n\t- Firewall Broken.", TerminalStyle.WARNING) + TerminalColourScheme.FormatText("\n\tAccess Granted.", TerminalStyle.INFO));
            }
        }
        else
        {
            TerminalUI.ForceInput("solve ");
        }
    }
Пример #9
0
        public async Task AddAsync(string manufacturer,
                                   string model,
                                   string serialNumber,
                                   string deviceDescription,
                                   int userId,
                                   int categoryId,
                                   string IPAddress)
        {
            Category cat = _context.Categories.Find(categoryId);
            User     usr = _context.Users.Find(userId);

            var device = new NetworkDevice
            {
                Manufacturer      = manufacturer,
                Model             = model,
                SerialNumber      = serialNumber,
                DeviceDescription = deviceDescription,
                DeviceOwner       = usr,
                IPAddress         = IPAddress,
                isAlive           = false,
                Categories        = new List <Category>()
            };

            device.Categories.Add(cat);
            _context.Device.Add(device);
            _context.SaveChanges();
        }
Пример #10
0
        public void AdminStatusTest()
        {
            NetworkDeviceList devs  = IPHelper.GetAllDevices();
            NetworkDevice     myDev = null;

            foreach (NetworkDevice dev in devs)
            {
                Console.WriteLine(dev.ToStringDetailed());
                if (dev.Name.EndsWith("{2E39C390-6D40-412E-ADF4-8270E3782F74}"))
                {
                    myDev = dev;
                }
            }

            if (myDev != null)
            {
                Console.WriteLine("Bringing down '{0}'...", myDev.Description);
                myDev.AdminStatus = false;
                Assert.IsTrue(!myDev.AdminStatus, "Admin status should be: False");
                //System.Threading.Thread.Sleep(10000);
                Console.WriteLine("Bringing up '{0}'...", myDev.Description);
                myDev.AdminStatus = true;
                Assert.IsTrue(myDev.AdminStatus, "Admin status should be: True");
            }
        }
Пример #11
0
        public static void Remove(NetworkDevice key)
        {
            int index = Keys.IndexOf(key);

            Keys.RemoveAt(index);
            Values.RemoveAt(index);
        }
Пример #12
0
    IEnumerator DoTransition(NetworkDevice current)
    {
        foreach (KeyValuePair <NetworkDevice, GameObject> g in Lines)
        {
            Destroy(g.Value);
        }

        if (current != null)
        {
            if (Devices.ContainsKey(current))
            {
                while (Vector2.Distance(Devices[current].GetComponent <RectTransform>().anchoredPosition, Vector2.zero) > 1)
                {
                    Devices[current].GetComponent <RectTransform>().anchoredPosition = Vector3.MoveTowards(Devices[current].GetComponent <RectTransform>().anchoredPosition, Vector3.zero, 600f * Time.unscaledDeltaTime);
                    yield return(new WaitForEndOfFrame());
                }

                Destroy(Devices[current]);
            }
        }

        Devices.Clear();

        Lines.Clear();
        PopulateNodes();
    }
Пример #13
0
        public void New_NetworkDevice_Gets_Id()
        {
            Guid          deviceId = Guid.NewGuid();
            string        hostname = "SESM-001";
            NetworkDevice device   = new NetworkDevice(deviceId, hostname);

            Assert.AreEqual(deviceId, device.AggregateId);
        }
Пример #14
0
 /// <summary>
 /// Set ConfigIP for NetworkDevice
 /// </summary>
 /// <param name="nic">Network device.</param>
 ///  /// <param name="config">IP Config</param>
 private static void SetConfigIP(NetworkDevice nic, IPConfig config)
 {
     NetworkConfig.Add(nic, config);
     AddressMap.Add(config.IPAddress.Hash, nic);
     MACMap.Add(nic.MACAddress.Hash, nic);
     IPConfig.Add(config);
     nic.DataReceived = HandlePacket;
 }
Пример #15
0
        internal static void AddPacket(IPPacket packet)
        {
            ensureQueueExists();
            NetworkDevice nic = Config.FindInterface(packet.SourceIP);

            packet.SourceMAC = nic.MACAddress;
            queue.Add(new BufferEntry(nic, packet));
        }
Пример #16
0
 public static void RemoveIPConfig(NetworkDevice nic)
 {
     IPV4.Config config = NetworkConfig.Get(nic);
     AddressMap.Remove(config.IPAddress.Hash);
     MACMap.Remove(nic.MACAddress.Hash);
     IPV4.Config.Remove(config);
     NetworkConfig.Remove(nic);
 }
Пример #17
0
 void Reset()
 {
     _timeout            = 0f;
     _state              = States.None;
     _networkName        = null;
     _deviceToConnect    = null;
     _deviceToDisconnect = null;
     NetworkDeviceList   = new List <NetworkDevice> ();
 }
Пример #18
0
        private void DeviceClicked(NetworkDevice device)
        {
            DevicePage dp = new DevicePage(device, this);

            // Hide the main form
            this.Hide();
            // Show the Device Page as a dialog
            dp.ShowDialog();
        }
Пример #19
0
    public void initUserConnection(TcpConnection _conn, string[] _formatData)
    {
        _disabledConnections.Remove(_conn);
        NetworkUser user = new NetworkUser(_conn);

        _userConnections.Add(user);

        _conn.OnRecieveTcpPackage += (string _data) => {
            string[] formatData = _data.Split(';');
            Console.WriteLine(string.Format("[SERVER] USER[{0}] recieved data: {1}", _conn.networkId, _data));

            if (formatData[0] == "GETDEV")
            {
                user.updateDevices(_enabledConnections.ToArray());
            }
            else if (formatData[0] == "DEVSEN")
            {
                string command = "";
                for (int i = 2; i < formatData.Length; i++)
                {
                    command += formatData[i];
                    if (i < formatData.Length - 1)
                    {
                        command += ";";
                    }
                }
                NetworkDevice device = _enabledConnections.Find(x => x.id == formatData[1]);
                if (device != null)
                {
                    device.send(command);
                }
            }
            else if (formatData[0] == "RESYNCSET")
            {
                if (formatData[1] == "info")
                {
                    SettingsController.resyncInfo(formatData[2]);
                }
                else if (formatData[1] == "tree")
                {
                    SettingsController.resyncTree(formatData[2]);
                }
                else if (formatData[1] == "commands")
                {
                    SettingsController.resyncCommands(formatData[2]);
                }
            }
        };

        _conn.OnConnectionClosed += () => {
            _userConnections.Remove(user);
        };

        Thread th = new Thread(new ParameterizedThreadStart(_syncSettings));

        th.Start(_conn);
    }
Пример #20
0
        private void AddDevice(int netId, NetworkDevice networkDevice)
        {
            if (!_devices.ContainsKey(netId))
            {
                _devices[netId] = new List <NetworkDevice>();
            }

            _devices[netId].Add(networkDevice);
        }
Пример #21
0
    void Update()
    {
        if (lastDevice != TerminalNetwork.GetCurrentDevice())
        {
            UpdateNodes();
        }

        lastDevice = TerminalNetwork.GetCurrentDevice();
    }
Пример #22
0
 public void WriteDevice(NetworkDevice device, byte[] bytes, Action onWritten)
 {
     BluetoothLEHardwareInterface.WriteCharacteristic(device.Address, SampleCharacteristic.ServiceUUID, SampleCharacteristic.CharacteristicUUID, bytes, bytes.Length, true, (Characteristic) => {
         if (onWritten != null)
         {
             onWritten();
         }
     });
 }
Пример #23
0
        public void SetHostName_AppliesChange()
        {
            Guid          deviceId = Guid.NewGuid();
            string        hostname = "SESM-001";
            NetworkDevice device   = new NetworkDevice(deviceId, hostname);

            device.SetHostname("NEW");

            Assert.AreEqual(device.hostname, "NEW");
        }
Пример #24
0
        public NetworkDevice Send(NetworkDevice networkDevice, Dictionary <string, string> SettingsDict)
        {
            _sDict         = SettingsDict;
            _networkDevice = networkDevice;

            PacketSendToTelnet();  // Передаём настройки по Telnet-протоколу
            _tc.ConnectionClose(); // Закрываем Telnet-соединение

            return(networkDevice); // Возвращаем объект с заполненными свойствами полученными из коммутатора
        }
Пример #25
0
    public void PrintUsage()
    {
        TerminalCore.AddMessage("\t Shell <cmd>:");
        NetworkDevice device = TerminalNetwork.GetCurrentDevice();

        foreach (string cmd in device.GetCommands())
        {
            TerminalCore.AddMessage("\t -" + cmd);
        }
    }
        public async Task <ActionResult <NetworkDevice> > PostNetworkDevice(NetworkDevice networkDevice)
        {
            // Indicate to the database context we want to add this new record
            _context.NetworkDevices.Add(networkDevice);
            await _context.SaveChangesAsync();

            // Return a response that indicates the object was created (status code `201`) and some additional
            // headers with details of the newly created object.
            return(CreatedAtAction("GetNetworkDevice", new { id = networkDevice.Id }, networkDevice));
        }
Пример #27
0
        /// <summary>
        /// Обновляет поля модели из сетевого сервиса
        /// </summary>
        /// <param name="device"></param>
        public void UpdateDevice(NetworkDevice device)
        {
            DeviceBase dvc;

            dvc = NetworksManager.Instance.Networks[device.NetworkId]
                  .Devices[device.NodeId];
            device.Location        = dvc.LocationName;
            device.PollingInterval = dvc.PollingInterval;
            device.Status          = dvc.Status;
        }
Пример #28
0
 public static bool ContainsKey(NetworkDevice k)
 {
     foreach (var device in Keys)
     {
         if (k == device)
         {
             return(true);
         }
     }
     return(false);
 }
Пример #29
0
 public Config this[NetworkDevice key]
 {
     get
     {
         return(Get(key));
     }
     set
     {
         Values[Keys.IndexOf(key)] = value;
     }
 }
Пример #30
0
 public static bool Enable(NetworkDevice device, Address ip, Address subnet, Address gw)
 {
     if (device != null)
     {
         Config config = new Config(ip, subnet, gw);
         Network.NetworkStack.ConfigIP(device, config);
         Kernel.debugger.Send(config.ToString());
         return(true);
     }
     return(false);
 }
Пример #31
0
 public ServerConnection(NetworkDevice networkDevice)
 {
     this.networkDevice = networkDevice;
 }
Пример #32
0
 public ClientConnection(NetworkDevice clientDevice)
 {
     this.clientDevice = clientDevice;
 }
Пример #33
0
 /// <summary>
 /// Create a new instance of HostFoundArgs.
 /// </summary>
 /// <param name="device">The found device.</param>
 public HostFoundArgs(NetworkDevice device)
 {
     this.device = device;
 }