Exemple #1
0
        public void Test()
        {
            StaticDns dns = new StaticDns(
                MemBlock.Reference(Utils.StringToBytes("10.250.0.0", '.')),
                MemBlock.Reference(Utils.StringToBytes("255.255.0.0", '.')),
                string.Empty, false);

            Assert.AreEqual(dns.NameLookUp("10.250.1.1"), "C250001001.ipop", "NameLookUp Dns set in range.");

            try {
                Assert.AreEqual(dns.NameLookUp("10.251.1.1"), null, "NameLookUp Dns set out of range.");
            } catch { }

            Assert.AreEqual(dns.AddressLookUp("C250001001.ipop"), "10.250.1.1", "AddressLookUp Dns set.");

            try {
                Assert.AreEqual(dns.AddressLookUp("C250001001.blaha"), null, "AddressLookUp Dns set bad dns name: blaha.");
            } catch { }

            try {
                Assert.AreEqual(dns.AddressLookUp("C250001001.blah"), null, "AddressLookUp Dns set bad dns name: blah.");
            } catch { }

            dns = new StaticDns(
                MemBlock.Reference(Utils.StringToBytes("10.251.0.0", '.')),
                MemBlock.Reference(Utils.StringToBytes("255.255.0.0", '.')),
                string.Empty, false);

            try {
                Assert.AreEqual(dns.NameLookUp("10.250.1.1"), null, "NameLookUp Dns changed out of range.");
            } catch { }

            Assert.AreEqual(dns.NameLookUp("10.251.1.1"), "C251001001.ipop", "NameLookUp Dns changed in range.");
        }
Exemple #2
0
        /// <summary>Always returns the oldest non-tunnel address.</summary>
        public virtual Address EvaluatePotentialOverlap(IDictionary msg)
        {
            Address oldest_addr = null;
            int     oldest_age  = -1;

            foreach (DictionaryEntry de in msg)
            {
                MemBlock key = de.Key as MemBlock;
                if (key == null)
                {
                    key = MemBlock.Reference((byte[])de.Key);
                }
                Address addr = new AHAddress(key);

                Hashtable values = de.Value as Hashtable;
                TransportAddress.TAType tatype =
                    TransportAddressFactory.StringToType(values["ta"] as string);

                if (tatype.Equals(TransportAddress.TAType.Tunnel))
                {
                    continue;
                }

                int age = (int)values["ct"];
                if (age > oldest_age)
                {
                    oldest_addr = addr;
                }
            }

            return(oldest_addr);
        }
Exemple #3
0
        public void TestPrimitiveTypes()
        {
            ArrayList expected_values = new ArrayList();
            MemBlock  e_mb            = MemBlock.Reference(Encoding.UTF8.GetBytes("test memblock"));

            expected_values.Add(e_mb);
            float e_f = (float)Math.PI;

            expected_values.Add((double)e_f);
            ushort e_sh = 11;

            expected_values.Add(e_sh);
            ulong e_long = 11111111111;

            expected_values.Add(e_long);
            uint e_ui = 34;

            expected_values.Add(e_ui);
            _mrm.CurrentInvokeState.RetValues = expected_values.ToArray();
            string target = this.GetRandomNodeAddr();

            object[] ret    = this._rpc.proxy(target, 3, -1, "Foo");
            byte[]   actual = (byte[])ret[0];
            Assert.IsTrue(e_mb.Equals(actual));
            float a_f = Convert.ToSingle((double)ret[1]);

            Assert.AreEqual(e_f, a_f);
        }
Exemple #4
0
        public void MDnsATest()
        {
            String Name = "david-laptop.local";

            DnsPacket.Types Type       = DnsPacket.Types.A;
            bool            CacheFlush = true;

            DnsPacket.Classes Class = DnsPacket.Classes.IN;
            int      Ttl            = 120;
            String   RData          = "10.227.56.136";
            Response rp             = new Response(Name, Type, Class, CacheFlush, Ttl, RData);

            MemBlock am = MemBlock.Reference(new byte[] { 0x0c, 0x64, 0x61, 0x76,
                                                          0x69, 0x64, 0x2d, 0x6c, 0x61, 0x70, 0x74, 0x6f, 0x70, 0x05, 0x6c, 0x6f,
                                                          0x63, 0x61, 0x6c, 0x00, 0x00, 0x01, 0x80, 0x01, 0x00, 0x00, 0x00, 0x78,
                                                          0x00, 0x04, 0x0a, 0xe3, 0x38, 0x88 });

            Response rm = new Response(am, 0);

            Assert.AreEqual(rp.Packet, am, "Packet");
            Assert.AreEqual(rm.Name, Name, "Name");
            Assert.AreEqual(rm.Type, Type, "Type");
            Assert.AreEqual(rm.Class, Class, "Class");
            Assert.AreEqual(rm.CacheFlush, CacheFlush, "CacheFlush");
            Assert.AreEqual(rm.Ttl, Ttl, "Ttl");
            Assert.AreEqual(rm.RData, RData, "RData");
        }
