示例#1
0
 private bool IsTokenValid(BinaryID token, IPAddress nodeIP)
 {
     if (token.Equals(GetToken(nodeIP)))
     {
         return(true);
     }
     else
     {
         return(token.Equals(GetOldToken(nodeIP)));
     }
 }
示例#2
0
        public override bool Equals(object obj)
        {
            NodeContact contact = obj as NodeContact;

            if (contact == null)
            {
                return(false);
            }

            return(_nodeID.Equals(contact._nodeID));
        }
示例#3
0
        private Connection AddConnection(Stream networkStream, BinaryID remotePeerID, IPEndPoint remotePeerEP)
        {
            lock (_connectionListByConnectionID)
            {
                //check for self
                if (_localPeerID.Equals(remotePeerID))
                {
                    _externalSelfEP = new IPEndPoint(remotePeerEP.Address, _externalSelfEP.Port);
                    return(null);
                }

                string connectionID = remotePeerEP.ToString();

                //check for existing connection by connection id
                if (_connectionListByConnectionID.ContainsKey(connectionID))
                {
                    return(null);
                }

                //check for existing connection by peer id
                if (_connectionListByPeerID.ContainsKey(remotePeerID))
                {
                    Connection existingConnection = _connectionListByPeerID[remotePeerID];

                    //compare existing and new peer ip end-point
                    if (AllowNewConnection(existingConnection.RemotePeerEP, remotePeerEP))
                    {
                        //remove existing connection and allow new connection
                        existingConnection.Dispose();
                    }
                    else
                    {
                        //keep existing connection
                        return(null);
                    }
                }

                //add connection
                Connection connection = new Connection(networkStream, remotePeerID, remotePeerEP, this, _requestHandler);
                _connectionListByConnectionID.Add(connectionID, connection);
                _connectionListByPeerID.Add(remotePeerID, connection);

                //start service
                connection.Start();

                return(connection);
            }
        }
 private void LocalDiscovery_PeerDiscovered(LocalPeerDiscovery sender, IPEndPoint peerEP, BinaryID networkID)
 {
     lock (_chats)
     {
         if (_chats.ContainsKey(networkID))
         {
             _chats[networkID].Network.MakeConnection(peerEP);
         }
         else
         {
             foreach (KeyValuePair <BinaryID, BitChat> chat in _chats)
             {
                 if (networkID.Equals(chat.Value.Network.MaskedPeerEmailAddress))
                 {
                     chat.Value.Network.SendInvitation(new IPEndPoint[] { peerEP });
                     break;
                 }
             }
         }
     }
 }
        private BitChatNetwork FindBitChatNetwork(Connection connection, BinaryID channelName)
        {
            //find network by channel name
            lock (_chats)
            {
                foreach (KeyValuePair <BinaryID, BitChat> chat in _chats)
                {
                    BitChatNetwork network = chat.Value.Network;

                    if (network.Status == BitChatNetworkStatus.Online)
                    {
                        BinaryID computedChannelName = network.GetChannelName(connection.LocalPeerID, connection.RemotePeerID);

                        if (computedChannelName.Equals(channelName))
                        {
                            return(network);
                        }
                    }
                }
            }

            return(null);
        }
