Ejemplo n.º 1
0
        public PuzzleValue[] GeneratePuzzles()
        {
            AssertState(SolverClientStates.WaitingGeneratePuzzles);
            List <PuzzleSetElement> puzzles = new List <PuzzleSetElement>();

            for (int i = 0; i < Parameters.RealPuzzleCount; i++)
            {
                BlindFactor blind  = null;
                Puzzle      puzzle = new Puzzle(ServerKey, InternalState.Puzzle).Blind(ref blind);
                puzzles.Add(new RealPuzzle(puzzle, blind));
            }

            for (int i = 0; i < Parameters.FakePuzzleCount; i++)
            {
                PuzzleSolution solution = null;
                Puzzle         puzzle   = ServerKey.GeneratePuzzle(ref solution);
                puzzles.Add(new FakePuzzle(puzzle, solution));
            }

            _PuzzleElements = puzzles.ToArray();
            NBitcoin.Utils.Shuffle(_PuzzleElements, RandomUtils.GetInt32());
            InternalState.FakeIndexes = new int[Parameters.FakePuzzleCount];
            int fakeI = 0;

            for (int i = 0; i < _PuzzleElements.Length; i++)
            {
                _PuzzleElements[i].Index = i;
                if (_PuzzleElements[i] is FakePuzzle)
                {
                    InternalState.FakeIndexes[fakeI++] = i;
                }
            }
            InternalState.Status = SolverClientStates.WaitingCommitments;
            return(_PuzzleElements.Select(p => p.Puzzle.PuzzleValue).ToArray());
        }
Ejemplo n.º 2
0
        public override int GetHashCode()
        {
            int hash = 1;

            if (ServerKey.Length != 0)
            {
                hash ^= ServerKey.GetHashCode();
            }
            if (ServerCert.Length != 0)
            {
                hash ^= ServerCert.GetHashCode();
            }
            if (CustomCa.Length != 0)
            {
                hash ^= CustomCa.GetHashCode();
            }
            if (ClientVerify != false)
            {
                hash ^= ClientVerify.GetHashCode();
            }
            if (_unknownFields != null)
            {
                hash ^= _unknownFields.GetHashCode();
            }
            return(hash);
        }
        public Task TryRemoveAddressesAsync(
            ServerKey serverKey,
            CancellationToken cancellationToken)
        {
            if (serverKey == null)
            {
                throw new ArgumentNullException(nameof(serverKey));
            }

            List <Task> tasks = new List <Task>();

            if (this.serverPartitionAddressToPkRangeIdMap.TryRemove(serverKey, out HashSet <PartitionKeyRangeIdentity> pkRangeIds))
            {
                PartitionKeyRangeIdentity[] pkRangeIdsCopy;
                lock (pkRangeIds)
                {
                    pkRangeIdsCopy = pkRangeIds.ToArray();
                }

                foreach (PartitionKeyRangeIdentity pkRangeId in pkRangeIdsCopy)
                {
                    DefaultTrace.TraceInformation("Remove addresses for collectionRid :{0}, pkRangeId: {1}, serviceEndpoint: {2}",
                                                  pkRangeId.CollectionRid,
                                                  pkRangeId.PartitionKeyRangeId,
                                                  this.serviceEndpoint);

                    tasks.Add(this.serverPartitionAddressCache.RemoveAsync(pkRangeId));
                }
            }

            return(Task.WhenAll(tasks));
        }
