Ejemplo n.º 1
0
        public VirtualNode(EvalEnvironment env, VirtualNetwork network, EvalOptionSet opt,
			IntervalInterrupter messagingInt, IntervalInterrupter kbrStabilizeInt, IntervalInterrupter anonInt, IntervalInterrupter dhtInt)
        {
            IPAddress pubAdrs = _ipGenerator.Next ();
            int bindPort;
            lock (_rnd) {
                bindPort = _rnd.Next (1024, ushort.MaxValue);
            }
            _pubEP = new IPEndPoint (pubAdrs, bindPort);
            _nodePrivateKey = ECKeyPair.Create (DefaultECDomain);
            _nodeId = Key.Create (_nodePrivateKey);
            VirtualDatagramEventSocket sock = new VirtualDatagramEventSocket (network, pubAdrs);
            sock.Bind (new IPEndPoint (IPAddress.Any, bindPort));
            _msock = opt.BypassMessagingSerializer
                ? (IMessagingSocket)new VirtualMessagingSocket (sock, true, messagingInt, DefaultMessagingRTO, DefaultMessagingRetries, DefaultMessagingRetryBufferSize, DefaultMessagingDupCheckSize)
                : (IMessagingSocket)new MessagingSocket (sock, true, SymmetricKey.NoneKey, Serializer.Instance, null, messagingInt, DefaultMessagingRTO, DefaultMessagingRetries, DefaultMessagingRetryBufferSize, DefaultMessagingDupCheckSize);
            _kbr = new SimpleIterativeRouter2 (_nodeId, 0, _msock, new SimpleRoutingAlgorithm (), Serializer.Instance, opt.NewKBRStrictMode);
            _localDHT = new OnMemoryLocalHashTable (_kbr, dhtInt);
            _dht = new SimpleDHT (_kbr, _msock, _localDHT);
            _dht.RegisterTypeID (typeof (string), 0, new LocalHashTableValueMerger<string> ());
            p2pncs.Net.Overlay.Anonymous.AnonymousRouter.DefaultRelayNodes = opt.AnonymousRouteRelays;
            p2pncs.Net.Overlay.Anonymous.AnonymousRouter.DefaultSubscribeRoutes = opt.AnonymousRouteRoutes + opt.AnonymousRouteBackupRoutes;
            p2pncs.Net.Overlay.Anonymous.AnonymousRouter.AC_DefaultUseSubscribeRoutes = opt.AnonymousRouteRoutes;
            _anonRouter = new AnonymousRouter (_dht, _nodePrivateKey, anonInt);
            _kbrStabilizeInt = kbrStabilizeInt;
            _kbrStabilizeInt.AddInterruption (_kbr.RoutingAlgorithm.Stabilize);
            _env = env;
        }
Ejemplo n.º 2
0
 public static object Decrypt(ECKeyPair privateKey, byte[] encrypted)
 {
     using (SymmetricAlgorithm algo = new CamelliaManaged ())
     using (ECIES ecies = new ECIES (DefaultAlgorithm.ECDomainName, algo)) {
         ecies.Parameters.PrivateKey = privateKey.PrivateKey;
         try {
             return Serializer.Instance.Deserialize (ecies.Decrypt (encrypted));
         } catch {
             return null;
         }
     }
 }
