Example #1
0
        void HandleSubscribe(XElement Node)
        {
            if (OnSubscribe == null)
            {
                return;
            }

            JID From = new JID(Node.Attribute("from").Value);
            SubscribeResponse Action = OnSubscribe.Invoke(From);

            if (Action == SubscribeResponse.Reject)
            {
                return;
            }

            XElement PresenceTag = new XElement("presence");

            PresenceTag.SetAttributeValue("to", From.GetBareJID());
            PresenceTag.SetAttributeValue("type", "subscribed");
            Uplink.GetNetworkClient().WriteTextToSocket(PresenceTag.ToString());

            if (Action == SubscribeResponse.Allow)
            {
                return;
            }

            Subscribe(From);
        }
Example #2
0
        public void Unsubscribe(JID To)
        {
            XElement PresenceTag = new XElement("presence");

            PresenceTag.SetAttributeValue("to", To.GetBareJID());
            PresenceTag.SetAttributeValue("type", "unsubscribe");
            Uplink.GetNetworkClient().WriteTextToSocket(PresenceTag.ToString());
        }
Example #3
0
        private void ProcessLanConnections(object no)
        {
            while (run)
            {
                List <DetectedNode> localNodes = peerFinder.Peers.ToList();

                foreach (DetectedNode peer in localNodes)
                {
                    if (peer.Address == serverNode.Location)
                    {
                        continue;
                    }

                    //If not already connected to that peer then connect
                    if (extOverlordServers.ToList().Where(o => o.Destination.Location == peer.Address).Count() == 0)
                    {
                        logger.Debug("Server connecting as client to external overlord at {0}", peer.Address);
                        var verb = new ConnectVerb();
                        verb.Address    = serverNode.Location;
                        verb.ClientType = ClientType.Overlord;
                        verb.Secret     = IDService.CreateID();

                        var uplink = new Uplink(model.LocalNode,
                                                new Node
                        {
                            ID       = peer.OverlordID,
                            Location = peer.Address,
                            NodeType = ClientType.Overlord,
                            Secret   = verb.Secret
                        });
                        extOverlordServers.Add(uplink);


                        var client = new Client(serverNode);
                        if (client.Execute(verb, peer.Address, 5000))
                        {
                            //Connected as client on an external overlord

                            uplink.OnDisconnect += uplink_OnDisconnect;

                            uplink.Start();
                            logger.Debug("Server connected to client to external overlord at {0}", peer.Address);
                            break;
                        }
                        else
                        {
                            //Failed to connect ot the external overlord
                            logger.Debug("Server failed to connect to external overlord at {0}", peer.Address);
                            peerFinder.RemovePeer(peer);
                            extOverlordServers.Remove(uplink);
                        }
                    }
                }
                Thread.Sleep(3000);
            }
        }
Example #4
0
        static void Main(string[] args)
        {
            // TODO - change with your decryptor
            IDecryptor decryptor = null;
            var        uplink    = new Uplink(decryptor);

            var results = uplink.Run();

            results.ForEach(Console.WriteLine);

            Console.WriteLine("\nPress Enter to exit...");
            Console.ReadLine();
        }
Example #5
0
    public void UpdateInformation()
    {
        UplinkMarker uplinkMarker = _uplinkObject.GetComponent <UplinkMarker>();
        Uplink       uplink       = uplinkMarker.uplink;
        string       text         = $"Id: {uplink.id}\n" +
                                    $"Name: {uplink.name}\n" +
                                    $"Org: {uplink.org}\n" +
                                    $"Site: {uplink.site}\n" +
                                    $"WAN: {uplink.wan}\n" +
                                    $"Appliance: {uplink.node}";
        TextMesh textMesh = GetComponent <TextMesh>();

        textMesh.text = text;
    }
Example #6
0
            public override void Begin()
            {
                //string Request = MyJID.GetBareJID();
                //Request = Convert.ToBase64String(Encoding.UTF8.GetBytes(Request));

                // Todo: Check if Subject alt name contains a jid or many, if so we need to set the jid here (Request) otherwise empty (=).
                string AuthXML = string.Empty;

                AuthXML += "<auth xmlns='urn:ietf:params:xml:ns:xmpp-sasl' mechanism='EXTERNAL'>";
                AuthXML += "=";
                AuthXML += "</auth>";

                Uplink.WriteTextToSocket(AuthXML);
            }
