Esempio n. 1
0
        public static void DownloadBinary(Hashtable htDbBinaryConfig)
        {
            HttpRequest  request  = HttpContext.Current.Request;
            HttpResponse response = HttpContext.Current.Response;

            if ((request.HttpMethod.ToUpper() != "GET") && (request.HttpMethod.ToUpper() != "HEAD"))
            {
                response.AppendHeader("Allow", "GET, HEAD");
                ResponseError(response, 405, "Method Not Allowed");
                return;
            }
            string parametersString = GetParameters(request).TrimEnd('/').TrimStart('/').Replace("-", "+").Replace("_", "/");    /* Replace invalid URL chars */

            parametersString = SymmCryptHelper.DecryptWithAES256FixedIV(BinaryContentUtils.DatabaseBinaryEnvironmentPassword, parametersString, Convert.FromBase64String(PRIVATE_SALT));

            var parameters = parametersString.Split('/');

            if (parameters.Length < 3)
            {
                ResponseError(response, 400, "Bad Request");
                return;
            }

            var entity    = parameters[0].ToLower();
            var attribute = parameters[1].ToLower();
            var id        = parameters[2];

            object objt = htDbBinaryConfig[entity + "/" + attribute];

            if (objt == null)
            {
                ResponseError(response, 404, "Not Found");
                return;
            }

            DbBinaryConfig dbBinaryConfig;

            dbBinaryConfig = (DbBinaryConfig)objt;

            byte[] buffer = GetDatabaseBinaryAttribute(id, dbBinaryConfig);
            if (buffer == null)
            {
                ResponseError(response, 404, "Not Found");
            }
            else
            {
                string md5Hash = SecureHashHelper.Hash(buffer);
                response.Clear();
                response.StatusCode  = 200; //OK
                response.ContentType = RuntimePlatformUtils.GetMIMEType(buffer);
                response.AppendHeader("ETag", "\"" + md5Hash + "\"");
                response.AppendHeader("Accept-Ranges", "none");
                if (request.HttpMethod.ToUpper() == "GET")
                {
                    BinaryWrite(response, buffer);
                }
                End(response);
            }
        }
        /// <summary>
        ///     Stores a refresh token hash for a user.
        /// </summary>
        /// <param name="userId">The user id.</param>
        /// <param name="refreshToken">The unhashed refresh token.</param>
        public async Task StoreRefreshTokenHashAsync(Guid userId, string refreshToken)
        {
            var sql = @"
                UPDATE  application.user_up_to_date AS u
                SET     refresh_token_hash = @refresh_token_hash
                WHERE   u.id = @user_id";

            await using var context = await CreateNewDatabaseContext(sql);

            context.AddParameterWithValue("user_id", userId);
            context.AddParameterWithValue("refresh_token_hash", SecureHashHelper.Hash(refreshToken));

            await context.NonQueryAsync(hasRowGuard : true);
        }
Esempio n. 3
0
        internal unsafe static void Init()
        {
            lock (s_initlock)
            {
                if (s_initialized)
                {
                    return;
                }

                string assembly_path = AssemblyUtility.TrinityCorePath;
#if !CORECLR
                string native_assembly_name = "Trinity.C.dll";
                string trinity_c_path       = Path.Combine(assembly_path, native_assembly_name);
                bool   found = false;

                if (File.Exists(trinity_c_path))
                {
                    using (Stream resourceStream = GetTrinityCAssembly(native_assembly_name))
                    {
                        string embedded_sha = SecureHashHelper.GetSHA512(resourceStream).Trim().ToLowerInvariant();
                        string ondisk_sha   = SecureHashHelper.GetFileSHA512(trinity_c_path).Trim().ToLowerInvariant();
                        if (embedded_sha.Equals(ondisk_sha))
                        {
                            found = true;
                        }
                    }
                }

                if (!found)
                {
                    ReleaseNativeAssembly(native_assembly_name, trinity_c_path);
                }
#endif

                fixed(char *pAssemblyPath = AssemblyUtility.MyAssemblyPath)
                {
                    __INIT_TRINITY_C__(pAssemblyPath);
                }

                if (Environment.OSVersion.Platform == PlatformID.Win32NT)
                {
                    Win32.NativeAPI.timeBeginPeriod(1);
#if !CORECLR
                    Register();
#endif
                }

                s_initialized = true;
            }
        }
        /// <summary>
        ///     Validates if a hashed refresh token matches the stored
        ///     refresh token hash in our data store.
        /// </summary>
        /// <remarks>
        ///     The hash value is retrieved from the database in order
        ///     to extract the salt used in the hashing algorithm.
        /// </remarks>
        /// <param name="userId">The user id.</param>
        /// <param name="refreshToken">The unhashed refresh token to check.</param>
        public async Task <bool> ValidateRefreshTokenAsync(Guid userId, string refreshToken)
        {
            var sql = @"
                SELECT  u.refresh_token_hash
                FROM    application.user_up_to_date AS u
                WHERE   u.id = @user_id";

            await using var context = await CreateNewDatabaseContext(sql);

            context.AddParameterWithValue("user_id", userId);

            await using var reader = await context.ReaderAsync();

            var saltWithHash = reader.GetSafeString(0);

            // Check hash.
            return(SecureHashHelper.DoesHashMatch(saltWithHash, refreshToken));
        }