Ejemplo n.º 4
0
        public Task TryRemoveAddressesAsync(
            ServerKey serverKey,
            CancellationToken cancellationToken)
        {
            if (serverKey == null)
            {
                throw new ArgumentNullException(nameof(serverKey));
            }

            List <Task> tasks = new List <Task>();
            HashSet <PartitionKeyRangeIdentity> pkRangeIds;

            if (this.serverPartitionAddressToPkRangeIdMap.TryGetValue(serverKey, out pkRangeIds))
            {
                foreach (PartitionKeyRangeIdentity pkRangeId in pkRangeIds)
                {
                    DefaultTrace.TraceInformation("Remove addresses for collectionRid :{0}, pkRangeId: {1}, serviceEndpoint: {2}",
                                                  pkRangeId.CollectionRid,
                                                  pkRangeId.PartitionKeyRangeId,
                                                  this.serviceEndpoint);

                    tasks.Add(this.serverPartitionAddressCache.RemoveAsync(pkRangeId));
                }

                // remove the server key from the map since we are updating the addresses
                HashSet <PartitionKeyRangeIdentity> ignorePkRanges;
                this.serverPartitionAddressToPkRangeIdMap.TryRemove(serverKey, out ignorePkRanges);
            }

            return(Task.WhenAll(tasks));
        }
        public void TryRemoveAddresses(
            ServerKey serverKey)
        {
            if (serverKey == null)
            {
                throw new ArgumentNullException(nameof(serverKey));
            }

            if (this.serverPartitionAddressToPkRangeIdMap.TryRemove(serverKey, out HashSet <PartitionKeyRangeIdentity> pkRangeIds))
            {
                PartitionKeyRangeIdentity[] pkRangeIdsCopy;
                lock (pkRangeIds)
                {
                    pkRangeIdsCopy = pkRangeIds.ToArray();
                }

                foreach (PartitionKeyRangeIdentity pkRangeId in pkRangeIdsCopy)
                {
                    DefaultTrace.TraceInformation("Remove addresses for collectionRid :{0}, pkRangeId: {1}, serviceEndpoint: {2}",
                                                  pkRangeId.CollectionRid,
                                                  pkRangeId.PartitionKeyRangeId,
                                                  this.serviceEndpoint);

                    this.serverPartitionAddressCache.TryRemove(pkRangeId);
                }
            }
        }
Ejemplo n.º 6
0
        public override void Process()
        {
            UserProxy user = (UserProxy)Session;

            user.InitC2S(ServerKey.RawData());
            base.Process();
        }
 public static void ValidateServerKey(ServerKey actual, string expectedName, string expectedKeyType, string expectedUri)
 {
     Assert.NotNull(actual);
     Assert.Equal(expectedName, actual.Name);
     Assert.Equal(expectedKeyType, actual.ServerKeyType);
     Assert.Equal(expectedUri, actual.Uri);
 }
