Ejemplo n.º 1
0
        protected void RaiseMessageReceived(NetMQFrame topic, NetMQFrame value)
        {
            var          handler = MessageReceived;
            MessageTopic mt      = (MessageTopic)Enum.Parse(typeof(MessageTopic), topic.ConvertToString());

            handler?.Invoke(this, new StockTVMessageReceivedEventArgs(mt, value.ToByteArray(true)));
        }
Ejemplo n.º 2
0
        public NetMQMessage DecryptApplicationMessage([NotNull] NetMQMessage cipherMessage)
        {
            if (!SecureChannelReady)
            {
                throw new NetMQSecurityException(NetMQSecurityErrorCode.SecureChannelNotReady, "Cannot decrypt messages until the secure channel is ready");
            }

            if (cipherMessage == null)
            {
                throw new ArgumentNullException("cipherMessage");
            }

            if (cipherMessage.FrameCount < 2)
            {
                throw new NetMQSecurityException(NetMQSecurityErrorCode.InvalidFramesCount, "cipher message should have at least 2 frames");
            }

            NetMQFrame protocolVersionFrame = cipherMessage.Pop();
            NetMQFrame contentTypeFrame     = cipherMessage.Pop();

            if (!protocolVersionFrame.ToByteArray().SequenceEqual(m_protocolVersion))
            {
                throw new NetMQSecurityException(NetMQSecurityErrorCode.InvalidProtocolVersion, "Wrong protocol version");
            }

            ContentType contentType = (ContentType)contentTypeFrame.Buffer[0];

            if (contentType != ContentType.ApplicationData)
            {
                throw new NetMQSecurityException(NetMQSecurityErrorCode.InvalidContentType, "Not an applicagtion data message");
            }

            return(m_recordLayer.DecryptMessage(ContentType.ApplicationData, cipherMessage));
        }
Ejemplo n.º 3
0
        public override void SetFromNetMQMessage(NetMQMessage message)
        {
            base.SetFromNetMQMessage(message);

            if (message.FrameCount != 3)
            {
                throw new NetMQSecurityException(NetMQSecurityErrorCode.InvalidFramesCount, "Malformed message");
            }

            // get the randon number
            NetMQFrame randomNumberFrame = message.Pop();

            RandomNumber = randomNumberFrame.ToByteArray();

            // get the length of the ciphers array
            NetMQFrame ciphersLengthFrame = message.Pop();
            int        ciphersLength      = BitConverter.ToInt32(ciphersLengthFrame.Buffer, 0);

            // get the ciphers
            NetMQFrame ciphersFrame = message.Pop();

            CipherSuites = new CipherSuite[ciphersLength];
            for (int i = 0; i < ciphersLength; i++)
            {
                CipherSuites[i] = (CipherSuite)ciphersFrame.Buffer[i * 2 + 1];
            }
        }
Ejemplo n.º 4
0
        public bool ProcessMessage(NetMQMessage incomingMessage, IList <NetMQMessage> outgoingMesssages)
        {
            ContentType contentType = ContentType.Handshake;

            if (incomingMessage != null)
            {
                NetMQFrame protocolVersionFrame = incomingMessage.Pop();
                byte[]     protocolVersionBytes = protocolVersionFrame.ToByteArray();

                if (protocolVersionBytes.Length != 2)
                {
                    throw new NetMQSecurityException(NetMQSecurityErrorCode.InvalidFrameLength, "Wrong length for protocol version frame");
                }

                if (!protocolVersionBytes.SequenceEqual(m_protocolVersion))
                {
                    throw new NetMQSecurityException(NetMQSecurityErrorCode.InvalidProtocolVersion, "Wrong protocol version");
                }

                NetMQFrame contentTypeFrame = incomingMessage.Pop();

                if (contentTypeFrame.MessageSize != 1)
                {
                    throw new NetMQSecurityException(NetMQSecurityErrorCode.InvalidFrameLength, "wrong length for message size");
                }

                contentType = (ContentType)contentTypeFrame.Buffer[0];

                if (contentType != ContentType.ChangeCipherSpec && contentType != ContentType.Handshake)
                {
                    throw new NetMQSecurityException(NetMQSecurityErrorCode.InvalidContentType, "Unkown content type");
                }

                if (ChangeSuiteChangeArrived)
                {
                    incomingMessage = m_recordLayer.DecryptMessage(contentType, incomingMessage);
                }
            }

            bool result = false;

            if (contentType == ContentType.Handshake)
            {
                result = m_handshakeLayer.ProcessMessages(incomingMessage, m_outgoingMessageBag);

                foreach (NetMQMessage outgoingMesssage in m_outgoingMessageBag.Messages)
                {
                    outgoingMesssages.Add(outgoingMesssage);
                }

                m_outgoingMessageBag.Clear();
            }
            else
            {
                ChangeSuiteChangeArrived = true;
            }

            return(SecureChannelReady = result && ChangeSuiteChangeArrived);
        }