Example #7
0
            public override void Begin()
            {
                SelectedNounce = "arne";                 // Guid.NewGuid().ToString();
                string Request = "n,,n=" + MyJID.GetUsername() + ",r=" + SelectedNounce;

                /*char[] outArray = new char[1024];
                 *              int nrTotal = Convert.ToBase64CharArray(tempbuff, 0, offset, outArray, 0);
                 *              string EncodedResponse = new string(outArray, 0, nrTotal);*/

                Request = Convert.ToBase64String(Encoding.UTF8.GetBytes((Request)),
                                                 Base64FormattingOptions.None);

                string AuthXML = string.Empty;

                AuthXML += "<auth xmlns='urn:ietf:params:xml:ns:xmpp-sasl' mechanism='SCRAM-SHA-1'>";                // << std::endl;
                AuthXML += Request;
                AuthXML += "</auth>";

                Uplink.WriteTextToSocket(AuthXML);
            }
Example #8
0
 public void OnPointerUp(PointerEventData eventData)
 {
     // Create uplink if selecting site
     if (_stateManager.currentMode != StateManagerMode.Delete)
     {
         if (_stateManager.currentObjectHover && _stateManager.currentObjectHover.tag == _siteLayer)
         {
             GameObject currentSite = _stateManager.currentObjectHover;
             _uplinks.Add(_currentUplinkCreation);
             string siteId = currentSite.GetComponent <SiteMarker>().site.id;
             Debug.Log($"Creating uplink {_currentUplinkCreation} from WAN: {wan.id} to site:{siteId}");
             _uplinkCreationInProgress = _currentUplinkCreation;
             // Create uplink API call
             _steelConnect.CreateUplink(wan.id, siteId)
             .Then(response => {
                 Uplink uplinkResponse = JsonUtility.FromJson <Uplink>(response.Text);
                 Debug.Log($"Uplink created {uplinkResponse.id} from WAN: {wan.id} to site:{siteId}");
                 UplinkMarker uplinkMarker = _uplinkCreationInProgress.GetComponent <UplinkMarker>();
                 GameObject line           = _uplinkCreationInProgress.transform.Find("Line").gameObject;
                 line.GetComponent <BoxCollider>().enabled = true;
                 uplinkMarker.created     = true;
                 uplinkMarker.uplink.id   = uplinkResponse.id;
                 uplinkMarker.uplink.name = uplinkResponse.name;
                 uplinkMarker.uplink.node = uplinkResponse.node;
                 uplinkMarker.uplink.org  = uplinkResponse.org;
                 uplinkMarker.uplink.site = uplinkResponse.site;
                 uplinkMarker.uplink.wan  = uplinkResponse.wan;
                 uplinkMarker.UpdateInformation();
                 uplinkMarker.wan  = gameObject;
                 uplinkMarker.site = currentSite;
                 _uplinkCreationInProgress.transform.parent = uplinks.transform;
                 _uplinkCreationInProgress = null;
             });
         }
         else
         {
             Destroy(_currentUplinkCreation);
         }
         _currentUplinkCreation = null;
     }
 }
Example #9
0
                public override void Begin()
                {
                    string ManagedString_authid  = MyJID.GetUsername();
                    string ManagedString_authzid = "";

                    byte [] tempbuff = new byte[1024];
                    int     offset   = 0;

                    byte[] authzid  = Encoding.UTF8.GetBytes(ManagedString_authzid);
                    byte[] authid   = Encoding.UTF8.GetBytes(ManagedString_authid);
                    byte[] password = Encoding.UTF8.GetBytes(Password);

                    memcpy(tempbuff, offset, authzid, authzid.Length);

                    offset            += authzid.Length;
                    tempbuff[offset++] = 0;

                    memcpy(tempbuff, offset, authid, authid.Length);
                    offset            += authid.Length;
                    tempbuff[offset++] = 0;

                    memcpy(tempbuff, offset, password, password.Length);
                    offset += password.Length;

                    char[] outArray        = new char[1024];
                    int    nrTotal         = Convert.ToBase64CharArray(tempbuff, 0, offset, outArray, 0);
                    string EncodedResponse = new string(outArray, 0, nrTotal);

                    string AuthXML = string.Empty;

                    AuthXML += "<auth xmlns='urn:ietf:params:xml:ns:xmpp-sasl' mechanism='PLAIN'>";                    // << std::endl;
                    AuthXML += EncodedResponse;
                    AuthXML += "</auth>";

                    //std::string blaha = AuthXML.str();
                    Uplink.WriteTextToSocket(AuthXML);
                }