Exemple #5
0
        public IcmpPacket(Types type, short id, short seq_num)
        {
            Type           = type;
            Identifier     = id;
            SequenceNumber = seq_num;
            Code           = (byte)0;

            byte[] msg  = new byte[64];
            Random rand = new Random();

            rand.NextBytes(msg);
            msg[0] = (byte)type;
            msg[1] = Code;
            msg[2] = (byte)0;
            msg[3] = (byte)0;


            NumberSerializer.WriteShort(Identifier, msg, 4);
            NumberSerializer.WriteShort(SequenceNumber, msg, 6);

            short checksum = (short)IPPacket.GenerateChecksum(MemBlock.Reference(msg));

            NumberSerializer.WriteShort(checksum, msg, 2);

            _icpacket = MemBlock.Reference(msg);
            _packet   = MemBlock.Reference(msg);
        }
Exemple #6
0
        /// <summary>Tasks that should be performed during startup until completion
        /// and repetitive tasks are added here.
        protected void CheckNode(object o, EventArgs ea)
        {
            lock (_sync) {
                if (_dhcp_config == null)
                {
                    GetDhcpConfig();
                    if (_dhcp_config == null)
                    {
                        return;
                    }
                }

                // The rest doesn't quite work right yet...
                DateTime now = DateTime.UtcNow;
                if ((now - _last_check_node).TotalSeconds < 30)
                {
                    return;
                }
                _last_check_node = now;
            }

            // Discover machines in on the LAN if they respond to ICMP requests
            WaitCallback wcb = delegate(object obj) {
                SendIcmpRequest(MemBlock.Reference(_dhcp_server.Broadcast));
            };

            ThreadPool.QueueUserWorkItem(wcb);
        }
        /** Parse without looking at the cache
         */
        protected static Address NoCacheParse(string ascii)
        {
            string[] parts = ascii.Split(':');
            //It should be:  urn:brunet:node:[encoded address]
            // or brunet:node:[encoded address]
            int offset = 0;

            if (parts[0].ToLower() == "urn")
            {
                offset = 1;
            }
            string brunet = parts[offset].ToLower();

            if (brunet != "brunet")
            {
                throw new ParseException
                          ("String is not a properly formated Brunet Address:" + ascii);
            }
            string node = parts[offset + 1].ToLower();

            if (node != "node")
            {
                throw new ParseException
                          ("String is not a properly formated Brunet Address:" + ascii);
            }
            try {
                byte[]   binadd = Base32.Decode(parts[offset + 2]);
                MemBlock mb     = MemBlock.Reference(binadd);
                return(Parse(mb));
            }
            catch (System.ArgumentOutOfRangeException ex) {
                throw new ParseException("Failed to parse Address string",
                                         ex);
            }
        }
Exemple #8
0
        public AHHeader(short hops, short ttl, Address source, Address dest, ushort options)
        {
            //Make the header part:
            byte[] header = new byte[LENGTH];
            int    offset = 0;

            //Write hops:
            NumberSerializer.WriteShort(hops, header, offset);
            Hops    = hops;
            offset += 2;

            NumberSerializer.WriteShort(ttl, header, offset);
            Ttl     = ttl;
            offset += 2;

            _src    = source;
            offset += source.CopyTo(header, offset);

            _dest   = dest;
            offset += dest.CopyTo(header, offset);

            Opts = options;
            NumberSerializer.WriteShort((short)options, header, offset);
            offset += 2;

            _data = MemBlock.Reference(header, 0, offset);
        }
Exemple #9
0
        public void TestLongTest()
        {
            var docs      = new DtlsOverlordClientServer(false, true, true, 0);
            var to_server = docs.Client.CreateSecurityAssociation(docs.ToServer) as DtlsAssociation;

            Assert.AreEqual(to_server.State, SecurityAssociation.States.Active, "Client.State == SslState.OK");

            byte[]        msg  = new byte[1024];
            System.Random rand = new System.Random();
            rand.NextBytes(msg);
            MemBlock mmsg0 = MemBlock.Reference(msg);

            msg = new byte[1024];
            rand.NextBytes(msg);
            MemBlock mmsg1 = MemBlock.Reference(msg);

            Assert.AreEqual(to_server.SslState, SslState.OK, "Client.State == SslState.OK");

            for (int i = 0; i < Int16.MaxValue; i++)
            {
                if (i % 2 == 0)
                {
                    to_server.Send(mmsg0);
                    Assert.AreEqual(docs.ServerIn.LastReceived, mmsg0, "Client -> Server");
                }
                else
                {
                    to_server.Send(mmsg1);
                    Assert.AreEqual(docs.ServerIn.LastReceived, mmsg1, "Client -> Server");
                }
            }
        }