Ejemplo n.º 5
0
        /// <summary>
        /// Remove the two frames from the given NetMQMessage, interpreting them thusly:
        /// 1. a byte with the HandshakeType, assumed to be ClientKeyExchange
        /// 2. a byte-array containing the EncryptedPreMasterSecret.
        /// </summary>
        /// <param name="message">a NetMQMessage - which must have 2 frames</param>
        /// <exception cref="NetMQSecurityException"><see cref="NetMQSecurityErrorCode.InvalidFramesCount"/>: FrameCount must be 1.</exception>
        public override void SetFromNetMQMessage(NetMQMessage message)
        {
            if (message.FrameCount != 1)
            {
                throw new NetMQSecurityException(NetMQSecurityErrorCode.InvalidFramesCount, "Malformed message");
            }

            NetMQFrame preMasterSecretFrame = message.Pop();

            EncryptedPreMasterSecret = preMasterSecretFrame.ToByteArray();
        }
Ejemplo n.º 6
0
        /// <summary>
        /// Remove the two frames from the given NetMQMessage, interpreting them thusly:
        /// 1. a byte with the HandshakeType,
        /// 2. a byte-array containing the verification data - used to verify the integrity of the content.
        /// </summary>
        /// <param name="message">a NetMQMessage - which must have 2 frames</param>
        /// <exception cref="NetMQSecurityException"><see cref="NetMQSecurityErrorCode.InvalidFramesCount"/>: FrameCount must be 1.</exception>
        public override void SetFromNetMQMessage(NetMQMessage message)
        {
            base.SetFromNetMQMessage(message);

            if (message.FrameCount != 1)
            {
                throw new NetMQSecurityException(NetMQSecurityErrorCode.InvalidFramesCount, "Malformed message");
            }

            NetMQFrame verifyDataFrame = message.Pop();

            VerifyData = verifyDataFrame.ToByteArray();
        }
Ejemplo n.º 7
0
        /// <summary>
        /// Remove the two frames from the given NetMQMessage, interpreting them thusly:
        /// 1. a byte with the HandshakeType,
        /// 2. a byte-array containing the X.509 digital certificate.
        /// </summary>
        /// <param name="message">a NetMQMessage - which must have 2 frames</param>
        /// <exception cref="NetMQSecurityException"><see cref="NetMQSecurityErrorCode.InvalidFramesCount"/>: FrameCount must be 1.</exception>
        public override void SetFromNetMQMessage(NetMQMessage message)
        {
            if (message.FrameCount != 1)
            {
                throw new NetMQSecurityException(NetMQSecurityErrorCode.InvalidFramesCount, "Malformed message");
            }

            NetMQFrame certificateFrame = message.Pop();

            byte[] certificateBytes = certificateFrame.ToByteArray();

            Certificate = new X509Certificate2();
            Certificate.Import(certificateBytes);
        }