Ejemplo n.º 3
0
		public void Test_GEC2 ()
		{
			ECDomainNames domainName = ECDomainNames.secp160r1;
			ECDomainParameters domain = ECDomains.GetDomainParameter (domainName);
			ECIES ecies = new ECIES (domainName);
			Number V_Private = Number.Parse ("45FB58A92A17AD4B15101C66E74F277E2B460866", 16);
			ECKeyPair pair = new ECKeyPair (V_Private, null, domain);
			pair.CreatePublicKeyFromPrivateKey ();
			ecies.Parameters._Q = pair._Q;
			byte[] M = System.Text.Encoding.ASCII.GetBytes ("abcdefghijklmnopqrst");
			byte[] k = Number.Parse ("702232148019446860144825009548118511996283736794", 10).ToByteArray (20, false);
			byte[] C = ecies.Encrypt (M, k);
			byte[] expectedC = new byte[] {0x02, 0xCE, 0x28, 0x73, 0xE5, 0xBE, 0x44, 0x95, 0x63, 0x39, 0x1F, 0xEB, 0x47, 0xDD, 0xCB, 0xA2, 0xDC, 0x16, 0x37, 0x91, 0x91, 0x71, 0x23, 0xC8, 0x70, 0xA3, 0x1A, 0x81, 0xEA, 0x75, 0x83, 0x29, 0x0D, 0x1B, 0xA1, 0x7B, 0xC8, 0x75, 0x94, 0x35, 0xED, 0x1C, 0xCD, 0xA9, 0xEB, 0x4E, 0xD2, 0x73, 0x60, 0xBE, 0x89, 0x67, 0x29, 0xAD, 0x18, 0x54, 0x93, 0x62, 0x25, 0x91, 0xE5};
			Assert.AreEqual (expectedC, C, "Encryption");

			ecies = new ECIES (domainName);
			ecies.Parameters._d = V_Private;
			byte[] M2 = ecies.Decrypt (C);
			Assert.AreEqual (M, M2, "Decryption");
		}
Ejemplo n.º 4
0
        static void LoadConfig(XmlConfig config, out ECKeyPair privateKey)
        {
            bool saveFlag = false;

            config.Define<int> (CONFIG_BIND_PORT, IntParser.Instance, new IntRangeValidator (1, ushort.MaxValue), 8080);
            config.Define<byte[]> (CONFIG_PRIVATE_KEY, BinaryParser.Instance, null, null);
            config.Define<string> (CONFIG_HOST, StringParser.Instance, null, string.Empty);

            try {
                if (File.Exists (CONFIG_PATH))
                    config.Load (CONFIG_PATH);
            } catch {
                saveFlag = true;
            }

            byte[] raw = config.GetValue<byte[]> (CONFIG_PRIVATE_KEY);
            while (true) {
                if (raw == null || raw.Length == 0) {
                    privateKey = ECKeyPair.Create (DefaultAlgorithm.ECDomainName);
                    config.SetValue<byte[]> (CONFIG_PRIVATE_KEY, privateKey.PrivateKey, false);
                    saveFlag = true;
                } else {
                    privateKey = ECKeyPairExtensions.CreatePrivate (raw);
                    if (privateKey.DomainName != DefaultAlgorithm.ECDomainName) {
                        raw = null;
                        continue;
                    }
                }
                break;
            }

            if (config.GetValue<string> (CONFIG_HOST).Length == 0) {
                config.SetValue<string> (CONFIG_HOST, "localhost", false);
                saveFlag = true;
            }

            if (saveFlag)
                config.Save (CONFIG_PATH);
        }