示例#6
0
            public bool Equals(PeerInfo obj)
            {
                if (ReferenceEquals(null, obj))
                {
                    return(false);
                }

                if (ReferenceEquals(this, obj))
                {
                    return(true);
                }

                if (!_peerEP.Equals(obj._peerEP))
                {
                    return(false);
                }

                if (!_networkID.Equals(obj._networkID))
                {
                    return(false);
                }

                return(true);
            }
        private Connection AddConnection(Stream networkStream, BinaryID remotePeerID, IPEndPoint remotePeerEP)
        {
            if ((remotePeerEP.AddressFamily == AddressFamily.InterNetworkV6) && (remotePeerEP.Address.ScopeId != 0))
            {
                remotePeerEP = new IPEndPoint(new IPAddress(remotePeerEP.Address.GetAddressBytes()), remotePeerEP.Port);
            }

            lock (_connectionListByConnectionID)
            {
                //check for self
                if (_localPeerID.Equals(remotePeerID))
                {
                    return(null);
                }

                //check for existing connection by connection id
                if (_connectionListByConnectionID.ContainsKey(remotePeerEP))
                {
                    Connection existingConnection = _connectionListByConnectionID[remotePeerEP];

                    //check for virtual vs real connection
                    bool currentIsVirtual  = Connection.IsStreamProxyTunnelConnection(networkStream);
                    bool existingIsVirtual = existingConnection.IsProxyTunnelConnection;

                    if (existingIsVirtual && !currentIsVirtual)
                    {
                        //existing is virtual and current is real; remove existing connection
                        existingConnection.Dispose();
                    }
                    else if (currentIsVirtual)
                    {
                        //existing is real/virtual and current is virtual; keep existing connection
                        return(null);
                    }
                }
                else if (_connectionListByPeerID.ContainsKey(remotePeerID)) //check for existing connection by peer id
                {
                    Connection existingConnection = _connectionListByPeerID[remotePeerID];

                    //check for virtual vs real connection
                    bool currentIsVirtual  = Connection.IsStreamProxyTunnelConnection(networkStream);
                    bool existingIsVirtual = existingConnection.IsProxyTunnelConnection;

                    if (existingIsVirtual && !currentIsVirtual)
                    {
                        //existing is virtual and current is real; remove existing connection
                        existingConnection.Dispose();
                    }
                    else if (currentIsVirtual)
                    {
                        //existing is real/virtual and current is virtual; keep existing connection
                        return(null);
                    }
                    else
                    {
                        //compare existing and new peer ip end-point
                        if (AllowNewConnection(existingConnection.RemotePeerEP, remotePeerEP))
                        {
                            //remove existing connection and allow new connection
                            existingConnection.Dispose();
                        }
                        else
                        {
                            //keep existing connection
                            return(null);
                        }
                    }
                }

                //add connection
                Connection connection = new Connection(networkStream, remotePeerID, remotePeerEP, this);
                _connectionListByConnectionID.Add(remotePeerEP, connection);
                _connectionListByPeerID.Add(remotePeerID, connection);

                //set event handlers
                connection.BitChatNetworkInvitation     += Connection_BitChatNetworkInvitation;
                connection.BitChatNetworkChannelRequest += BitChatNetworkChannelRequest;
                connection.TcpRelayPeersAvailable       += TcpRelayPeersAvailable;
                connection.Disposed += Connection_Disposed;

                //start service
                connection.Start();

                return(connection);
            }
        }