Ejemplo n.º 8
0
        /// <summary>
        /// Remove the three frames from the given NetMQMessage, interpreting them thusly:
        /// 1. a byte with the <see cref="HandshakeType"/>,
        /// 2. RandomNumber (a byte-array),
        /// 3. a 2-byte array with the <see cref="CipherSuite"/> in the 2nd byte.
        /// </summary>
        /// <param name="message">a NetMQMessage - which must have 3 frames</param>
        /// <exception cref="NetMQSecurityException"><see cref="NetMQSecurityErrorCode.InvalidFramesCount"/>: FrameCount must be 2.</exception>
        public override void SetFromNetMQMessage(NetMQMessage message)
        {
            base.SetFromNetMQMessage(message);

            if (message.FrameCount != 2)
            {
                throw new NetMQSecurityException(NetMQSecurityErrorCode.InvalidFramesCount, "Malformed message");
            }

            // Get the random number
            NetMQFrame randomNumberFrame = message.Pop();

            RandomNumber = randomNumberFrame.ToByteArray();

            // Get the cipher suite
            NetMQFrame cipherSuiteFrame = message.Pop();

            CipherSuite = (CipherSuite)cipherSuiteFrame.Buffer[1];
        }
Ejemplo n.º 9
0
        /// <summary>
        /// Create a new Message instance.
        /// </summary>
        /// <param name="message">Instance of NetMQMessage class.</param>
        public Message(NetMQMessage message)
        {
            if (message.FrameCount == 4)
            {
                Topic = message.Pop().ConvertToString();

                Id = message.Pop();

                NetMQFrame data = message.Pop();
                Data.MergeFrom(data.ToByteArray());

                Bytes = message.Pop();
            }
            else
            {
                Topic = message.Pop().ConvertToString();

                NetMQFrame data = message.Pop();
                Data.MergeFrom(data.ToByteArray());

                Bytes = message.Pop();
            }
        }
Ejemplo n.º 10
0
        /// <summary>
        /// Remove the three frames from the given NetMQMessage, interpreting them thusly:
        /// 1. a byte with the <see cref="HandshakeType"/>,
        /// 2. RandomNumber (a byte-array),
        /// 3. a 2-byte array with the <see cref="CipherSuite"/> in the 2nd byte.
        /// </summary>
        /// <param name="message">a NetMQMessage - which must have 3 frames</param>
        /// <exception cref="NetMQSecurityException"><see cref="NetMQSecurityErrorCode.InvalidFramesCount"/>: FrameCount must be 2.</exception>
        public override void SetFromNetMQMessage(NetMQMessage message)
        {
            if (message.FrameCount != 5)
            {
                throw new NetMQSecurityException(NetMQSecurityErrorCode.InvalidFramesCount, "Malformed message");
            }

            // Get the random number
            NetMQFrame randomNumberFrame = message.Pop();

            RandomNumber = randomNumberFrame.ToByteArray();

            NetMQFrame sessionIdLengthFrame = message.Pop();
            NetMQFrame sessionIdFrame       = message.Pop();

            SessionID = sessionIdFrame.ToByteArray();
            // Get the cipher suite
            NetMQFrame cipherSuiteFrame = message.Pop();

            CipherSuite = (CipherSuite)cipherSuiteFrame.Buffer[1];

            NetMQFrame compressionMethod = message.Pop();
        }
Ejemplo n.º 11
0
        /// <summary>
        /// Remove the three frames from the given NetMQMessage, interpreting them thusly:
        /// 1. a byte with the HandshakeType, presumed here to be ClientHello,
        /// 2. a byte-array containing the RandomNumber,
        /// 3. a byte-array with the list of CipherSuites.
        /// </summary>
        /// <param name="message">a NetMQMessage - which must have 2 frames</param>
        /// <exception cref="NetMQSecurityException"><see cref="NetMQSecurityErrorCode.InvalidFramesCount"/>: FrameCount must be 3.</exception>
        public override void SetFromNetMQMessage(NetMQMessage message)
        {
            if (message.FrameCount != 5)
            {
                throw new NetMQSecurityException(NetMQSecurityErrorCode.InvalidFramesCount, "Malformed message");
            }
            // get the random number
            NetMQFrame randomNumberFrame = message.Pop();

            RandomNumber = randomNumberFrame.ToByteArray();
            NetMQFrame sessionIdLengthFrame = message.Pop();
            NetMQFrame sessionIdFrame       = message.Pop();

            this.SessionID = sessionIdFrame.ToByteArray();
            //若为空则需要初始话一个新的sessionid
            if (this.SessionID.Length == 0)
            {
                this.SessionID = Encoding.ASCII.GetBytes(Guid.NewGuid().ToString("N"));
            }

            // get the length of the cipher-suites array
            NetMQFrame ciphersLengthFrame = message.Pop();

            byte[] temp = new byte[2];
            temp[1] = ciphersLengthFrame.Buffer[0];
            temp[0] = ciphersLengthFrame.Buffer[1];
            int ciphersLength = BitConverter.ToUInt16(temp, 0) / 2;

            // get the cipher-suites
            NetMQFrame ciphersFrame = message.Pop();

            CipherSuites = new CipherSuite[ciphersLength];
            for (int i = 0; i < ciphersLength; i++)
            {
                CipherSuites[i] = (CipherSuite)ciphersFrame.Buffer[i * 2 + 1];
            }
        }
