예제 #1
0
        public override bool Equals(object obj)
        {
            if (obj is null)
            {
                return(false);
            }

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

            NodeContact contact = obj as NodeContact;

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

            if (_nodeEP.Equals(contact._nodeEP))
            {
                return(true);
            }

            return(_nodeId.Equals(contact._nodeId));
        }
예제 #2
0
            public bool IsThisNetwork(BinaryNumber networkID)
            {
                if (_isResponse)
                {
                    throw new Exception("Packet is not a query.");
                }

                BinaryNumber computedHmac;

                using (HMACSHA256 hmacSHA256 = new HMACSHA256(networkID.Number))
                {
                    computedHmac = new BinaryNumber(hmacSHA256.ComputeHash(_challenge.Number)); //computed hmac
                }

                return(_hmac.Equals(computedHmac));
            }
예제 #3
0
        public static List <IPEndPoint> GetPeerEPs(BinaryNumber channelName, Connection requestingConnection)
        {
            BinaryNumber localPeerID  = requestingConnection.LocalPeerID;
            BinaryNumber remotePeerID = requestingConnection.RemotePeerID;

            lock (_relays)
            {
                foreach (KeyValuePair <BinaryNumber, TcpRelayService> itemRelay in _relays)
                {
                    BinaryNumber computedChannelName = Connection.GetChannelName(localPeerID, remotePeerID, itemRelay.Key);

                    if (computedChannelName.Equals(channelName))
                    {
                        Dictionary <BinaryNumber, Connection> relayConnections = itemRelay.Value._relayConnections;
                        List <IPEndPoint> peerEPs = new List <IPEndPoint>(relayConnections.Count);

                        lock (relayConnections)
                        {
                            foreach (KeyValuePair <BinaryNumber, Connection> itemProxyConnection in relayConnections)
                            {
                                peerEPs.Add(itemProxyConnection.Value.RemotePeerEP);
                            }
                        }

                        return(peerEPs);
                    }
                }
            }

            return(null);
        }
예제 #4
0
        public bool IsValid(SecureChannelHandshakeHello hello, byte[] masterKey)
        {
            using (MemoryStream mS = new MemoryStream(32))
            {
                hello.WriteTo(mS);
                mS.Position = 0;

                BinaryNumber computedHmac = new BinaryNumber((new HMACSHA256(masterKey)).ComputeHash(mS));
                return(_hmac.Equals(computedHmac));
            }
        }
예제 #5
0
        public override bool Equals(object obj)
        {
            if (obj is null)
            {
                return(false);
            }

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

            if (obj is DnsTSIGRecord other)
            {
                if (!_algorithmName.Equals(other._algorithmName, StringComparison.OrdinalIgnoreCase))
                {
                    return(false);
                }

                if (_timeSigned != other._timeSigned)
                {
                    return(false);
                }

                if (_fudge != other._fudge)
                {
                    return(false);
                }

                if (!BinaryNumber.Equals(_mac, other._mac))
                {
                    return(false);
                }

                if (_originalID != other._originalID)
                {
                    return(false);
                }

                if (_error != other._error)
                {
                    return(false);
                }

                if (!BinaryNumber.Equals(_otherData, other._otherData))
                {
                    return(false);
                }

                return(true);
            }

            return(false);
        }
예제 #6
0
        public static bool IsUserIdValid(byte[] publicKey, BinaryNumber userId)
        {
            if (userId.Value.Length != 20)
            {
                return(false);
            }

            byte[] random = new byte[4];
            Buffer.BlockCopy(userId.Value, 0, random, 0, 4);

            byte[] generatedValue = GenerateUserId(publicKey, random);

            return(BinaryNumber.Equals(userId.Value, generatedValue));
        }
예제 #7
0
        public override bool Equals(object obj)
        {
            if (obj == null)
            {
                return(false);
            }

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

            MeshNetworkPeerInfo objPeerInfo = obj as MeshNetworkPeerInfo;

            return(_peerUserId.Equals(objPeerInfo._peerUserId));
        }
예제 #8
0
        internal void MeshNetworkRequest(Connection connection, BinaryNumber networkId, Stream channel)
        {
            MeshNetwork network = null;

            lock (_networks)
            {
                if (_networks.ContainsKey(networkId))
                {
                    network = _networks[networkId];
                }
            }

            if (network == null)
            {
                if (!networkId.Equals(_maskedUserId))
                {
                    //no network found
                    channel.Dispose();
                    return;
                }

                //private network connection invitation attempt
                if (!_allowInboundInvitations || (_allowOnlyLocalInboundInvitations && ((connection.RemotePeerEP.AddressFamily == AddressFamily.Unspecified) || !NetUtilities.IsPrivateIP((connection.RemotePeerEP as IPEndPoint).Address))))
                {
                    //not allowed
                    channel.Dispose();
                    return;
                }

                //accept invitation
                network = MeshNetwork.AcceptPrivateNetworkInvitation(_connectionManager, connection, channel);

                //add network
                lock (_networks)
                {
                    _networks.Add(network.NetworkId, network);
                }

                //notify UI
                RaiseEventInvitationReceived(network);
            }
            else
            {
                network.AcceptConnectionAndJoinNetwork(connection, channel);
            }
        }