Ejemplo n.º 8
0
        static void Main(string[] args)
        {
            // Check if there is a generated serverkey
            // if not found generate
            string serverkeyfile = WORKSPACE_FOLDER + Path.DirectorySeparatorChar + SERVERKEY_FILE;

            try
            {
                if (File.Exists(serverkeyfile))
                {
                    // File allready generated ask for password to decrypt
                    Console.Write("Enter password to decrypt serverkey: ");
                    string password = ReadLine.ReadPassword();

                    string filecontent = File.ReadAllText(serverkeyfile);

                    filecontent = Crypto.RC4.Decrypt(password, filecontent);

                    ServerKey serverkeyobj = JsonConvert.DeserializeObject <ServerKey>(filecontent);

                    //All is ok file valid check key lenght than use it

                    if (serverkeyobj.serverkey.Length == 16)
                    {
                        Execute(serverkeyobj.serverkey);
                    }
                    else
                    {
                        throw new SystemException("Serverkey corrupted");
                    }
                }
                else
                {
                    // Serverkey file not found ask for password to encrypt the file
                    string password = "";
                    do
                    {
                        Console.Write("Enter password to encrypt serverkey: ");
                        password = ReadLine.ReadPassword();
                    }while (password.Length < 8 || password.StartsWith("        "));

                    // Generate serverkey and store in encrypted file
                    ServerKey serverkeyobj = new ServerKey();
                    Random    r            = new Random();
                    serverkeyobj.serverkey = RandomString(16, r);
                    string serverkeystr = JsonConvert.SerializeObject(serverkeyobj, Formatting.Indented);
                    File.WriteAllText(serverkeyfile, Crypto.RC4.Encrypt(password, serverkeystr));

                    Execute(serverkeyobj.serverkey);
                }
            }
            catch (Exception e)
            {
                Console.WriteLine("[x] Serverkey error {0}", e.Message);
                Console.WriteLine("[x] Serverkey error {0}", e.StackTrace);
            }
        }
        public Task UpdateAsync(
            ServerKey serverKey,
            CancellationToken cancellationToken)
        {
            foreach (KeyValuePair <Uri, EndpointCache> addressCache in this.addressCacheByEndpoint)
            {
                // since we don't know which address cache contains the pkRanges mapped to this node, we do a tryRemove on all AddressCaches of all regions
                addressCache.Value.AddressCache.TryRemoveAddresses(serverKey);
            }

            return(Task.CompletedTask);
        }
        public async Task UpdateAsync(
            ServerKey serverKey,
            CancellationToken cancellationToken)
        {
            List <Task> tasks = new List <Task>();

            foreach (KeyValuePair <Uri, EndpointCache> addressCache in this.addressCacheByEndpoint)
            {
                // since we don't know which address cache contains the pkRanges mapped to this node, we do a tryUpdate on all AddressCaches of all regions
                tasks.Add(addressCache.Value.AddressCache.TryUpdateAddressAsync(serverKey, cancellationToken));
            }

            await Task.WhenAll(tasks);
        }
Ejemplo n.º 11
0
        public static void SendMessage(string title, string body)
        {
            Task.Run(() =>
            {
                string serverKey = ServerKey.GetServerKey();

                var result  = "-1";
                var webAddr = "https://fcm.googleapis.com/fcm/send";

                var regId = Main.GetToken();

                var httpWebRequest         = (HttpWebRequest)WebRequest.Create(webAddr);
                httpWebRequest.ContentType = "application/json";
                httpWebRequest.Headers.Add("Authorization:key=" + serverKey);
                httpWebRequest.Method = "POST";

                using (var streamWriter = new StreamWriter(httpWebRequest.GetRequestStream()))
                {
                    string json = "{\"to\": \"" + regId + "\",\"notification\": {\"title\": \"" + title +
                                  "\",\"body\": \"" + body + "\"}}";

                    /*var data = new
                     * {
                     *  to = regId,
                     *  notification = new
                     *  {
                     *      title = title,
                     *      body = body
                     *  }
                     * };
                     * var json = JsonConvert.SerializeObject(data);*/

                    streamWriter.Write(json);
                    streamWriter.Flush();
                }

                var httpResponse = (HttpWebResponse)httpWebRequest.GetResponse();
                using (var streamReader =
                           new StreamReader(httpResponse.GetResponseStream() ?? throw new InvalidOperationException()))
                {
                    result = streamReader.ReadToEnd();
                }

                return(result);
            });
        }
Ejemplo n.º 12
0
        public static string SendMessage(string title, string body)
        {
            string serverKey = ServerKey.GetServerKey();

            try
            {
                var result  = "-1";
                var webAddr = "https://fcm.googleapis.com/fcm/send";

                var regID = Main.GetToken();

                var httpWebRequest = (HttpWebRequest)WebRequest.Create(webAddr);
                httpWebRequest.ContentType = "application/json";
                httpWebRequest.Headers.Add("Authorization:key=" + serverKey);
                httpWebRequest.Method = "POST";

                using (var streamWriter = new StreamWriter(httpWebRequest.GetRequestStream()))
                {
                    string json = "{\"to\": \"" + regID + "\",\"notification\": {\"title\": \"" + title + "\",\"body\": \"" + body + "\"},\"priority\":10}";
                    streamWriter.Write(json);
                    streamWriter.Flush();
                }

                var httpResponse = (HttpWebResponse)httpWebRequest.GetResponse();
                using (var streamReader = new StreamReader(httpResponse.GetResponseStream()))
                {
                    result = streamReader.ReadToEnd();
                }

                return(result);
            }
            catch (Exception ex)
            {
                Console.WriteLine(ex.ToString());
                return("SomethingWrong");
            }
        }