Ejemplo n.º 12
0
        /// <summary>
        /// Remove the three frames from the given NetMQMessage, interpreting them thusly:
        /// 1. a byte with the HandshakeType, presumed here to be ClientHello,
        /// 2. a byte-array containing the RandomNumber,
        /// 3. a byte-array with the list of CipherSuites.
        /// </summary>
        /// <param name="message">a NetMQMessage - which must have 2 frames</param>
        /// <exception cref="NetMQSecurityException"><see cref="NetMQSecurityErrorCode.InvalidFramesCount"/>: FrameCount must be 3.</exception>

        public override void SetFromNetMQMessage(NetMQMessage message)
        {
            if (message.FrameCount != 9)
            {
                throw new NetMQSecurityException(NetMQSecurityErrorCode.InvalidFramesCount, "Malformed message");
            }
            // get the random number
            NetMQFrame randomNumberFrame = message.Pop();

            RandomNumber = randomNumberFrame.ToByteArray();

            NetMQFrame sessionIdLengthFrame = message.Pop();
            NetMQFrame sessionIdFrame       = message.Pop();

            SessionID = sessionIdFrame.ToByteArray();
            // get the length of the cipher-suites array
            NetMQFrame ciphersLengthFrame = message.Pop();

            byte[] temp = new byte[2];
            temp[1] = ciphersLengthFrame.Buffer[0];
            temp[0] = ciphersLengthFrame.Buffer[1];
            int ciphersLength = BitConverter.ToUInt16(temp, 0) / 2;

            // get the cipher-suites
            NetMQFrame ciphersFrame = message.Pop();

            CipherSuites = new CipherSuite[ciphersLength];
            for (int i = 0; i < ciphersLength; i++)
            {
                CipherSuites[i] = (CipherSuite)ciphersFrame.Buffer[i * 2 + 1];
            }
            NetMQFrame compressionMethodLength = message.Pop();
            NetMQFrame compressionMethod       = message.Pop();
            NetMQFrame extensionsLength        = message.Pop();
            NetMQFrame extensions = message.Pop();
        }
Ejemplo n.º 13
0
        public NetMQMessage DecryptMessage(ContentType contentType, NetMQMessage cipherMessage)
        {
            if (SecurityParameters.BulkCipherAlgorithm == BulkCipherAlgorithm.Null &&
                SecurityParameters.MACAlgorithm == MACAlgorithm.Null)
            {
                return(cipherMessage);
            }

            if (cipherMessage.FrameCount < 2)
            {
                throw new NetMQSecurityException(NetMQSecurityErrorCode.InvalidFramesCount, "cipher message should have at least 2 frames, iv and sequence number");
            }

            NetMQFrame ivFrame = cipherMessage.Pop();

            m_decryptionBulkAlgorithm.IV = ivFrame.ToByteArray();

            using (var decryptor = m_decryptionBulkAlgorithm.CreateDecryptor())
            {
                NetMQMessage plainMessage = new NetMQMessage();

                NetMQFrame seqNumFrame = cipherMessage.Pop();

                byte[] frameBytes;
                byte[] seqNumMAC;
                byte[] padding;

                DecryptBytes(decryptor, seqNumFrame.ToByteArray(), out frameBytes, out seqNumMAC, out padding);

                ulong seqNum     = BitConverter.ToUInt64(frameBytes, 0);
                int   frameCount = BitConverter.ToInt32(frameBytes, 8);

                int frameIndex = 0;

                ValidateBytes(contentType, seqNum, frameIndex, frameBytes, seqNumMAC, padding);

                if (CheckReplayAttack(seqNum))
                {
                    throw new NetMQSecurityException(NetMQSecurityErrorCode.ReplayAttack,
                                                     "Message already handled or very old message, might be under replay attack");
                }

                if (frameCount != cipherMessage.FrameCount)
                {
                    throw new NetMQSecurityException(NetMQSecurityErrorCode.EncryptedFramesMissing, "Frames was removed from the encrypted message");
                }

                frameIndex++;

                foreach (NetMQFrame cipherFrame in cipherMessage)
                {
                    byte[] data;
                    byte[] mac;

                    DecryptBytes(decryptor, cipherFrame.ToByteArray(), out data, out mac, out padding);
                    ValidateBytes(contentType, seqNum, frameIndex, data, mac, padding);

                    frameIndex++;

                    plainMessage.Append(data);
                }

                return(plainMessage);
            }
        }