Ejemplo n.º 5
0
 public Node(Interrupters ints, IDatagramEventSocket bindedDgramSock, ITcpListener tcpListener, string db_path, ushort bindUdpPort, ushort bindTcpPort)
 {
     _udpPort = bindUdpPort;
     _tcpPort = bindTcpPort;
     _ints = ints;
     _dgramSock = bindedDgramSock;
     _tcpListener = tcpListener;
     _rtoAlgo = new RFC2988BasedRTOCalculator (TimeSpan.FromSeconds (1), TimeSpan.FromMilliseconds (100), 50, false);
     _messagingSock = new MessagingSocket (_dgramSock, true, SymmetricKey.NoneKey, p2pncs.Serializer.Instance,
         null, ints.MessagingInt, _rtoAlgo, DefaultMessagingRetry, DefaultMessagingRetryBufferSize, DefaultMessagingDuplicationCheckBufferSize);
     _kbrPrivateKey = ECKeyPair.Create (DefaultAlgorithm.ECDomainName);
     _kbr = new SimpleIterativeRouter2 (Key.Create (_kbrPrivateKey), bindTcpPort, _messagingSock, new SimpleRoutingAlgorithm (), p2pncs.Serializer.Instance, true);
     _portChecker = new PortOpenChecker (_kbr);
     _localHT = new OnMemoryLocalHashTable (_kbr, ints.DHTInt);
     IMassKeyDelivererLocalStore mkdLocalStore = _localHT as IMassKeyDelivererLocalStore;
     _dht = new SimpleDHT (_kbr, _messagingSock, _localHT);
     _anonymous = new AnonymousRouter (_dht, _kbrPrivateKey, ints.AnonymousInt);
     ints.KBRStabilizeInt.AddInterruption (Stabilize);
     _mkd = new MassKeyDeliverer (_dht, mkdLocalStore, ints.MassKeyDeliverTimerInt);
     _mmlc = new MMLC (_anonymous, _dht, mkdLocalStore, db_path, ints.StreamSocketTimeoutInt, ints.DFSRePutTimerInt);
     _crawler = new FileInfoCrawler (_tcpListener, _mmlc, _ints.CrawlingTimer);
     _statistics = new Statistics ((AnonymousRouter)_anonymous, _mmlc, _tcpListener);
 }
Ejemplo n.º 6
0
 DebugNode(int idx, Interrupters ints, ITcpListener listener, IDatagramEventSocket bindedDgramSock, IPEndPoint bindTcpEp, IPEndPoint bindUdpEp, int gw_port, string dbpath)
     : base(ints, bindedDgramSock, listener, dbpath, (ushort)bindUdpEp.Port, (ushort)bindTcpEp.Port)
 {
     _idx = idx;
     _bindTcpEP = bindTcpEp;
     _imPrivateKey = ECKeyPair.Create (DefaultAlgorithm.ECDomainName);
     _imPublicKey = Key.Create (_imPrivateKey);
     _name = "Node-" + idx.ToString ("x");
     _app = new WebApp (this, ints);
     _is_gw = gw_port > 0;
     if (_is_gw) {
         _sessionMiddleware = new SessionMiddleware (MMLC.CreateDBConnection, _app);
         _server = HttpServer.CreateEmbedHttpServer (_sessionMiddleware, null, true, true, false, gw_port, 16);
     }
 }