Exemple #10
0
        public void TestRecall()
        {
            Random r = new Random();

            System.Collections.Hashtable ht = new System.Collections.Hashtable();
            for (int i = 0; i < 128; i++)
            {
                byte[] key_buf = new byte[r.Next(1024)];
                r.NextBytes(key_buf);
                MemBlock key     = MemBlock.Reference(key_buf);
                byte[]   val_buf = new byte[r.Next(1024)];
                r.NextBytes(val_buf);
                MemBlock val = MemBlock.Reference(val_buf);

                MemBlock old_v = Swap(key, val);
                ht[key] = val;
                Assert.IsNull(old_v, "old value is null");
            }

            foreach (System.Collections.DictionaryEntry de in ht)
            {
                MemBlock recall_v = Read((MemBlock)de.Key);
                Assert.AreEqual(recall_v, de.Value, "check recall");
            }
        }
Exemple #11
0
        public void Testdaap()
        {
            MemBlock mdnsm = MemBlock.Reference(new byte[] { 0x00, 0x00, 0x00, 0x00,
                                                             0x00, 0x01, 0x00, 0x00, 0x00, 0x01, 0x00, 0x00, 0x10, 0x50, 0x69, 0x65,
                                                             0x72, 0x72, 0x65, 0x27, 0x73, 0x20, 0x4C, 0x69, 0x62, 0x72, 0x61, 0x72,
                                                             0x79, 0x05, 0x5F, 0x64, 0x61, 0x61, 0x70, 0x04, 0x5F, 0x74, 0x63, 0x70,
                                                             0x05, 0x6C, 0x6F, 0x63, 0x61, 0x6C, 0x00, 0x00, 0xFF, 0x00, 0x01, 0xC0,
                                                             0x0C, 0x00, 0x21, 0x00, 0x01, 0x00, 0x00, 0x00, 0x78, 0x00, 0x0D, 0x00,
                                                             0x00, 0x00, 0x00, 0x0E, 0x69, 0x04, 0x50, 0x49, 0x42, 0x4D, 0xC0,
                                                             0x2 });
            DnsPacket mdns = new DnsPacket(mdnsm);

            Assert.AreEqual(mdns.Questions.Length, 1, "Questions");
            Assert.AreEqual(mdns.Answers.Length, 0, "Answers");
            Assert.AreEqual(mdns.Authority.Length, 1, "Authority");
            Assert.AreEqual(mdns.Additional.Length, 0, "Additional");

            Assert.AreEqual(mdns.Questions[0].QNameBlob,
                            MemBlock.Reference(new byte[] { 0x10, 0x50, 0x69, 0x65, 0x72, 0x72, 0x65,
                                                            0x27, 0x73, 0x20, 0x4C, 0x69, 0x62, 0x72, 0x61, 0x72, 0x79, 0x05, 0x5F,
                                                            0x64, 0x61, 0x61, 0x70, 0x04, 0x5F, 0x74, 0x63, 0x70, 0x05, 0x6C, 0x6F,
                                                            0x63, 0x61, 0x6C, 0x00 }), "QName");
            Assert.AreEqual(mdns.Questions[0].QType, (DnsPacket.Types) 0xFF, "QType");
            Assert.AreEqual(mdns.Questions[0].QClass, DnsPacket.Classes.IN, "QClass");
        }
Exemple #12
0
        public void TestResponse()
        {
            byte[] response = new byte[] { 0x01, 0x01, 0x00, 0x18, 0x21, 0x12, 0xa4,
                                           0x42, 0x99, 0x7b, 0x63, 0x08, 0x17, 0x9d, 0x00, 0xbc, 0xe9, 0xb5, 0x9f,
                                           0x57, 0x00, 0x01, 0x00, 0x08, 0x00, 0x01, 0xe1, 0x6e, 0x46, 0xb9, 0x63,
                                           0xb6, 0x00, 0x04, 0x00, 0x08, 0x00, 0x01, 0x4b, 0x66, 0x4a, 0x7d, 0x5f,
                                           0x7e };
            MemBlock   resp    = MemBlock.Reference(response);
            StunPacket from_mb = new StunPacket(resp);

            List <StunPacket.Attribute> attrs = new List <StunPacket.Attribute>(2);

            attrs.Add(new StunPacket.AttributeAddress(
                          StunPacket.Attribute.AttributeType.MappedAddress,
                          IPAddress.Parse("70.185.99.182"),
                          57710));
            attrs.Add(new StunPacket.AttributeAddress(
                          StunPacket.Attribute.AttributeType.SourceAddress,
                          IPAddress.Parse("74.125.95.126"),
                          19302));
            StunPacket from_input = new StunPacket(StunPacket.ClassType.Response,
                                                   StunPacket.MessageType.Binding, attrs);

            from_input = new StunPacket(from_input.Data);

            Assert.AreEqual(from_mb.Attributes.Count, from_input.Attributes.Count, "Attributes");
            for (int i = 0; i < from_mb.Attributes.Count; i++)
            {
                Assert.AreEqual(from_mb.Attributes[i].Data, from_input.Attributes[i].Data, "Attribute " + i);
            }
            Assert.AreEqual(from_mb.Message, from_input.Message, "Message");
            Assert.AreEqual(from_mb.Class, from_input.Class, "Class");
            Assert.AreEqual(from_mb.Data.Length, from_input.Data.Length, "Length");
        }