Ejemplo n.º 14
0
 private static byte[] GetFromFrameByteArray(NetMQFrame frame)
 {
     return(frame.ToByteArray());
 }
Ejemplo n.º 15
0
        public static NetMQMessage Encode(ZreMessage msg)
        {
            var message = new NetMQMessage();
            var frameSize = 2 + 1;  //  Signature and message ID

            switch (msg._id)
            {
                case ZreMessageType.Hello:
                //  version is a 1-byte integer
                frameSize += 1;
                //  sequence is a 2-byte integer
                frameSize += 2;
                //  endpoint is a string with 1-byte length
                frameSize++;       //  Size is one octet
                if (!string.IsNullOrEmpty(msg._endpoint))
                {
                    frameSize += msg._endpoint.Length;
                }
                //  groups is an array of strings
                frameSize += 4;    //  Size is 4 octets
                if (msg._groups != null && msg._groups.Count > 0)
                {
                    //  Add up size of list contents
                    foreach (var @group in msg._groups)
                    {
                        frameSize += 4 + @group.Length;
                    }
                }
                //  status is a 1-byte integer
                frameSize += 1;
                //  name is a string with 1-byte length
                frameSize++;       //  Size is one octet
                if (!string.IsNullOrEmpty(msg._name))
                {
                    frameSize += msg._name.Length;
                }
                //  headers is an array of key=value strings
                frameSize += 4;    //  Size is 4 octets
                if (msg._headers != null && msg._headers.Count > 0)
                {
                    msg._headersBytes = 0;
                    //  Add up size of dictionary contents
                    foreach (var header in msg._headers)
                    {
                        msg._headersBytes += 1 + header.Key.Length;
                        msg._headersBytes += 4 + header.Value.Length;
                    }
                }
                frameSize += msg._headersBytes;
                break;

                case ZreMessageType.Whisper:
                //  version is a 1-byte integer
                frameSize += 1;
                //  sequence is a 2-byte integer
                frameSize += 2;
                break;

                case ZreMessageType.Shout:
                //  version is a 1-byte integer
                frameSize += 1;
                //  sequence is a 2-byte integer
                frameSize += 2;
                //  group is a string with 1-byte length
                frameSize++;       //  Size is one octet
                if (!string.IsNullOrEmpty(msg._group))
                {
                    frameSize += msg._group.Length;
                }
                break;

                case ZreMessageType.Join:
                //  version is a 1-byte integer
                frameSize += 1;
                //  sequence is a 2-byte integer
                frameSize += 2;
                //  group is a string with 1-byte length
                frameSize++;       //  Size is one octet
                if (!string.IsNullOrEmpty(msg._group))
                {
                    frameSize += msg._group.Length;
                }
                //  status is a 1-byte integer
                frameSize += 1;
                break;

                case ZreMessageType.Leave:
                //  version is a 1-byte integer
                frameSize += 1;
                //  sequence is a 2-byte integer
                frameSize += 2;
                //  group is a string with 1-byte length
                frameSize++;       //  Size is one octet
                if (!string.IsNullOrEmpty(msg._group))
                {
                    frameSize += msg._group.Length;
                }
                //  status is a 1-byte integer
                frameSize += 1;
                break;

                case ZreMessageType.Ping:
                //  version is a 1-byte integer
                frameSize += 1;
                //  sequence is a 2-byte integer
                frameSize += 2;
                break;

                case ZreMessageType.PingOk:
                //  version is a 1-byte integer
                frameSize += 1;
                //  sequence is a 2-byte integer
                frameSize += 2;
                break;
            }

            var frame = new NetMQFrame(frameSize);
            msg._needle = frame.ToByteArray();
            msg._needleReader = new BinaryReader(new MemoryStream(msg._needle));
            msg._needleWriter = new BinaryWriter(new MemoryStream(msg._needle));
            msg._needleWriter.PutNumber2(0xAAA0 | ZreConstants.ProtocolSignature);
            msg._needleWriter.PutNumber1((byte)msg._id);
            switch (msg._id)
            {
                case ZreMessageType.Hello:
                msg._needleWriter.PutNumber1(ZreConstants.ProtocolVersion);
                msg._needleWriter.PutNumber2(msg._sequence);
                if (!string.IsNullOrEmpty(msg._endpoint))
                {
                    msg._needleWriter.PutString(msg._endpoint);
                }
                else
                {
                    msg._needleWriter.PutNumber1(0);    //  Empty string
                }

                if (msg._groups != null)
                {
                    msg._needleWriter.PutNumber4(msg._groups.Count);
                    foreach (var @group in msg._groups)
                    {
                        msg._needleWriter.PutLongString(@group);
                    }
                }
                else
                {
                    msg._needleWriter.PutNumber4(0);    //  Empty string array
                }

                msg._needleWriter.PutNumber1(msg._status);

                if (!string.IsNullOrEmpty(msg._name))
                {
                    msg._needleWriter.PutString(msg._name);
                }
                else
                {
                    msg._needleWriter.PutNumber1(0);    //  Empty string
                }

                if (msg._headers != null)
                {
                    msg._needleWriter.PutNumber4(msg._headers.Count);
                    foreach (var header in msg._headers)
                    {
                        msg._needleWriter.PutString(header.Key);
                        msg._needleWriter.PutLongString(header.Value);
                    }
                }
                else
                {
                    msg._needleWriter.PutNumber4(0);    //  Empty dictionary
                }
                break;

                case ZreMessageType.Whisper:
                msg._needleWriter.PutNumber1(ZreConstants.ProtocolVersion);
                msg._needleWriter.PutNumber2(msg._sequence);
                break;

                case ZreMessageType.Shout:
                msg._needleWriter.PutNumber1(ZreConstants.ProtocolVersion);
                msg._needleWriter.PutNumber2(msg._sequence);
                if (!string.IsNullOrEmpty(msg._group))
                {
                    msg._needleWriter.PutString(msg._group);
                }
                else
                {
                    msg._needleWriter.PutNumber1(0);    //  Empty string
                }
                break;

                case ZreMessageType.Join:
                msg._needleWriter.PutNumber1(ZreConstants.ProtocolVersion);
                msg._needleWriter.PutNumber2(msg._sequence);
                if (!string.IsNullOrEmpty(msg._group))
                {
                    msg._needleWriter.PutString(msg._group);
                }
                else
                {
                    msg._needleWriter.PutNumber1(0);    //  Empty string
                }
                msg._needleWriter.PutNumber1(msg._status);
                break;

                case ZreMessageType.Leave:
                msg._needleWriter.PutNumber1(ZreConstants.ProtocolVersion);
                msg._needleWriter.PutNumber2(msg._sequence);
                if (!string.IsNullOrEmpty(msg._group))
                {
                    msg._needleWriter.PutString(msg._group);
                }
                else
                {
                    msg._needleWriter.PutNumber1(0);    //  Empty string
                }
                msg._needleWriter.PutNumber1(msg._status);
                break;

                case ZreMessageType.Ping:
                msg._needleWriter.PutNumber1(ZreConstants.ProtocolVersion);
                msg._needleWriter.PutNumber2(msg._sequence);
                break;

                case ZreMessageType.PingOk:
                msg._needleWriter.PutNumber1(ZreConstants.ProtocolVersion);
                msg._needleWriter.PutNumber2(msg._sequence);
                break;
            }

            //  Now send the data frame
            message.Append(frame);

            //  Now send the message field if there is any
            if (msg._id == ZreMessageType.Whisper)
            {
                if (msg._content != null && !msg._content.IsEmpty)
                {
                    while (!msg._content.IsEmpty)
                    {
                        var contentFrame = msg._content.Pop();
                        message.Append(contentFrame);
                    }
                }
                else
                {
                    message.AppendEmptyFrame();
                }
            }
            //  Now send the message field if there is any
            if (msg._id == ZreMessageType.Shout)
            {
                if (msg._content != null && !msg._content.IsEmpty)
                {
                    while (!msg._content.IsEmpty)
                    {
                        var contentFrame = msg._content.Pop();
                        message.Append(contentFrame);
                    }
                }
                else
                {
                    message.AppendEmptyFrame();
                }
            }

            return message;
        }
