Example #1
0
        public override void Terminate()
        {
            menuItemCopyKey.Click   -= MenuItemCopyKey_Click;
            menuItemDeleteKey.Click -= MenuItemDeleteKey_Click;

            host.KeyProviderPool.Remove(symKeyProvider);
            symKeyProvider = null;

            TokenEngine?.Dispose();
            TokenEngine = null;

            host = null;
        }
Example #2
0
        public override bool Initialize(IPluginHost host)
        {
            try
            {
                this.host = host ?? throw new ArgumentNullException("Invalid initialization data.");

                var initResult = TokenEngine.CreateTokenEngineAsync().Result;
                TokenEngine = initResult.Instance;

                host.KeyProviderPool.Add(symKeyProvider = new SymmetricKeyProvider(this));
            }
            catch (Exception e)
            {
                MessageBox.Show($"Failed to initialize plugin." +
                                $"{Environment.NewLine}{Environment.NewLine}Please make sure that the digitronic Token Engine is installed and working properly." +
                                $"{Environment.NewLine}{Environment.NewLine}({e.GetRelevantMessage()})"
                                , "Token Engine Key Provider", MessageBoxButtons.OK, MessageBoxIcon.Error);
                return(false);
            }

            return(true);
        }
Example #3
0
        /// <summary>
        /// Execute the response result.
        /// </summary>
        /// <param name="context">HTTP controller context</param>
        /// <remarks>Invoked by <see cref="ControllerFactory"/> to process the response.</remarks>
        public override void ExecuteResult(IControllerContext context)
        {
            if (context == null)
            {
                throw new ArgumentNullException("context");
            }

            // only handle GET and HEAD
            if (!context.HttpContext.Request.HttpMethod.ToUpper().Equals("GET") &&
                !context.HttpContext.Request.HttpMethod.ToUpper().Equals("HEAD"))
            {
                return;
            }

            var header = context.HttpContext.Request.Headers["If-Modified-Since"];

            // TODO: Build reliable date parser
            var time = DateTime.MinValue;
            //var time = header != null
            //               ? ParseUtility.TryParseDateTime(header)
            //               : DateTime.MinValue;

            var    fileContext  = new FileContext(context.HttpContext.Request, time);
            string fileNamePath = string.Concat(@"\winfs\",
                                                Constants.HTTP_WEB_ROOT_FOLDER, @"\",
                                                Constants.HTTP_WEB_VIEWS_FOLDER, @"\",
                                                context.ControllerName.Replace("Controller", String.Empty), @"\",
                                                context.ActionName, @".html");

            _fileService.GetFile(fileContext, fileNamePath);
            if (!fileContext.IsFound)
            {
                context.HttpContext.Response.StatusCode        = (int)HttpStatusCode.InternalServerError;
                context.HttpContext.Response.StatusDescription = string.Concat("Failed to find view '", fileContext.Filename, ".");
                return;
            }

            var mimeType = MimeTypeProvider.Instance.Get(fileContext.Filename);

            if (mimeType == null || mimeType != "text/html")
            {
                context.HttpContext.Response.StatusCode        = (int)HttpStatusCode.UnsupportedMediaType;
                context.HttpContext.Response.StatusDescription = string.Concat("File type '", Path.GetExtension(fileContext.Filename), "' is not supported.");
                return;
            }

            context.HttpContext.Response.AddHeader("Last-Modified", fileContext.LastModifiedAtUtc.ToString("R"));
            context.HttpContext.Response.AddHeader("Accept-Ranges", "bytes");
            context.HttpContext.Response.AddHeader("Content-Disposition", "inline;filename=\"" + Path.GetFileName(fileContext.Filename) + "\"");
            context.HttpContext.Response.ContentType = mimeType;

            //  Parse tokens from file content
            using (StreamReader sr = new StreamReader(fileContext.FileStream))
            {
                TokenEngine  content = new TokenEngine(sr.ReadToEnd(), context.ViewData);
                MemoryStream body    = new MemoryStream(Encoding.UTF8.GetBytes(content.ToString()));
                context.HttpContext.Response.Body          = body;
                context.HttpContext.Response.ContentLength = (int)body.Length;
            }

            // Do not include a body when the client only want's to get content information.
            if (context.HttpContext.Request.HttpMethod.ToUpper().Equals("HEAD") && context.HttpContext.Response.Body != null)
            {
                context.HttpContext.Response.Body.Dispose();
                context.HttpContext.Response.Body = null;
            }
        }