示例#8
0
        private void _listener_ReceivedPeerInfo(IPEndPoint peerEP, byte[] challenge, BinaryID recvHMAC, bool isReply)
        {
            if (PeerDiscovered != null)
            {
                BinaryID foundNetworkID = null;

                lock (_trackedNetworkIDs)
                {
                    foreach (BinaryID networkID in _trackedNetworkIDs)
                    {
                        using (HMACSHA256 hmacSHA256 = new HMACSHA256(networkID.ID))
                        {
                            BinaryID computedHmac = new BinaryID(hmacSHA256.ComputeHash(challenge));

                            if (computedHmac.Equals(recvHMAC))
                            {
                                foundNetworkID = networkID;
                                break;
                            }
                        }
                    }
                }

                if (foundNetworkID != null)
                {
                    PeerInfo peerInfo = new PeerInfo(peerEP, foundNetworkID);

                    bool peerInCache;

                    if (_peerInfoCache.Contains(peerInfo))
                    {
                        PeerInfo existingPeerInfo = _peerInfoCache[_peerInfoCache.IndexOf(peerInfo)];

                        if (existingPeerInfo.IsExpired())
                        {
                            peerInCache = false;
                            _peerInfoCache.Remove(existingPeerInfo);
                        }
                        else
                        {
                            peerInCache = true;
                        }
                    }
                    else
                    {
                        peerInCache = false;
                    }

                    if (!peerInCache)
                    {
                        _peerInfoCache.Add(peerInfo);

                        PeerDiscovered(this, peerEP, foundNetworkID);
                    }

                    if (!isReply)
                    {
                        ThreadPool.QueueUserWorkItem(AnnounceAsync, new object[] { foundNetworkID, new IPAddress[] { peerEP.Address }, 1, true });
                    }
                }
            }
        }
        private int ReadSecureChannelPacket()
        {
            //read secure channel packet

            //read first block to read the encrypted packet size
            OffsetStream.StreamRead(_baseStream, _readEncryptedData, 0, _blockSizeBytes);
            _cryptoDecryptor.TransformBlock(_readEncryptedData, 0, _blockSizeBytes, _readBufferData, 0);
            _readBufferPosition = _blockSizeBytes;

            //read packet header 2 byte length
            int dataLength = BitConverter.ToUInt16(_readBufferData, 0);

            _readBufferLength = dataLength;

            dataLength -= _blockSizeBytes;

            if (_cryptoDecryptor.CanTransformMultipleBlocks)
            {
                if (dataLength > 0)
                {
                    int pendingBlocks = dataLength / _blockSizeBytes;

                    if (dataLength % _blockSizeBytes > 0)
                    {
                        pendingBlocks++;
                    }

                    int pendingBytes = pendingBlocks * _blockSizeBytes;

                    //read pending blocks
                    OffsetStream.StreamRead(_baseStream, _readEncryptedData, _readBufferPosition, pendingBytes);
                    _cryptoDecryptor.TransformBlock(_readEncryptedData, _readBufferPosition, pendingBytes, _readBufferData, _readBufferPosition);
                    _readBufferPosition += pendingBytes;
                }
            }
            else
            {
                while (dataLength > 0)
                {
                    //read next block
                    OffsetStream.StreamRead(_baseStream, _readEncryptedData, _readBufferPosition, _blockSizeBytes);
                    _cryptoDecryptor.TransformBlock(_readEncryptedData, _readBufferPosition, _blockSizeBytes, _readBufferData, _readBufferPosition);
                    _readBufferPosition += _blockSizeBytes;

                    dataLength -= _blockSizeBytes;
                }
            }

            //read auth hmac
            BinaryID authHMAC = new BinaryID(new byte[_authHMACSize]);

            OffsetStream.StreamRead(_baseStream, authHMAC.ID, 0, _authHMACSize);

            //verify auth hmac with computed hmac
            BinaryID computedAuthHMAC = new BinaryID(_authHMACDecrypt.ComputeHash(_readEncryptedData, 0, _readBufferPosition));

            if (!computedAuthHMAC.Equals(authHMAC))
            {
                throw new SecureChannelException(SecureChannelCode.InvalidMessageHMACReceived, _remotePeerEP, _remotePeerCert);
            }

            _readBufferPosition = 3;

            //return bytes available in this packet to read
            return(_readBufferLength - _readBufferPosition);
        }
        private int ReadSecureChannelFrame()
        {
            //read secure channel frame

            //read first block to read the encrypted packet size
            OffsetStream.StreamRead(_baseStream, _readEncryptedData, 0, _blockSizeBytes);
            _cryptoDecryptor.TransformBlock(_readEncryptedData, 0, _blockSizeBytes, _readBufferData, 0);
            _readBufferPosition = _blockSizeBytes;

            //read frame header 2 byte length
            int dataLength = BitConverter.ToUInt16(_readBufferData, 0);
            _readBufferLength = dataLength;

            dataLength -= _blockSizeBytes;

            if (_cryptoDecryptor.CanTransformMultipleBlocks)
            {
                if (dataLength > 0)
                {
                    int pendingBlocks = dataLength / _blockSizeBytes;

                    if (dataLength % _blockSizeBytes > 0)
                        pendingBlocks++;

                    int pendingBytes = pendingBlocks * _blockSizeBytes;

                    //read pending blocks
                    OffsetStream.StreamRead(_baseStream, _readEncryptedData, _readBufferPosition, pendingBytes);
                    _cryptoDecryptor.TransformBlock(_readEncryptedData, _readBufferPosition, pendingBytes, _readBufferData, _readBufferPosition);
                    _readBufferPosition += pendingBytes;
                }
            }
            else
            {
                while (dataLength > 0)
                {
                    //read next block
                    OffsetStream.StreamRead(_baseStream, _readEncryptedData, _readBufferPosition, _blockSizeBytes);
                    _cryptoDecryptor.TransformBlock(_readEncryptedData, _readBufferPosition, _blockSizeBytes, _readBufferData, _readBufferPosition);
                    _readBufferPosition += _blockSizeBytes;

                    dataLength -= _blockSizeBytes;
                }
            }

            //read auth hmac
            BinaryID authHMAC = new BinaryID(new byte[_authHMACSize]);
            OffsetStream.StreamRead(_baseStream, authHMAC.ID, 0, _authHMACSize);

            //verify auth hmac with computed hmac
            BinaryID computedAuthHMAC = new BinaryID(_authHMACDecrypt.ComputeHash(_readEncryptedData, 0, _readBufferPosition));

            if (!computedAuthHMAC.Equals(authHMAC))
                throw new SecureChannelException(SecureChannelCode.InvalidMessageHMACReceived, _remotePeerEP, _remotePeerCert);

            _readBufferPosition = 3;

            //return bytes available in this frame to read
            return _readBufferLength - _readBufferPosition;
        }