Exemple #13
0
            /// <summary>Converts an attribute into a specific type if a parser exists
            /// for it, otherwise stuffs it into a generic Attribute object.</summary>
            public static Attribute Parse(MemBlock data)
            {
                if (4 > data.Length)
                {
                    throw new Exception("Poorly formed packet");
                }
                ushort type   = (ushort)NumberSerializer.ReadShort(data, 0);
                ushort length = (ushort)NumberSerializer.ReadShort(data, 2);

                if (4 + length > data.Length)
                {
                    throw new Exception("Poorly formed packet");
                }
                MemBlock att_data = MemBlock.Reference(data, 4, length);

                AttributeType attype = (AttributeType)type;

                if (attype == AttributeType.MappedAddress ||
                    attype == AttributeType.ResponseAddress ||
                    attype == AttributeType.ChangeAddress ||
                    attype == AttributeType.SourceAddress)
                {
                    return(new AttributeAddress(attype, att_data));
                }

                switch (attype)
                {
                default:
                    return(new Attribute(attype, att_data));
                }
            }
Exemple #14
0
        public void TestSend()
        {
            var fp = FragPipe.Instance;

            var head_c = new HeaderChop(new PType("frag").ToMemBlock());

            fp.Subscribe(head_c, null);

            var fh = new FragmentingHandler(1000);

            head_c.Subscribe(fh, null);

            var th = new TestHandler();

            fh.Subscribe(th, null);
            head_c.WithoutHeader.Subscribe(th, null);

            var fs = new FragmentingSender(100, fp);
            var r  = new System.Random();

            for (int length = 1; length < 10000; length++)
            {
                var buf = new byte[length];
                r.NextBytes(buf);
                var dat = MemBlock.Reference(buf);
                fs.Send(dat); //This will do the assert.
                Assert.AreEqual(dat, th.LastData, "Data was received");
            }
        }
        public void Test()
        {
            MemBlock mdnsm = MemBlock.Reference(new byte[] { 0x00, 0x00, 0x00, 0x00,
                                                             0x00, 0x01, 0x00, 0x00, 0x00, 0x01, 0x00, 0x00, 0x0E, 0x64, 0x61, 0x76,
                                                             0x69, 0x64, 0x69, 0x77, 0x2D, 0x6C, 0x61, 0x70, 0x74, 0x6F, 0x70, 0x05,
                                                             0x6C, 0x6F, 0x63, 0x61, 0x6C, 0x00, 0x00, 0xFF, 0x00, 0x01, 0xC0, 0x0C,
                                                             0x00, 0x01, 0x00, 0x01, 0x00, 0x00, 0x00, 0x78, 0x00, 0x04, 0x0A, 0xFE,
                                                             0x00, 0x01 });
            DnsPacket mdns   = new DnsPacket(mdnsm);
            String    ss_ip  = "10.254.112.232";
            bool      change = MDnsTranslator.mDnsTranslate(mdns.Answers, ss_ip);

            change |= MDnsTranslator.mDnsTranslate(mdns.Authority, ss_ip);
            change |= MDnsTranslator.mDnsTranslate(mdns.Additional, ss_ip);
            // If we make a change let's make a new packet!
            if (change)
            {
                mdns = new DnsPacket(mdns.ID, mdns.Query, mdns.Opcode, mdns.AA,
                                     mdns.RA, mdns.RD, mdns.Questions, mdns.Answers,
                                     mdns.Authority, mdns.Additional);
            }
            Assert.AreEqual(mdns.Authority[0].Name, "davidiw-laptop.local", "Name");
            Assert.AreEqual(mdns.Authority[0].Type, DnsPacket.Types.A, "Type");
            Assert.AreEqual(mdns.Authority[0].Class, DnsPacket.Classes.IN, "Class");
            Assert.AreEqual(mdns.Authority[0].CacheFlush, false, "CacheFlush");
            Assert.AreEqual(mdns.Authority[0].Ttl, 120, "Ttl");
            Assert.AreEqual(mdns.Authority[0].RData, "10.254.112.232", "RData");
        }