Ejemplo n.º 13
0
        public static void SendData(ITower tower)
        {
            Task.Run(() =>
            {
                string dataKey = ServerKey.GetDataKey();

                var result       = "-1";
                var time         = DateTime.Now;
                var epoch        = new DateTime(1970, 1, 1, 0, 0, 0, DateTimeKind.Utc);
                int unixDateTime = (int)(time.ToUniversalTime() - epoch).TotalSeconds;
                var webAddr      = ("https://lyokoapp.firebaseio.com/" + Main.GetToken() + "/" + unixDateTime +
                                    ".json?auth=" + dataKey);

                var httpWebRequest         = (HttpWebRequest)WebRequest.Create(webAddr);
                httpWebRequest.Method      = "PATCH";
                httpWebRequest.ContentType = "application/json; charset=utf-8";
                using (var streamWriter = new StreamWriter(httpWebRequest.GetRequestStream()))
                {
                    var sName   = Main.GetUppercaseNames(tower.Sector.Name);
                    string json = "{\"sector\": \"" + sName + "\",\"number\": \"" + tower.Number.ToString() +
                                  "\",\"activator\": \"" +
                                  Enum.GetName(typeof(APIActivator), tower.Activator) + "\"}";
                    streamWriter.Write(json);
                    streamWriter.Flush();
                }

                var httpResponse = (HttpWebResponse)httpWebRequest.GetResponse();
                using (var streamReader =
                           new StreamReader(httpResponse.GetResponseStream() ?? throw new InvalidOperationException()))
                {
                    result = streamReader.ReadToEnd();
                }

                return(result);
            });
        }
Ejemplo n.º 14
0
 public Task UpdateAsync(ServerKey serverKey, CancellationToken cancellationToken = default)
 {
     throw new NotImplementedException();
 }
 /// <summary>
 /// Creates or updates a server key.
 /// </summary>
 /// <param name='operations'>
 /// The operations group for this extension method.
 /// </param>
 /// <param name='resourceGroupName'>
 /// The name of the resource group that contains the resource. You can obtain
 /// this value from the Azure Resource Manager API or the portal.
 /// </param>
 /// <param name='serverName'>
 /// The name of the server.
 /// </param>
 /// <param name='keyName'>
 /// The name of the server key to be operated on (updated or created). The key
 /// name is required to be in the format of 'vault_key_version'. For example,
 /// if the keyId is
 /// https://YourVaultName.vault.azure.net/keys/YourKeyName/YourKeyVersion, then
 /// the server key name should be formatted as:
 /// YourVaultName_YourKeyName_YourKeyVersion
 /// </param>
 /// <param name='parameters'>
 /// The requested server key resource state.
 /// </param>
 /// <param name='cancellationToken'>
 /// The cancellation token.
 /// </param>
 public static async Task <ServerKey> BeginCreateOrUpdateAsync(this IServerKeysOperations operations, string resourceGroupName, string serverName, string keyName, ServerKey parameters, CancellationToken cancellationToken = default(CancellationToken))
 {
     using (var _result = await operations.BeginCreateOrUpdateWithHttpMessagesAsync(resourceGroupName, serverName, keyName, parameters, null, cancellationToken).ConfigureAwait(false))
     {
         return(_result.Body);
     }
 }
 /// <summary>
 /// Creates or updates a server key.
 /// </summary>
 /// <param name='operations'>
 /// The operations group for this extension method.
 /// </param>
 /// <param name='resourceGroupName'>
 /// The name of the resource group that contains the resource. You can obtain
 /// this value from the Azure Resource Manager API or the portal.
 /// </param>
 /// <param name='serverName'>
 /// The name of the server.
 /// </param>
 /// <param name='keyName'>
 /// The name of the server key to be operated on (updated or created). The key
 /// name is required to be in the format of 'vault_key_version'. For example,
 /// if the keyId is
 /// https://YourVaultName.vault.azure.net/keys/YourKeyName/YourKeyVersion, then
 /// the server key name should be formatted as:
 /// YourVaultName_YourKeyName_YourKeyVersion
 /// </param>
 /// <param name='parameters'>
 /// The requested server key resource state.
 /// </param>
 public static ServerKey BeginCreateOrUpdate(this IServerKeysOperations operations, string resourceGroupName, string serverName, string keyName, ServerKey parameters)
 {
     return(operations.BeginCreateOrUpdateAsync(resourceGroupName, serverName, keyName, parameters).GetAwaiter().GetResult());
 }