Ejemplo n.º 7
0
        public void BidirectionalCommunicationTest()
        {
            using (KBREnvironment env = new KBREnvironment (true, true)) {
                int nodes = 20;
                ECKeyPair[] nodePrivateKeys = new ECKeyPair[nodes];
                Key[] nodeKeys = new Key[nodes];
                for (int i = 0; i < nodePrivateKeys.Length; i ++) {
                    nodePrivateKeys[i] = ECKeyPair.Create (DefaultAlgorithm.ECDomainName);
                    nodeKeys[i] = Key.Create (nodePrivateKeys[i]);
                }
                env.AddNodes (nodeKeys, nodePrivateKeys);

                ECKeyPair priv1 = ECKeyPair.Create (DefaultAlgorithm.ECDomainName);
                ECKeyPair priv2 = ECKeyPair.Create (DefaultAlgorithm.ECDomainName);
                Key id1 = Key.Create (priv1);
                Key id2 = Key.Create (priv2);
                ISubscribeInfo subscribeInfo1 = env.AnonymousRouters[0].SubscribeRecipient (id1, priv1);
                ISubscribeInfo subscribeInfo2 = env.AnonymousRouters[1].SubscribeRecipient (id2, priv2);
                while (true) {
                    if (subscribeInfo1.Status != SubscribeRouteStatus.Establishing && subscribeInfo2.Status != SubscribeRouteStatus.Establishing)
                        break;
                    Thread.Sleep (100);
                }

                byte[] received1 = null;
                object received1_lock = new object ();
                AutoResetEvent received1_done = new AutoResetEvent (false);
                byte[] received2 = null;
                object received2_lock = new object ();
                AutoResetEvent received2_done = new AutoResetEvent (false);
                AutoResetEvent accepted_done = new AutoResetEvent (false);
                IAnonymousSocket sock2 = null;
                subscribeInfo2.Accepting += delegate (object sender, AcceptingEventArgs args) {
                    string msg = args.Payload as string;
                    Assert.IsNotNull (msg);
                    Assert.AreEqual ("HELLO", msg);
                    args.Accept ("HELLO2", null);
                };
                subscribeInfo2.Accepted += delegate (object sender, AcceptedEventArgs args) {
                    lock (received2_lock) {
                        Assert.IsNull (sock2, "2.accepted.#1");
                        sock2 = args.Socket;
                        Assert.IsNotNull (sock2, "2.accepted.#2");
                        accepted_done.Set ();
                    }
                };

                IAsyncResult ar = env.AnonymousRouters[0].BeginConnect (id1, id2, AnonymousConnectionType.LowLatency, "HELLO", null, null);
                IAnonymousSocket sock1 = env.AnonymousRouters[0].EndConnect (ar);
                Assert.IsNotNull (sock1, "1.sock");
                Assert.AreEqual ("HELLO2", sock1.PayloadAtEstablishing as string);
                Assert.IsTrue (accepted_done.WaitOne (1000), "2.waiting");
                Assert.IsNotNull (sock2, "2.sock");
                Assert.AreEqual ("HELLO", sock2.PayloadAtEstablishing as string);
                sock1.Received += delegate (object sender, DatagramReceiveEventArgs args) {
                    lock (received1_lock) {
                        Assert.IsNull (received1, "1.received.#1");
                        received1 = new byte[args.Size];
                        Buffer.BlockCopy (args.Buffer, 0, received1, 0, received1.Length);
                        received1_done.Set ();
                    }
                };
                sock2.Received += delegate (object sender2, DatagramReceiveEventArgs args2) {
                    lock (received2_lock) {
                        Assert.IsNull (received2, "2.received.#1");
                        received2 = new byte[args2.Size];
                        Buffer.BlockCopy (args2.Buffer, 0, received2, 0, received2.Length);
                        received2_done.Set ();
                    }
                };
                sock1.InitializedEventHandlers ();
                sock2.InitializedEventHandlers ();

                for (int i = 0; i < 3; i ++) {
                    string msg = "HELLO " + i.ToString ();
                    sock1.SendTo (Encoding.UTF8.GetBytes (msg), AnonymousRouter.DummyEndPoint);
                    Assert.IsTrue (received2_done.WaitOne (5000), "2.received.#2");
                    Assert.IsNotNull (received2, "2.received.#3");
                    Assert.AreEqual (msg, Encoding.UTF8.GetString (received2));
                    lock (received2_lock) {
                        received2 = null;
                    }

                    msg = "OK " + i.ToString ();
                    sock2.SendTo (Encoding.UTF8.GetBytes (msg), AnonymousRouter.DummyEndPoint);
                    Assert.IsTrue (received1_done.WaitOne (5000), "1.received.#2");
                    Assert.IsNotNull (received1, "1.received.#3");
                    Assert.AreEqual (msg, Encoding.UTF8.GetString (received1));
                    lock (received1_lock) {
                        received1 = null;
                    }
                }
            }
        }