Ejemplo n.º 16
0
 public static HashDigest <T> ConvertToHashDigest <T>(
     this NetMQFrame frame)
     where T : HashAlgorithm
 {
     return(new HashDigest <T>(frame.ToByteArray()));
 }
Ejemplo n.º 17
0
 public static BlockHash ConvertToBlockHash(this NetMQFrame frame) =>
 new BlockHash(frame.ToByteArray());
Ejemplo n.º 18
0
 public static TxId ConvertToTxId(this NetMQFrame frame)
 {
     return(new TxId(frame.ToByteArray()));
 }
Ejemplo n.º 19
0
        /// <summary>
        /// Process handshake and change cipher suite messages. This method should be called for every incoming message until the method returns true.
        /// You cannot encrypt or decrypt messages until the method return true.
        /// Each call to the method may include outgoing messages that need to be sent to the other peer.
        /// </summary>
        /// <param name="incomingMessage">the incoming message from the other peer</param>
        /// <param name="outgoingMesssages">the list of outgoing messages that need to be sent to the other peer</param>
        /// <returns>true when the method completes the handshake stage and the SecureChannel is ready to encrypt and decrypt messages</returns>
        /// <exception cref="NetMQSecurityException">NetMQSecurityErrorCode.InvalidContentType: Unknown content type.</exception>
        /// <exception cref="NetMQSecurityException">NetMQSecurityErrorCode.InvalidFrameLength: Wrong length for protocol version frame.</exception>
        /// <exception cref="NetMQSecurityException">NetMQSecurityErrorCode.InvalidFrameLength: Wrong length for message size.</exception>
        /// <exception cref="NetMQSecurityException">NetMQSecurityErrorCode.InvalidProtocolVersion: Wrong protocol version.</exception>
        /// <remarks>
        /// Note: Within this library, this method is ONLY called from within the unit-tests.
        /// </remarks>
        public bool ProcessMessage(NetMQMessage incomingMessage, IList <NetMQMessage> outgoingMesssages)
        {
#if DEBUG
            if (incomingMessage != null)
            {
                Debug.WriteLine("[record layer(" + incomingMessage.Sum(f => f.BufferSize) + ")]");
            }
#endif
            ContentType contentType = ContentType.Handshake;

            if (incomingMessage != null)
            {
                // Verify that the first two frames are the protocol-version and the content-type,

                NetMQFrame contentTypeFrame = incomingMessage.Pop();

                if (contentTypeFrame.MessageSize != 1)
                {
                    throw new NetMQSecurityException(NetMQSecurityErrorCode.InvalidFrameLength, "wrong length for Content Type  size");
                }

                // Verify that the content-type is either handshake, or change-cipher-suit..
                contentType = (ContentType)contentTypeFrame.Buffer[0];

                if (contentType != ContentType.ChangeCipherSpec && contentType != ContentType.Handshake && contentType != ContentType.Alert)
                {
                    throw new NetMQSecurityException(NetMQSecurityErrorCode.InvalidContentType, "Unknown content type");
                }
                NetMQFrame protocolVersionFrame = incomingMessage.Pop();
                byte[]     protocolVersionBytes = protocolVersionFrame.ToByteArray();

                if (protocolVersionBytes.Length != 2)
                {
                    throw new NetMQSecurityException(NetMQSecurityErrorCode.InvalidFrameLength, "Wrong length for protocol version frame");
                }
                if (n_ConnectionEnd == ConnectionEnd.Server && contentType == ContentType.Handshake)
                {
                    //第一次握手时
                    if (ProtocolVersion == null)
                    {
                        //校验记录层版本号是否支持
                        if (Constants.SupposeVersions.Any(p => p.SequenceEqual(protocolVersionBytes)))
                        {
                            //支持版本
                            ProtocolVersion = protocolVersionBytes;
                        }
                        else
                        {
                            throw new NetMQSecurityException(NetMQSecurityErrorCode.InvalidFrameLength, "the protocol version is not supposed");
                        }
                    }
                }
                //作为服务端首次接收到客户端
                if (!protocolVersionBytes.SequenceEqual(ProtocolVersion))
                {
                    throw new NetMQSecurityException(NetMQSecurityErrorCode.InvalidProtocolVersion, "Wrong protocol version");
                }
                RemoveLength(incomingMessage);
                if (ChangeSuiteChangeArrived)
                {
                    RecordLayer.SetSubProtocolVersion(m_handshakeLayer.SubProtocolVersion);

                    //已经收到ChangeCipherSuite,接下来就是Finish
                    //Finished报文是第一个解密报文。需要解密。
                    incomingMessage = RecordLayer.DecryptMessage(contentType, incomingMessage);
                }
                if (contentType == ContentType.Alert)
                {
                    throw new NetMQSecurityException(NetMQSecurityErrorCode.HandshakeException, "peer response alert[" + (AlertDescription)incomingMessage.Last.Buffer[0] + "]");
                }
            }
            else
            {
                //作为客户端确定使用的版本号,后续客户端和服务端通讯都要校验版本号一致性。
                //客户端使用3,3版本
                ProtocolVersion = GetVersion(Configuration.StandardTLSFormat);
            }

            bool result = false;
            if (contentType == ContentType.Handshake)
            {
                result         = m_handshakeLayer.ProcessMessages(incomingMessage, m_outgoingMessageBag);
                this.SessionId = m_handshakeLayer.SessionID;
                if (m_outgoingMessageBag.Messages.Count() > 1)
                {
                    // Move the messages from the saved list over to the outgoing Messages collection..
                    foreach (NetMQMessage outgoingMesssage in m_outgoingMessageBag.Messages)
                    {
                        outgoingMesssages.Add(outgoingMesssage);
                    }
                }
                else
                {
                    // Move the messages from the saved list over to the outgoing Messages collection..
                    foreach (NetMQMessage outgoingMesssage in m_outgoingMessageBag.Messages)
                    {
                        outgoingMesssages.Add(outgoingMesssage);
                    }
                }
                m_outgoingMessageBag.Clear();
            }
            else
            {
                ////每个record计数都+1
                //RecordLayer.GetAndIncreaseReadSequneceNumber();
                //接下去的是Finished,需要加密。
                ChangeSuiteChangeArrived = true;
            }

            return(SecureChannelReady = result && ChangeSuiteChangeArrived);
        }