Exemple #16
0
        /// <summary>3a) Receive a DHEWithCertificate, verify the certificate and DHE and
        /// send a Confirm that you are ready to Verify the stack and start the
        /// system.</summary>
        /// <param name="sa">A security association that we wish to perform the
        /// specified control operation on.</param>
        /// <param name="scm">The received SecurityControlMessage.</param>
        /// <param name="scm_reply">A prepared reply message (with headers and such.</param>
        /// <param name="return_path">Where to send the result.</param>
        /// <param name="low_level_sender">We expect the return_path to not be an edge or
        /// some other type of "low level" sender, so this contains the parsed out value.</param>
        protected void HandleControlDHEWithCertificates(PeerSecAssociation sa,
                                                        SecurityControlMessage scm, SecurityControlMessage scm_reply,
                                                        ISender return_path, ISender low_level_sender)
        {
            ProtocolLog.WriteIf(ProtocolLog.Security, GetHashCode() + " Received DHEWithCertificate from: " + low_level_sender);
            if (sa == null)
            {
                throw new Exception("No valid SA!");
            }
            byte[] cert = new byte[scm.Certificate.Length];
            scm.Certificate.CopyTo(cert, 0);
            X509Certificate rcert = new X509Certificate(cert);
            HashAlgorithm   sha1  = new SHA1CryptoServiceProvider();

            scm.Verify((RSACryptoServiceProvider)rcert.RSA, sha1);
            _ch.Verify(rcert, low_level_sender);

            sa.RemoteCertificate = rcert;
            sa.RDHE.Value        = scm.DHE;

            scm_reply.LocalCookie  = scm.RemoteCookie;
            scm_reply.RemoteCookie = scm.LocalCookie;
            scm_reply.Hash         = MemBlock.Reference(sha1.ComputeHash((byte[])scm.Packet));
            scm_reply.Type         = SecurityControlMessage.MessageType.Confirm;
            lock (_private_key_lock) {
                scm_reply.Sign(_private_key, sha1);
            }

            ICopyable to_send = new CopyList(Security, SecureControl, scm_reply.Packet);

            _rrman.SendRequest(return_path, ReqrepManager.ReqrepType.Request,
                               to_send, this, sa);
            ProtocolLog.WriteIf(ProtocolLog.Security, GetHashCode() + " Successful DHEWithCertificate from: " + low_level_sender);
        }
        /// <summary>
        /// Finds an available IP range on the system
        /// </summary>
        /// <param name="networkdevice">Device to be ignored</param>
        /// <param name="startip">Device to be ignored</param>
        /// <returns>Return IP to use</returns>
        public static MemBlock GetNetwork(string networkdevice, MemBlock startip)
        {
            MemBlock    netip         = startip;
            ArrayList   used_networks = new ArrayList();
            IPHostEntry entry         = System.Net.Dns.GetHostEntry(String.Empty);

            foreach (IPAddress ip in entry.AddressList)
            {
                byte[] address = ip.GetAddressBytes();
                address[2] = 0;
                address[3] = 0;
                used_networks.Add(MemBlock.Reference(address));
            }

            while (used_networks.Contains(netip))
            {
                byte[] tmp = new byte[netip.Length];
                netip.CopyTo(tmp, 0);
                if (tmp[1] == 0)
                {
                    throw new Exception("Out of Addresses!");
                }
                tmp[1] -= 1;
                netip   = MemBlock.Reference(tmp);
            }
            return(netip);
        }
Exemple #18
0
        public void test()
        {
            MockDataHandler mdh = new MockDataHandler();

            mdh.HandleDataCallback += Callback;
            ISender sender = new MockSender(null, null, mdh, 0);

            byte[][]   b    = new byte[10][];
            MemBlock[] mb   = new MemBlock[10];
            Random     rand = new Random();

            for (int i = 0; i < 10; i++)
            {
                b[i] = new byte[128];
                rand.NextBytes(b[i]);
                mb[i] = MemBlock.Reference(b[i]);
                sender.Send(mb[i]);
            }

            for (int i = 0; i < 10; i++)
            {
                Assert.AreEqual(i, mdh.Position(mb[i]), "Position " + i);
                Assert.IsTrue(mdh.Contains(mb[i]), "Contains " + i);
            }

            Assert.AreEqual(_count, 10, "Count");
        }