Example #4
0
        private void MenuItemDeleteKey_Click(object sender, EventArgs e)
        {
            var title = "Clean up all tokens";

            try
            {
                if (MessageBox.Show("Are you sure you want clean up all connected tokens?"
                                    , title
                                    , MessageBoxButtons.YesNo
                                    , MessageBoxIcon.Question) != DialogResult.Yes)
                {
                    return;
                }


                var tokenList = Task.Run(async() =>
                {
                    var result = await TokenEngine.GetTokenListAsync();
                    foreach (var t in result)
                    {
                        await t.LoadAsync();
                        if (!t.Capability.IsInitialized || !t.Capability.IsObjectAPISupported || t.Capability.IsObjectAPIIsReadOnly)
                        {
                            continue;
                        }
                    }
                    return(result.Where(t => t.Capability.IsInitialized || t.Capability.IsObjectAPISupported || !t.Capability.IsObjectAPIIsReadOnly).ToList());
                }).Result;

                if (tokenList.Count == 0)
                {
                    if (MessageBox.Show("No token was found. Please connect a token."
                                        , title
                                        , MessageBoxButtons.OK
                                        , MessageBoxIcon.Question) != DialogResult.Yes)
                    {
                        return;
                    }
                }

                var errorMessage = Task.Run(async() =>
                {
                    foreach (var token in tokenList)
                    {
                        try
                        {
                            var objs = await token.FindObjectsAsync(isPrivate: true);
                            await Task.WhenAll(objs.Select(async x => await x.DeleteAsync()));
                        }
                        catch (Exception ex)
                        {
                            return(ex.Message);
                        }
                    }

                    return(string.Empty);
                }).Result;

                if (!string.IsNullOrEmpty(errorMessage))
                {
                    throw new Exception(errorMessage);
                }

                MessageBox.Show($"All connected tokens have been cleaned up."
                                , title
                                , MessageBoxButtons.OK
                                , MessageBoxIcon.Information);
            }
            catch (Exception ex)
            {
                var exception = ex;
                if (ex.InnerException != null)
                {
                    exception = ex.InnerException;
                }
                MessageBox.Show($"An error occurred:{Environment.NewLine}{exception.Message}"
                                , title
                                , MessageBoxButtons.OK
                                , MessageBoxIcon.Error);
            }
        }
Example #5
0
        private void MenuItemCopyKey_Click(object sender, EventArgs e)
        {
            var title = "Copy Last Key";

            try
            {
                var result = MessageBox.Show("Are you sure you want to copy the last key used to the current token?"
                                             , title
                                             , MessageBoxButtons.YesNo
                                             , MessageBoxIcon.Question);

                if (result != DialogResult.Yes)
                {
                    return;
                }

                if (symKeyProvider.ProtectedLastProvidedKey == null)
                {
                    throw new Exception("No key has been used yet. Use a token to log in and try again.");
                }

                var token = Task.Run(async() =>
                {
                    foreach (var t in await TokenEngine.GetTokenListAsync())
                    {
                        await t.LoadAsync();
                        if (!t.Capability.IsInitialized || !t.Capability.IsObjectAPISupported || t.Capability.IsObjectAPIIsReadOnly)
                        {
                            continue;
                        }

                        return(t);
                    }
                    return(null);
                }).Result;

                if (token == null)
                {
                    throw new Exception("No suitable token was found.");
                }

                var errorMessage = Task.Run(async() =>
                {
                    var dataObject = (await token.FindObjectsAsync(SymmetricKeyProvider.DataObjectLabel, isPrivate: true))
                                     .FirstOrDefault();

                    if (dataObject != null)
                    {
                        return("There is already a key on the token.");
                    }

                    var key = new byte[symKeyProvider.ProtectedLastProvidedKey.Length];

                    try
                    {
                        Array.Copy(symKeyProvider.ProtectedLastProvidedKey, key, symKeyProvider.ProtectedLastProvidedKey.Length);
                        ProtectedMemory.Unprotect(key, MemoryProtectionScope.SameProcess);
                        using (var keyData = new SymmetricKeyData(key))
                        {
                            dataObject = await token.CreateObjectAsync(SymmetricKeyProvider.DataObjectLabel, keyData.RawData.Length, isPrivate: true);
                            await dataObject.SetDataAsync(keyData.RawData);
                        }
                    }
                    catch
                    {
                        try
                        {
                            await dataObject.DeleteAsync();
                        }
                        catch { }

                        throw;
                    }
                    finally
                    {
                        Array.Clear(key, 0, key.Length);
                    }

                    return(string.Empty);
                }).Result;

                if (!string.IsNullOrEmpty(errorMessage))
                {
                    throw new Exception(errorMessage);
                }

                MessageBox.Show($"The key was successfully copied to another token."
                                , title
                                , MessageBoxButtons.OK
                                , MessageBoxIcon.Information);
            }
            catch (Exception ex)
            {
                var exception = ex;
                if (ex.InnerException != null)
                {
                    exception = ex.InnerException;
                }
                MessageBox.Show($"An error occurred:{Environment.NewLine}{exception.Message}"
                                , title
                                , MessageBoxButtons.OK
                                , MessageBoxIcon.Error);
            }
        }