Esempio n. 5
0
        static TrinityC()
        {
            if (Environment.OSVersion.Platform == PlatformID.Win32NT)
            {
                string assembly_path  = Path.GetDirectoryName(Assembly.GetExecutingAssembly().Location);
                string trinity_c_md5  = Resources.Trinity_C_sha512.Trim().ToLowerInvariant();
                string trinity_c_path = Path.Combine(assembly_path, "Trinity.C.dll");

                bool found = false;

                if (File.Exists(trinity_c_path))
                {
                    string md5 = SecureHashHelper.GetFileSHA512(trinity_c_path).Trim().ToLowerInvariant();
                    if (trinity_c_md5.Equals(md5))
                    {
                        found = true;
                    }
                }

                if (!found)
                {
                    Assembly assembly       = Assembly.GetExecutingAssembly();
                    Stream   resourceStream = assembly.GetManifestResourceStream("Trinity.Trinity.C.dll");
                    try
                    {
                        using (FileStream fs = new FileStream(trinity_c_path, FileMode.Create))
                        {
                            resourceStream.CopyTo(fs);
                            fs.Flush();
                        }
                        if (resourceStream != null)
                        {
                            resourceStream.Dispose();
                        }
                    }
                    catch (Exception)
                    {
                        Console.WriteLine("Trinity.C cannot be released, please make sure the working directory is writable.");
                        Win32.NativeAPI.timeEndPeriod(1);
                        Environment.Exit(0);
                    }
                }
            }
        }
Esempio n. 6
0
 /**
  * It should be ok to truncate the hash to a shorter length since we are not worried about collisions here,
  * just trying to force different hashes when the content is updated.
  *
  * FIPS 180-4 (http://csrc.nist.gov/publications/fips/fips180-4/fips-180-4.pdf) specifies that:
  * "Some application may require a hash function with a message digest length different than those provided
  * by the hash functions in this Standard. In such cases, a truncated message digest may be used, whereby a
  * hash function with a larger message digest length is applied to the data to be hashed, and the resulting
  * message digest is truncated by selecting an appropriate number of the leftmost bits".
  **/
 private static string GetBinaryContentHash(byte[] content)
 {
     return(SecureHashHelper.Hash(content).Substring(0, 20));
 }
Esempio n. 7
0
        static TrinityC()
        {
            string assembly_path = Path.GetDirectoryName(Assembly.GetExecutingAssembly().Location);

#if !CORECLR
            string native_assembly_name = "Trinity.C.dll";
#else
            string native_assembly_name = null;
            switch (Environment.OSVersion.Platform)
            {
            case PlatformID.Win32NT:
                native_assembly_name = "Trinity.dll";
                break;

            case PlatformID.Unix:
                native_assembly_name = "libTrinity.so";
                break;

            default: throw new NotImplementedException();
            }
#endif
            string trinity_c_path = Path.Combine(assembly_path, native_assembly_name);
#if !CORECLR
            string trinity_c_md5 = Resources.Trinity_C_sha512.Trim().ToLowerInvariant();

            bool found = false;
            if (File.Exists(trinity_c_path))
            {
                string md5 = SecureHashHelper.GetFileSHA512(trinity_c_path).Trim().ToLowerInvariant();
                if (trinity_c_md5.Equals(md5))
                {
                    found = true;
                }
            }

            if (found)
            {
                return;
            }
#endif
            Assembly assembly       = Assembly.GetExecutingAssembly();
            Stream   resourceStream = assembly.GetManifestResourceStream("Trinity." + native_assembly_name);
            try
            {
                using (FileStream fs = new FileStream(trinity_c_path, FileMode.Create))
                {
                    resourceStream.CopyTo(fs);
                    fs.Flush();
                }
                if (resourceStream != null)
                {
                    resourceStream.Dispose();
                }
            }
            catch (Exception)
            {
                Console.WriteLine("Trinity.C cannot be released, please make sure the working directory is writable.");
                if (Environment.OSVersion.Platform == PlatformID.Win32NT)
                {
                    Win32.NativeAPI.timeEndPeriod(1);
                }
                Environment.Exit(0);
            }
        }