Exemple #19
0
        /**
         * Abandon any attempts to get requests for the given ID.
         * @throw Exception if handler is not the original handler for this Request
         */
        public void StopRequest(int request_id, IReplyHandler handler)
        {
            RequestState rs = null;

            lock ( _sync ) {
                if (!_req_state_table.TryTake(request_id, out rs))
                {
                    rs = null;
                }
            }
            if (rs != null)
            {
                /*
                 * Send an ack for this reply:
                 */
                byte[] ack_payload = new byte[5];
                ack_payload[0] = (byte)ReqrepType.ReplyAck;
                NumberSerializer.WriteInt(request_id, ack_payload, 1);
                ICopyable data = new CopyList(_prefix, MemBlock.Reference(ack_payload));
                foreach (ISender ret_path in rs.Repliers)
                {
                    try {
                        //Try to send an ack, but if we can't, oh well...
                        ret_path.Send(data);
                    }
                    catch { }
                }
            }
        }
Exemple #20
0
        /**
         * <summary>Constructor when creating a Dns Query</summary>
         * <param name="QName">the name of resource you are looking up, IP Address
         * when QType = Ptr otherwise hostname</param>
         * <param name="QType"> the type of look up to perform</param>
         * <param name="QClass">should always be IN</param>
         */
        public Question(String QName, DnsPacket.Types QType, DnsPacket.Classes QClass)
        {
            this.QName  = QName;
            this.QType  = QType;
            this.QClass = QClass;

            if (QType == DnsPacket.Types.A || QType == DnsPacket.Types.AAAA)
            {
                QNameBlob = DnsPacket.HostnameStringToMemBlock(QName);
            }
            else if (QType == DnsPacket.Types.Ptr)
            {
                QNameBlob = DnsPacket.PtrStringToMemBlock(QName);
            }
            else
            {
                throw new Exception("Invalid QType: " + QType + "!");
            }

            // 2 for QType + 2 for QClass
            byte[] data = new byte[4];
            int    idx  = 0;

            data[idx++] = (byte)((((int)QType) >> 8) & 0xFF);
            data[idx++] = (byte)(((int)QType) & 0xFF);
            data[idx++] = (byte)((((int)QClass) >> 8) & 0xFF);
            data[idx++] = (byte)(((int)QClass) & 0xFF);
            _icpacket   = new CopyList(QNameBlob, MemBlock.Reference(data));
        }
Exemple #21
0
        public void DnsPtrTest()
        {
            String Name = "64.233.169.104";

            DnsPacket.Types   Type  = DnsPacket.Types.Ptr;
            DnsPacket.Classes Class = DnsPacket.Classes.IN;
            int      Ttl            = 30;
            String   RData          = "yo-in-f104.google.com";
            Response rp             = new Response(Name, Type, Class, Ttl, RData);

            MemBlock ptrm = MemBlock.Reference(new byte[] { 0x03, 0x31, 0x30, 0x34,
                                                            0x03, 0x31, 0x36, 0x39, 0x03, 0x32, 0x33, 0x33, 0x02, 0x36, 0x34, 0x07,
                                                            0x69, 0x6e, 0x2d, 0x61, 0x64, 0x64, 0x72, 0x04, 0x61, 0x72, 0x70, 0x61,
                                                            0x00, 0x00, 0x0c, 0x00, 0x01, 0x00, 0x00, 0x00, 0x1e, 0x00, 0x17, 0x0a,
                                                            0x79, 0x6f, 0x2d, 0x69, 0x6e, 0x2d, 0x66, 0x31, 0x30, 0x34, 0x06, 0x67,
                                                            0x6f, 0x6f, 0x67, 0x6c, 0x65, 0x03, 0x63, 0x6f, 0x6d, 0x00 });
            Response rm = new Response(ptrm, 0);

            Assert.AreEqual(rp.Packet, ptrm, "Packet");
            Assert.AreEqual(rm.Name, Name, "Name");
            Assert.AreEqual(rm.Type, Type, "Type");
            Assert.AreEqual(rm.Class, Class, "Class");
            Assert.AreEqual(rm.Ttl, Ttl, "Ttl");
            Assert.AreEqual(rm.RData, RData, "RData");
        }
Exemple #22
0
        ///<summary>All outgoing data filters through here.</summary>
        override protected bool HandleOutgoing(ICopyable app_data, out ICopyable data)
        {
            if (!_active)
            {
                if (_closed == 1)
                {
                    throw new SendException(false, "SA closed, unable to send!");
                }
                UpdateSH(null, null);
                data = null;
                return(false);
            }

            // prepare the packet
            SecurityDataMessage sdm = new SecurityDataMessage();

            sdm.SPI  = _spi;
            sdm.Data = app_data as MemBlock;
            if (sdm.Data == null)
            {
                byte[] b = new byte[app_data.Length];
                app_data.CopyTo(b, 0);
                sdm.Data = MemBlock.Reference(b);
            }

            // Encrypt it!
            lock (_sync) {
                _current_sh.SignAndEncrypt(sdm);
            }

            data = new CopyList(PeerSecOverlord.Security, PeerSecOverlord.SecureData, sdm.ICPacket);
            return(true);
        }