示例#11
0
            public bool IsValid(Hello hello, byte[] masterKey)
            {
                BinaryID computedHmac = new BinaryID((new HMACSHA256(masterKey)).ComputeHash(hello.ToStream()));

                return(_hmac.Equals(computedHmac));
            }
        private void _listener_ReceivedPeerInfo(IPEndPoint peerEP, byte[] challenge, BinaryID recvHMAC, bool isReply)
        {
            if (PeerDiscovered != null)
            {
                BinaryID foundNetworkID = null;

                lock (_trackedNetworkIDs)
                {
                    foreach (BinaryID networkID in _trackedNetworkIDs)
                    {
                        using (HMACSHA256 hmacSHA256 = new HMACSHA256(networkID.ID))
                        {
                            BinaryID computedHmac = new BinaryID(hmacSHA256.ComputeHash(challenge));

                            if (computedHmac.Equals(recvHMAC))
                            {
                                foundNetworkID = networkID;
                                break;
                            }
                        }
                    }
                }

                if (foundNetworkID != null)
                {
                    PeerInfo peerInfo = new PeerInfo(peerEP, foundNetworkID);

                    bool peerInCache;

                    if (_peerInfoCache.Contains(peerInfo))
                    {
                        PeerInfo existingPeerInfo = _peerInfoCache[_peerInfoCache.IndexOf(peerInfo)];

                        if (existingPeerInfo.IsExpired())
                        {
                            peerInCache = false;
                            _peerInfoCache.Remove(existingPeerInfo);
                        }
                        else
                        {
                            peerInCache = true;
                        }
                    }
                    else
                    {
                        peerInCache = false;
                    }

                    if (!peerInCache)
                    {
                        _peerInfoCache.Add(peerInfo);

                        PeerDiscovered(this, peerEP, foundNetworkID);
                    }

                    if (!isReply)
                        ThreadPool.QueueUserWorkItem(AnnounceAsync, new object[] { foundNetworkID, new IPAddress[] { peerEP.Address }, 1, true });
                }
            }
        }
        public byte[] ReadMessage(int number)
        {
            lock (_lock)
            {
                //seek to index location
                int indexPosition = number * 4;

                if (indexPosition >= _index.Length)
                {
                    throw new IOException("Cannot read message from message store: message number out of range.");
                }

                _index.Position = indexPosition;

                //read message offset
                byte[] buffer = new byte[4];
                _index.Read(buffer, 0, 4);
                uint messageOffset = BitConverter.ToUInt32(buffer, 0);

                //seek to message offset
                _data.Position = messageOffset;

                //read data
                BincodingDecoder decoder = new BincodingDecoder(_data);
                byte[]           IV;
                byte[]           encryptedData;

                switch (decoder.DecodeNext().GetByteValue()) //version
                {
                case 1:
                    IV            = decoder.DecodeNext().Value;
                    encryptedData = decoder.DecodeNext().Value;
                    byte[] aeHmac = decoder.DecodeNext().Value;

                    //verify hmac
                    BinaryID computedAeHmac;

                    using (HMAC hmac = new HMACSHA256(_key))
                    {
                        computedAeHmac = new BinaryID(hmac.ComputeHash(encryptedData));
                    }

                    if (!computedAeHmac.Equals(new BinaryID(aeHmac)))
                    {
                        throw new CryptoException("Cannot read message from message store: message is corrupt or tampered.");
                    }

                    break;

                default:
                    throw new IOException("Cannot read message from message store: message version not supported.");
                }

                using (MemoryStream mS = new MemoryStream(encryptedData.Length))
                {
                    using (MemoryStream src = new MemoryStream(encryptedData, 0, encryptedData.Length))
                    {
                        _crypto.IV = IV;
                        _crypto.Decrypt(src, mS);
                    }

                    return(mS.ToArray());
                }
            }
        }