Ejemplo n.º 20
0
    //Poll the buffer as long as there is new data. If there is new data return true, otherwise return false.
    //Only the last data sample is kept!
    public bool getNewestData(out T output)
    {
        if (client != null)
        {
            bool newDataAvailable = false;

            //note: if there is a situation where a huge backlog exists, add timeOut/System.Diagnostics.Stopwatch and do polling over multiple Unity frames
            //System.Diagnostics.Stopwatch sw = new System.Diagnostics.Stopwatch();
            //sw.Start();

            //not sure what happens inside Poll, but if data is available getData is called immediately and the code continues in the while loop body
            while (client.Poll(TimeSpan.Zero)) //try to poll data, but don't wait if there is none
            {
                newDataAvailable = true;       //we have found new data in this frame

                /*if(sw.ElapsedMilliseconds>timeOut)//check time
                 * {
                 *  //if time is up, stop the clock and break
                 *  sw.Stop ();
                 *  break;
                 * }*/
            }

            //if new data was received, deserialize it and return
            if (newDataAvailable)
            {
                NetMQFrame frame = msg.Pop();

                lastData = ProtoBuf.Serializer.Deserialize <T>(new System.IO.MemoryStream(frame.ToByteArray()));
            }

            output = lastData;


            return(newDataAvailable);
        }
        output = lastData;
        return(false);
    }