Exemple #23
0
        public void Test()
        {
            RSACryptoServiceProvider rsa = new RSACryptoServiceProvider();

            byte[] blob = rsa.ExportCspBlob(false);
            RSACryptoServiceProvider rsa_pub = new RSACryptoServiceProvider();

            rsa_pub.ImportCspBlob(blob);
            CertificateMaker cm = new CertificateMaker("United States", "UFL",
                                                       "ACIS", "David Wolinsky", "*****@*****.**", rsa_pub,
                                                       "brunet:node:abcdefghijklmnopqrs");

            Assert.AreEqual("C=United States, O=UFL, OU=ACIS, CN=David Wolinsky, [email protected]", cm.Subject.DN, "DN test 1");
            cm = new CertificateMaker(cm.UnsignedData);
            Assert.AreEqual("C=United States, O=UFL, OU=ACIS, CN=David Wolinsky, [email protected]", cm.Subject.DN, "DN test 2");

            Certificate cert = cm.Sign(cm, rsa);

            Assert.IsTrue(cert.Signature != null, "Signature");
            Assert.AreEqual(cm.Subject.DN, cert.Issuer.DN, "Issuer = Subject");
            Assert.AreEqual("brunet:node:abcdefghijklmnopqrs", cert.NodeAddress, "Node address");

            Mono.Math.BigInteger rsa_pub_bi  = new Mono.Math.BigInteger(rsa_pub.ExportCspBlob(false));
            Mono.Math.BigInteger cert_pub_bi = new Mono.Math.BigInteger(cert.PublicKey.ExportCspBlob(false));
            Assert.AreEqual(rsa_pub_bi, cert_pub_bi, "Key");

            SHA1CryptoServiceProvider sha1 = new SHA1CryptoServiceProvider();

            Assert.AreEqual(MemBlock.Reference(cert.SerialNumber),
                            MemBlock.Reference(sha1.ComputeHash(cert.UnsignedData)),
                            "SerialNumber == hash of unsigned data");
        }
Exemple #24
0
        protected void Setup(PeerSecAssociation sa1, PeerSecAssociation sa2)
        {
            sa1.Reset();
            sa2.Reset();
            sa1.RDHE.Value = sa2.LDHE;
            sa2.RDHE.Value = sa1.LDHE;

            Random rand = new Random();

            byte[] b = new byte[128];
            rand.NextBytes(b);
            MemBlock mb = MemBlock.Reference(b);

            sa1.DHEWithCertificateAndCAsOutHash.Value = mb;
            sa1.VerifyResponse(mb);

            b = new byte[128];
            rand.NextBytes(b);
            mb = MemBlock.Reference(b);

            sa2.DHEWithCertificateHash.Value = mb;
            sa2.VerifyRequest(mb);

            sa1.Enable();
            sa2.Enable();
            // This is just for kicks
            sa1.Enable();
        }
        protected void SendControlPacket(EndPoint end, int remoteid, int localid,
                                         ControlCode c, object state)
        {
            using (MemoryStream ms = new MemoryStream()) {
                NumberSerializer.WriteInt((int)c, ms);
                if (c == ControlCode.EdgeDataAnnounce)
                {
                    UdpEdge e = (UdpEdge)_id_ht[localid];
                    if ((e != null) && (e.RemoteID == remoteid))
                    {
                        Hashtable t = new Hashtable();
                        t["RemoteTA"] = e.RemoteTA.ToString();
                        t["LocalTA"]  = e.LocalTA.ToString();
                        AdrConverter.Serialize(t, ms);
                    }
                    else
                    {
                        if (ProtocolLog.UdpEdge.Enabled)
                        {
                            ProtocolLog.Write(ProtocolLog.UdpEdge, String.Format(
                                                  "Problem sending EdgeData: EndPoint: {0}, remoteid: {1}, " +
                                                  "localid: {2}, Edge: {3}", end, remoteid, localid, e));
                        }
                    }
                }

                _send_queue.Enqueue(new UdpMessage(localid, ~remoteid, MemBlock.Reference(ms.ToArray()), end));
                if (ProtocolLog.UdpEdge.Enabled)
                {
                    ProtocolLog.Write(ProtocolLog.UdpEdge, String.Format(
                                          "Sending control {1} to: {0}", end, c));
                }
            }
        }