예제 #9
0
            public bool Equals(DiscoveryPacket obj)
            {
                if (ReferenceEquals(null, obj))
                {
                    return(false);
                }

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

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

                return(true);
            }
예제 #10
0
        public MeshNode(Stream s, string password, string profileFolder, TorController torController)
        {
            _password      = password;
            _profileFolder = profileFolder;

            switch (s.ReadByte()) //version
            {
            case 1:
                //read headers and init decryptor
                Aes decryptionAlgo = Aes.Create();
                decryptionAlgo.Key     = MeshNetwork.GetKdfValue32(Encoding.UTF8.GetBytes(password), s.ReadBytes(32), 1, 1 * 1024 * 1024); //salt
                decryptionAlgo.IV      = s.ReadBytes(16);                                                                                  //IV
                decryptionAlgo.Padding = PaddingMode.ISO10126;
                decryptionAlgo.Mode    = CipherMode.CBC;

                byte[] hmac = s.ReadBytes(32);     //hmac
                long   cipherTextStartPosition = s.Position;

                //authenticate data in Encrypt-then-MAC (EtM) mode
                using (HMAC aeHmac = new HMACSHA256(decryptionAlgo.Key))
                {
                    byte[] computedHmac = aeHmac.ComputeHash(s);

                    if (!BinaryNumber.Equals(hmac, computedHmac))
                    {
                        throw new CryptographicException("Invalid password or data tampered.");
                    }
                }

                //decrypt data and init node
                s.Position = cipherTextStartPosition;
                CryptoStream cS = new CryptoStream(s, decryptionAlgo.CreateDecryptor(), CryptoStreamMode.Read);

                InitMeshNode(new BinaryReader(cS), torController);
                break;

            case -1:
                throw new EndOfStreamException();

            default:
                throw new InvalidDataException("MeshNode format version not supported.");
            }
        }
예제 #11
0
 private void LocalDiscovery_PeerDiscovered(LocalPeerDiscovery sender, IPEndPoint peerEP, BinaryNumber networkID)
 {
     lock (_chats)
     {
         if (_chats.ContainsKey(networkID))
         {
             _chats[networkID].Network.MakeConnection(peerEP);
         }
         else
         {
             foreach (KeyValuePair <BinaryNumber, BitChat> chat in _chats)
             {
                 if (networkID.Equals(chat.Value.Network.MaskedPeerEmailAddress))
                 {
                     chat.Value.Network.SendInvitation(new IPEndPoint[] { peerEP });
                     break;
                 }
             }
         }
     }
 }
예제 #12
0
        private BitChatNetwork FindBitChatNetwork(Connection connection, BinaryNumber channelName)
        {
            //find network by channel name
            lock (_chats)
            {
                foreach (KeyValuePair <BinaryNumber, BitChat> chat in _chats)
                {
                    BitChatNetwork network = chat.Value.Network;

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

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

            return(null);
        }
예제 #13
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);
            }
예제 #14
0
        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
            BinaryNumber authHMAC = new BinaryNumber(new byte[_authHMACSize]);

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

            //verify auth hmac with computed hmac
            BinaryNumber computedAuthHMAC = new BinaryNumber(_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);
        }
예제 #15
0
        public void ReadMessage(int number, Stream output)
        {
            lock (_lock)
            {
                if (_disposed)
                {
                    return;
                }

                //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.ReadBytes(buffer, 0, 4);
                uint messageOffset = BitConverter.ToUInt32(buffer, 0);

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

                //read data
                BinaryReader bR = new BinaryReader(_data);
                byte[]       IV;
                byte[]       encryptedData;

                switch (bR.ReadByte()) //version
                {
                case 1:
                    IV            = bR.ReadBuffer();
                    encryptedData = bR.ReadBuffer();
                    byte[] aeHmac = bR.ReadBuffer();

                    //verification for authenticated encryption in Encrypt-then-MAC (EtM) mode
                    BinaryNumber computedAeHmac;

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

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

                    break;

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

                using (MemoryStream src = new MemoryStream(encryptedData, 0, encryptedData.Length))
                {
                    _crypto.IV = IV;
                    Decrypt(src, output);
                }
            }
        }
예제 #16
0
        public bool IsPskAuthValid(SecureChannelHandshakeHello serverHello, SecureChannelHandshakeHello clientHello, byte[] psk)
        {
            BinaryNumber generatedPskAuthValue = GetPskAuthValue(serverHello.SupportedCiphers, _ephemeralPublicKey, serverHello.Nonce.Value, clientHello.Nonce.Value, psk);

            return(_pskAuth.Equals(generatedPskAuthValue));
        }
예제 #17
0
        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];
                OffsetStream.StreamRead(_index, 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
                    BinaryNumber computedAeHmac;

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

                    if (!computedAeHmac.Equals(new BinaryNumber(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());
                }
            }
        }