Example #10
0
        private void uplink_OnDisconnect(Uplink s)
        {
            //A remote overlord has disconnected, notify local clients of all associated peering going offline.
            lock (sync)
            {
                logger.Debug("Server had uplink disconnect to {0}", s.Destination.ID);
                extOverlordServers.Remove(s);
                var verb = new UpdateVerb();
                foreach (Node node in externalNodes.ToList())
                {
                    if (node.OverlordID == s.Destination.ID || node.ID == s.Destination.ID)
                    {
                        //Check the node isnt now logged on locally
                        if (connectedClientNodes.Where(n => n.Node.ID == node.ID).Count() > 0)
                        {
                            continue;
                        }
                        verb.Nodes.Add(new Node {
                            ID = node.ID, Online = false
                        });
                    }
                    externalNodes.Remove(node);
                }
                verb.Nodes.Add(new Node {
                    ID = s.Destination.ID, Online = false
                });
                NetworkRequest req = verb.CreateRequest();
                req.OverlordID = serverNode.ID;
                SendToStandardClients(req);

                //Remove the overlord itself
                if (extOverlordServers.Contains(s))
                {
                    extOverlordServers.Remove(s);
                }
            }
        }
Example #11
0
            public override void Challenge(XElement Challenge)
            {
                //string ChallengeBase64 = "cj1hcm5lV21qejZsQkI5ZmxjUWtld09rWnNYQT09LHM9ZEVPaUhHaC9KRVRIc2xKcGZVY2FBZz09LGk9NDA5Ng=="; //Challenge.Value;
                string ChallengeBase64  = Challenge.Value;
                string DecodedChallenge = Encoding.UTF8.GetString(
                    Convert.FromBase64String(ChallengeBase64));

                string[] SplittedChallenge = DecodedChallenge.Split(',');

                Dictionary <string, string> ChallengeMap = new Dictionary <string, string>();

                foreach (string str in SplittedChallenge)
                {
                    string[] SplittedSplit = str.Split(new char[] { '=' }, 2);
                    ChallengeMap[SplittedSplit[0]] = SplittedSplit[1];
                }
                string r = ChallengeMap["r"];
                string s = ChallengeMap["s"];
                string i = ChallengeMap["i"];

                int    NrNrIterations = Convert.ToInt32(i);
                string n = MyJID.GetUsername();

                byte[] SaltBytes = new byte[1024];
                byte[] DecodedS  = Convert.FromBase64String(s);
                memcpy(SaltBytes, 0, DecodedS, DecodedS.Length);
                SaltBytes[DecodedS.Length]     = 0;
                SaltBytes[DecodedS.Length + 1] = 0;
                SaltBytes[DecodedS.Length + 2] = 0;
                SaltBytes[DecodedS.Length + 3] = 1;

                string c = "biws";


                HMACSHA1 hmacFromPassword = new HMACSHA1(Encoding.UTF8.GetBytes(Password));

                byte[] Result   = hmacFromPassword.ComputeHash(SaltBytes, 0, DecodedS.Length + 4);
                byte[] Previous = (byte[])Result.Clone();

                for (int j = 1; j < NrNrIterations; j++)
                {
                    byte[] tmp = hmacFromPassword.ComputeHash(Previous);
                    for (int k = 0; k < tmp.Length; k++)
                    {
                        Result[k]   = (byte)(Result[k] ^ tmp[k]);
                        Previous[k] = tmp[k];
                    }
                }
                HMACSHA1 hmacFromSaltedPassword = new HMACSHA1(Result);

                byte[] ClientKey = hmacFromSaltedPassword.ComputeHash(Encoding.UTF8.GetBytes("Client Key"));
                SHA1   hash      = SHA1.Create();

                byte[] StoredKey = hash.ComputeHash(ClientKey);

                string AuthMessage = string.Format("n={0},r={1},{2},c={3},r={4}",
                                                   n,
                                                   SelectedNounce,
                                                   DecodedChallenge,
                                                   c,
                                                   r);


                HMACSHA1 hmacFromStoredKey = new HMACSHA1(StoredKey);

                byte[] ClientSignature = hmacFromStoredKey.ComputeHash(Encoding.UTF8.GetBytes(AuthMessage));
                byte[] ClientProof     = new byte[ClientSignature.Length];

                for (int k = 0; k < ClientSignature.Length; k++)
                {
                    ClientProof[k] = (byte)(ClientKey[k] ^ ClientSignature[k]);
                }

                byte[] ServerKey = hmacFromSaltedPassword.ComputeHash(Encoding.UTF8.GetBytes("Server Key"));

                HMACSHA1 hmacFromServerKey = new HMACSHA1(ServerKey);

                byte[] ServerSignature = hmacFromServerKey.ComputeHash(Encoding.UTF8.GetBytes(AuthMessage));
                ServerProof = Convert.ToBase64String(ServerSignature, Base64FormattingOptions.None);

                string proof               = Convert.ToBase64String(ClientProof, Base64FormattingOptions.None);
                string InnerResponse       = string.Format("c={0},r={1},p={2}", c, r, proof);
                string Base64InnerResponse = Convert.ToBase64String(Encoding.UTF8.GetBytes(InnerResponse));
                string Response            = string.Format("<response xmlns='urn:ietf:params:xml:ns:xmpp-sasl'>{0}</response>", Base64InnerResponse);

                Uplink.WriteTextToSocket(Response);
            }