Exemple #26
0
        /// <summary>
        /// Sends Dns query to Dns Server and returns the response.
        /// </summary>
        /// <param name="dns_server">The IPEndPoint of the Dns Server
        /// <param name="request"> Dns Packet to be sent</param>
        /// <returns></returns>
        public MemBlock Resolve(EndPoint server, byte[] request)
        {
            Socket socket = new Socket(AddressFamily.InterNetwork, SocketType.Dgram, ProtocolType.Udp);

            socket.SetSocketOption(SocketOptionLevel.Socket, SocketOptionName.ReceiveTimeout, 1000);
            socket.Connect(server);
            socket.Send(request, request.Length, SocketFlags.None);

            MemBlock response = null;

            try {
                byte[] tmp    = new byte[512];
                int    length = socket.Receive(tmp);
                response = MemBlock.Reference(tmp, 0, length);
            } finally {
                socket.Close();
            }

            // Is this a response to our request?
            if ((response[0] != request[0]) || (response[1] != request[1]))
            {
                throw new Exception("Invalid response");
            }

            return(response);
        }
Exemple #27
0
        /// <summary>Continues a broadcast to the overlay.</summary>
        public BroadcastSender(StructuredNode node, AHAddress source,
                               AHAddress from, AHAddress to, int forwarders, int hops)
        {
            Node             = node;
            Source           = source;
            From             = from;
            To               = to;
            _distance_sorter = new AbsoluteDistanceComparer(node.Address as AHAddress);
            _address_sorter  = new LeftDistanceComparer(node.Address as AHAddress);
            Forwarders       = forwarders;
            Hops             = hops;

            byte[] hops_data = new byte[4];
            NumberSerializer.WriteInt(hops, hops_data, 0);
            _hops = MemBlock.Reference(hops_data);

            if (forwarders == DEFAULT_FORWARDERS)
            {
                _forwarders = DEFAULT_FORWARDERS_MB;
            }
            else
            {
                byte[] def = new byte[4];
                NumberSerializer.WriteInt(forwarders, def, 0);
                _forwarders = MemBlock.Reference(def);
            }
        }
Exemple #28
0
        /// <summary>Constructor for a TunnelEdge, RemoteID == -1 for out bound.</summary>
        public TunnelEdge(IEdgeSendHandler send_handler, TunnelTransportAddress local_ta,
                          TunnelTransportAddress remote_ta, IForwarderSelector ias, List <Connection> overlap,
                          int remote_id) : base(send_handler, remote_id != -1)
        {
            _remote_id = remote_id;
            lock (_rand) {
                LocalID = _rand.Next();
            }
            byte[] bid = new byte[8];
            NumberSerializer.WriteInt(LocalID, bid, 0);
            NumberSerializer.WriteInt(_remote_id, bid, 4);
            _mid       = MemBlock.Reference(bid);
            _local_ta  = local_ta;
            _remote_ta = remote_ta;
            _tunnels   = new List <Connection>(overlap);
            _ias       = ias;
            _ias.Update(_tunnels);

            AHHeader ahh = new AHHeader(1, 20, local_ta.Target, remote_ta.Target,
                                        AHHeader.Options.Exact);
            ICopyable header = new CopyList(PType.Protocol.AH, ahh,
                                            PType.Protocol.Tunneling);

            Header = MemBlock.Copy(header);
        }
 /// <summary>Change in either local or remote IDs, time to update the
 /// header to match.</summary>
 protected void UpdateHeader()
 {
     byte[] header = new byte[8];
     NumberSerializer.WriteInt(_local_id, header, SOURCE_OFFSET);
     NumberSerializer.WriteInt(_remote_id, header, DESTINATION_OFFSET);
     _header = MemBlock.Reference(header);
 }
Exemple #30
0
        /// <summary>
        /// Maps IP address to Brunet address.
        /// </summary>
        /// <param name="ip">IP address to map</param>
        /// <param name="addr">Brunet address to map</param>
        /// <returns>IP string of the allocated IP</returns>
        public string AddIPMapping(string ip, Address addr)
        {
            MemBlock ip_bytes;

            lock (_sync) {
                if (ip == null || ip == String.Empty)
                {
                    do
                    {
                        ip_bytes = MemBlock.Reference(_dhcp.RandomIPAddress());
                    } while (_ip_addr.ContainsKey(ip_bytes));
                }
                else
                {
                    ip_bytes = MemBlock.Reference(Utils.StringToBytes(ip, '.'));
                    if (!_dhcp.ValidIP(ip_bytes))
                    {
                        throw new Exception("Invalid IP");
                    }
                }

                if (_ip_addr.ContainsValue(addr) || _addr_ip.ContainsValue(ip_bytes))
                {
                    throw new Exception("IP/P2P address is already found");
                }

                _ip_addr.Add(ip_bytes, addr);
                _addr_ip.Add(addr, ip_bytes);
                mcast_addr.Add(addr);
            }
            return(Utils.BytesToString(ip_bytes, '.'));
        }