Ejemplo n.º 8
0
        public void EstablishFailTest()
        {
            using (KBREnvironment env = new KBREnvironment (true, true)) {
                int nodes = 20;
                ECKeyPair[] nodePrivateKeys = new ECKeyPair[nodes];
                Key[] nodeKeys = new Key[nodes];
                for (int i = 0; i < nodePrivateKeys.Length; i ++) {
                    nodePrivateKeys[i] = ECKeyPair.Create (DefaultAlgorithm.ECDomainName);
                    nodeKeys[i] = Key.Create (nodePrivateKeys[i]);
                }
                env.AddNodes (nodeKeys, nodePrivateKeys);

                ECKeyPair priv1 = ECKeyPair.Create (DefaultAlgorithm.ECDomainName);
                ECKeyPair priv2 = ECKeyPair.Create (DefaultAlgorithm.ECDomainName);
                Key id1 = Key.Create (priv1);
                Key id2 = Key.Create (priv2);
                ISubscribeInfo subscribeInfo1 = env.AnonymousRouters[0].SubscribeRecipient (id1, priv1);
                ISubscribeInfo subscribeInfo2 = env.AnonymousRouters[1].SubscribeRecipient (id2, priv2);
                while (true) {
                    if (subscribeInfo1.Status != SubscribeRouteStatus.Establishing && subscribeInfo2.Status != SubscribeRouteStatus.Establishing)
                        break;
                    Thread.Sleep (100);
                }

                AutoResetEvent accepted_done = new AutoResetEvent (false);
                IAnonymousSocket sock2 = null;
                subscribeInfo2.Accepting += delegate (object sender, AcceptingEventArgs args) {
                    args.Reject ();
                };
                subscribeInfo2.Accepted += delegate (object sender, AcceptedEventArgs args) {
                    accepted_done.Set ();
                    sock2 = args.Socket;
                };

                try {
                    IAsyncResult ar = env.AnonymousRouters[0].BeginConnect (id1, id2, AnonymousConnectionType.LowLatency, null, null, null);
                    env.AnonymousRouters[0].EndConnect (ar);
                    Assert.Fail ();
                } catch (System.Net.Sockets.SocketException) {}
            }
        }
Ejemplo n.º 9
0
 public void AddNodes(Key[] keys, ECKeyPair[] keyPairs)
 {
     for (int i = 0; i < keys.Length; i++) {
         IPAddress adrs = _ipGenerator.Next ();
         IPEndPoint ep = new IPEndPoint (adrs, 10000);
         VirtualDatagramEventSocket sock = new VirtualDatagramEventSocket (_network, adrs);
         sock.Bind (new IPEndPoint (IPAddress.Loopback, ep.Port));
         //IMessagingSocket msock = new MessagingSocket (sock, true, SymmetricKey.NoneKey, Serializer.Instance, null, _interrupter, TimeSpan.FromSeconds (1), 2, 1024);
         IMessagingSocket msock = new VirtualMessagingSocket (sock, true, _interrupter, _rtoAlgo, 2, 1024, 1024);
         _sockets.Add (msock);
         IKeyBasedRouter router = new SimpleIterativeRouter2 (keys[i], 0, msock, new SimpleRoutingAlgorithm (), Serializer.Instance, true);
         _routers.Add (router);
         if (_dhts != null) {
             IDistributedHashTable dht = new SimpleDHT (router, msock, new OnMemoryLocalHashTable (router, _dhtInt));
             _dhts.Add (dht);
             if (_anons != null) {
                 IAnonymousRouter anonRouter = new AnonymousRouter (dht, keyPairs[i], _anonInt);
                 _anons.Add (anonRouter);
             }
         }
         if (_endPoints.Count != 0) {
             if (_initEPs == null || _endPoints.Count < 3)
                 _initEPs = _endPoints.ToArray ();
             router.Join (_initEPs);
         }
         _endPoints.Add (ep);
         Thread.Sleep (5);
     }
     Thread.Sleep (500);
 }
Ejemplo n.º 10
0
 public void Sign(ECKeyPair privateKey)
 {
     _key = Key.Create (privateKey);
     using (ECDSA ecdsa = new ECDSA (privateKey)) {
         _sign = ecdsa.SignHash (ComputeHash ());
     }
 }