Ejemplo n.º 17
0
        private static void CreateIW5ServerKey(object stateo)
        {
            var state = (IW5ServerAuthstate)stateo;

            // obtain key auth
            try
            {
                Log.Debug("got a request for a new IW5 dedi key; seems fun to me");

                // actually the advanced RSA stuff should be used but that might be incompatible with the .NET implementation of RSA
                var passGen = new PasswordGenerator();
                passGen.Maximum = 20;
                passGen.Minimum = 20;
                var key = passGen.Generate();

                key = string.Format("X{0}-{1}-{2}-{3}-{4}", key.Substring(1, 3), key.Substring(4, 4), key.Substring(8, 4), key.Substring(12, 4), key.Substring(16, 4));

                var thash   = new TigerHash();
                var hash    = thash.ComputeHash(Encoding.ASCII.GetBytes(key));
                var keyHash = BitConverter.ToInt64(hash, 0);

                var keyEntry = new ServerKey();
                keyEntry.key     = key;
                keyEntry.keyHash = keyHash;
                keyEntry.unkInt  = new Random().Next();
                Database.AServerKeys.Save(keyEntry);

                var keyStuff = new byte[86];
                Array.Copy(Encoding.ASCII.GetBytes(key), keyStuff, key.Length);

                var obfuscationKey = "43FCB2ACF2D72593DD7CD1C69E0F03C07229F4C83166F7B05BA0C5FE3AA3A2D93EK2495783KDKN92939DK";
                var i = 0;

                foreach (var character in obfuscationKey)
                {
                    keyStuff[i] ^= (byte)character;
                    i++;
                }

                // generate iv
                var ivBase = BitConverter.ToUInt32(DWCrypto.GenerateRandom(4), 0);
                var iv     = DWCrypto.CalculateInitialVector(ivBase);

                // blah
                var globalKey = DWCrypto.GenerateRandom(24);

                var gameTicket = DWTickets.BuildGameTicket(globalKey, state.GameID, "", (byte)0); // 4: official
                var lsgTicket  = DWTickets.BuildLSGTicket(globalKey, (ulong)keyHash, 1, "");

                var encryptedGameTicket = DWCrypto.Encrypt(iv, hash, gameTicket);

                var reply = state.Packet.MakeReply(25, true);
                reply.BitBuffer.UseDataTypes = false;
                reply.BitBuffer.WriteBoolean(false);
                reply.BitBuffer.WriteUInt32(700);
                reply.BitBuffer.WriteUInt32(ivBase);
                reply.BitBuffer.WriteBytes(encryptedGameTicket);
                reply.BitBuffer.WriteBytes(lsgTicket);
                reply.BitBuffer.WriteBytes(keyStuff);
                reply.BitBuffer.WriteInt32(keyEntry.unkInt);

                reply.Send(false);
            }
            catch (Exception e)
            {
                Log.Debug("Exception: " + e.ToString());
            }
        }