Esempio n. 8
0
        internal static void Init()
        {
            lock (s_initlock)
            {
                if (s_initialized)
                {
                    return;
                }

                string assembly_path = Path.GetDirectoryName(Assembly.GetExecutingAssembly().Location);
#if !CORECLR
                string native_assembly_name = "Trinity.C.dll";
#else
                string native_assembly_name = null;
                switch (Environment.OSVersion.Platform)
                {
                case PlatformID.Win32NT:
                    native_assembly_name = "Trinity.dll";
                    break;

                case PlatformID.Unix:
                    native_assembly_name = "libTrinity.so";
                    break;

                default: throw new NotImplementedException();
                }
#endif
                string trinity_c_path = Path.Combine(assembly_path, native_assembly_name);
                bool   found          = false;
#if !CORECLR
                string trinity_c_md5 = Resources.Trinity_C_sha512.Trim().ToLowerInvariant();

                if (File.Exists(trinity_c_path))
                {
                    string md5 = SecureHashHelper.GetFileSHA512(trinity_c_path).Trim().ToLowerInvariant();
                    if (trinity_c_md5.Equals(md5))
                    {
                        found = true;
                    }
                }
#endif

                if (!found)
                {
                    ReleaseNativeAssembly(native_assembly_name, trinity_c_path);
                }

                /* native assembly is released. initialize Trinity.C now */
                __INIT_TRINITY_C__();

                if (Environment.OSVersion.Platform == PlatformID.Win32NT)
                {
                    Win32.NativeAPI.timeBeginPeriod(1);
#if !CORECLR
                    Register();
#endif
                }

                s_initialized = true;
            }
        }
Esempio n. 9
0
        internal unsafe static void Init()
        {
            lock (s_initlock)
            {
                if (s_initialized)
                {
                    return;
                }

                string assembly_path = AssemblyPath.TrinityCorePath;
#if !CORECLR
                string native_assembly_name = "Trinity.C.dll";
#else
                string native_assembly_name = null;
                switch (Environment.OSVersion.Platform)
                {
                case PlatformID.Win32NT:
                    native_assembly_name = "Trinity.dll";
                    break;

                case PlatformID.Unix:
                    native_assembly_name = "libTrinity.so";
                    break;

                default: throw new NotImplementedException();
                }
#endif
                string trinity_c_path = Path.Combine(assembly_path, native_assembly_name);
                bool   found          = false;

                if (File.Exists(trinity_c_path))
                {
                    using (Stream resourceStream = GetTrinityCAssembly(native_assembly_name))
                    {
                        string embedded_sha = SecureHashHelper.GetSHA512(resourceStream).Trim().ToLowerInvariant();
                        string ondisk_sha   = SecureHashHelper.GetFileSHA512(trinity_c_path).Trim().ToLowerInvariant();
                        if (embedded_sha.Equals(ondisk_sha))
                        {
                            found = true;
                        }
                    }
                }

                if (!found)
                {
                    ReleaseNativeAssembly(native_assembly_name, trinity_c_path);
                }

                /* native assembly is released. initialize Trinity.C now */
                fixed(char *pAssemblyPath = AssemblyPath.MyAssemblyPath)
                {
                    __INIT_TRINITY_C__(pAssemblyPath);
                }

                if (Environment.OSVersion.Platform == PlatformID.Win32NT)
                {
                    Win32.NativeAPI.timeBeginPeriod(1);
#if !CORECLR
                    Register();
#endif
                }

                s_initialized = true;
            }
        }