Example #12
0
        /// <summary>
        /// Handle updates from local clients, external overlords and peers on external overlords from their overlord.
        /// </summary>
        /// <param name="e"></param>
        /// <param name="req"></param>
        /// <returns></returns>
        private bool HandleUpdate(RequestEventArgs e, NetworkRequest req)
        {
            try
            {
                var verb = new UpdateVerb();
                verb.ProcessRequest(req);

                //Ignore updates about ourself
                if (verb.Nodes != null && verb.Nodes.Count == 1 && verb.Nodes[0].ID == serverNode.ID)
                {
                    SendResponse(e, null);
                    return(true);
                }

                //Is the call from a local client?
                ClientStream localClient =
                    connectedClientNodes.ToList().Where(
                        n =>
                        n.Node.ID == req.SourceID && n.Node.Secret == req.AuthKey &&
                        n.Node.NodeType != ClientType.Overlord).FirstOrDefault();
                if (null != localClient)
                {
                    //Only allow updates about itself
                    Node client = verb.Nodes.Where(n => n.ID == localClient.Node.ID).FirstOrDefault();
                    if (null != client && verb.Nodes.Count == 1)
                    {
                        logger.Trace("Server got update from local client {0}", client.ID);
                        lock (sync)
                        {
                            //Copy to local store
                            foreach (var value in verb.Nodes[0].Data)
                            {
                                localClient.Node.SetData(value.Key, value.Value);
                            }

                            req.OverlordID = serverNode.ID;
                            //Retransmit
                            SendToOverlordClients(req);
                            SendToStandardClients(req);

                            //Has the client disconnected?
                            if (!localClient.Node.Online)
                            {
                                localClient.Kill();
                                connectedClientNodes.Remove(localClient);
                            }
                        }
                        SendResponse(e, null);
                        return(true);
                    }
                }
                else
                {
                    //Is the update from an external overlord?
                    Uplink overlord =
                        extOverlordServers.ToList().Where(
                            n =>
                            n.Destination.ID == req.OverlordID && n.Destination.Secret == req.AuthKey &&
                            n.Destination.NodeType == ClientType.Overlord).FirstOrDefault();
                    if (null != overlord)
                    {
                        logger.Trace("Server got update from external overlord {0}", overlord.Destination.ID);
                        //Check each update
                        var nverb = new UpdateVerb();
                        foreach (Node update in verb.Nodes)
                        {
                            if (!string.IsNullOrEmpty(update.ID))
                            {
                                //Ignore updates about ourself
                                if (update.ID == serverNode.ID)
                                {
                                    continue;
                                }

                                lock (sync)
                                {
                                    //Is the update about the overlord itself?
                                    Uplink osearch =
                                        extOverlordServers.Where(
                                            o => o.Destination.ID == update.ID && o.Destination.Secret == req.AuthKey).
                                        FirstOrDefault();
                                    if (null != osearch)
                                    {
                                        logger.Trace("Server got update from external about itself: {0}",
                                                     osearch.Destination.ID);
                                        //Copy to local store
                                        foreach (var value in update.Data)
                                        {
                                            osearch.Destination.SetData(value.Key, value.Value);
                                        }
                                        //Retransmit changes
                                        nverb.Nodes.Add(update);

                                        //Overlord going offline
                                        if (!osearch.Destination.Online)
                                        {
                                            osearch.OnDisconnect -= uplink_OnDisconnect;
                                            osearch.Kill();

                                            //Remove associated external nodes
                                            foreach (Node enode in externalNodes.ToList())
                                            {
                                                if (enode.OverlordID == osearch.Destination.OverlordID)
                                                {
                                                    externalNodes.Remove(enode);
                                                    //Only signal disconnect is the node isnt a local node
                                                    //I.e. they connected locally without disconnecting externally.
                                                    ClientStream search =
                                                        connectedClientNodes.Where(n => n.Node.ID == enode.ID).
                                                        FirstOrDefault();
                                                    if (null == search)
                                                    {
                                                        //The node isn't connected locally, is it connected elsewhere externally?
                                                        Node bestExternal =
                                                            externalNodes.ToList().Where(n => n.ID == enode.ID).
                                                            OrderByDescending(n => n.LastUpdate).FirstOrDefault();
                                                        if (null != bestExternal)
                                                        {
                                                            //User has logged on elsewhere, update local clients of new details
                                                            nverb.Nodes.Add(bestExternal);
                                                        }
                                                        else
                                                        {
                                                            nverb.Nodes.Add(new Node {
                                                                ID = enode.ID, Online = false
                                                            });
                                                        }
                                                    }
                                                }
                                            }
                                        }
                                    }
                                    else
                                    {
                                        logger.Trace("Server got update from external server about : {0}", update.ID);

                                        //Check to see if the external node is connected locally, if so then dont retransmit changes but store changes under the relevant object
                                        ClientStream localNode =
                                            connectedClientNodes.Where(n => n.Node.ID == update.ID).FirstOrDefault();

                                        //Update about an external node from an external overlord
                                        Node search =
                                            externalNodes.Where(n => n.ID == update.ID && n.OverlordID == req.OverlordID)
                                            .FirstOrDefault();
                                        if (null == search)
                                        {
                                            if (!string.IsNullOrEmpty(update.ID))
                                            {
                                                //New external node
                                                search = new Node();
                                                //Copy to local store
                                                foreach (var value in update.Data)
                                                {
                                                    search.SetData(value.Key, value.Value);
                                                }
                                                search.OverlordID = req.OverlordID;
                                                externalNodes.Add(search);
                                                //Dont retransmit external node as it is local
                                                if (null == localNode)
                                                {
                                                    nverb.Nodes.Add(update);
                                                }
                                            }
                                        }
                                        else
                                        {
                                            //Copy to local store
                                            foreach (var value in update.Data)
                                            {
                                                search.SetData(value.Key, value.Value);
                                            }
                                            //Has the external node changed to a different overlord?
                                            if (search.OverlordID != req.OverlordID)
                                            {
                                                search.OverlordID = req.OverlordID;
                                                update.OverlordID = req.OverlordID;
                                            }
                                            //Dont retransmit external node as it is local
                                            if (null == localNode)
                                            {
                                                //Retransmit changes
                                                nverb.Nodes.Add(update);
                                            }
                                        }
                                    }
                                }
                            }
                        }
                        //Only transmit external node info to local clients
                        if (nverb.Nodes.Count > 0)
                        {
                            NetworkRequest nreq = nverb.CreateRequest();
                            nreq.OverlordID = req.OverlordID;
                            SendToStandardClients(nreq);
                        }
                        SendResponse(e, null);
                        return(true);
                    }
                }
            }
            catch
            {
            }
            logger.Debug("Server received an invalid update");
            SendError(e);
            return(false);
        }