How to Snoop proof your wpf application? - wpf

Snoop allows you to look inside the application and change element properties.
Its a great asset for developers, but can be a security issue in some cases, like when we have users who like to look in places where they shouldn't be looking. Is there a way to do something to block applications like Snoop from "snooping" your application?
And if there is no way to block it, what do you recommend to do to minimize security risks?
Snoop is a utility that allows you browse visual tree of a wpf application and view and change properties. Its very useful when you are trying to debug something and have no idea what is going on. You can find more here.
Thank you.

There actually is a way to detect whether your application is being "snooped" by the snoop program. The solution I will give is not a silver bullet, and if someone really wants to snoop your application, they'd have to modify the snoop source code (it's an open source project).
What snoop actually does is it injects an assembly into your application, and the injected assembly recursively examines your applications visual tree starting at the root. In other words, snoop actually runs inside your application. That being said, the solution is to raise an event when the snoop assembly is injected into your application.
First, you need to subscribe to the assembly-loaded event somewhere in your application (preferably the begginging):
AppDomain.CurrentDomain.AssemblyLoad += new AssemblyLoadEventHandler(CurrentDomain_AssemblyLoad);
Then, you would implement the handler somewhat like this:
void CurrentDomain_AssemblyLoad(object sender, AssemblyLoadEventArgs args)
{
if (args.LoadedAssembly.FullName.StartsWith("ManagedInjector"))
MessageBox.Show("hey you, stop snooping");//and shut down your application.
}
You would probably need to enhance this solution for real silver-bullet solution, but at least this solution will definitely stop the current latest version of snoop being run as is (without the code modified). The better solution would be to check that no external assemblies are being injected into your application.
However, Kent is still right in the fact that a utility like Snoop should not cause any security vulnerabilities since security should not be implemented at the UI level. But at least this shows you how to prevent people from "snooping" your application.

By implementing security properly. If your "security" can be thwarted with a tool like Snoop, then you're doing it wrong.
Suppose there's a command that only certain users can execute. It sounds like the only place you're enforcing this is at the UI level (by disabling the corresponding button, for example). That being the case, you're right - I could easily use Snoop to enable the button and execute the command. But you should be enforcing the security constraints on your server, or perhaps in your command execution logic if you have no server. Basically, security should be implemented as close to the thing you're trying to protect as possible. Security at the UI level is merely for convenience of the user.

Great responses for a very good question,
I want to add an example of the password that should never be saved in your datacontext, as snoop check also the datacontext of the UI, so if you use the right control PasswordBox you will find that you can’t bind the password property, that means even if you snoop the application you can’t get the password as it is not saved in any property
But we found many people who try to create a work around (helpers, behaviors, usercontrol ...) to bind the password, but they forget that snoop can get it like that
So your server should never trust your client , every time it should check the right privilege (as we can sniff the client request using Fiddler for exp then rebuild a custome request to by pass client application security)

Related

WPF Resource Refreshing problem

I using multilanguage solution from this thread Multilanguage in WPF
But i have problem with automaticaly Resource refreshing after language was changed.
Old strings stay in old language, new is traversed propertly.
What is easiest solution to solve this problem, for example refresh all resources in application?
I've worked with localization as well. The problem with it is the changes you make in culture info while your app is running, isn't going to be shown in the UI. The values for the controls do change, but the change isn't notified to the ui of the control. For as far as i've been googling this, i haven't found a reasonable solution for offline applications. Even InitializeComponents isn't doing the trick.
The only solution, allthough i don't like that one very much, is to change the culture, then start up a batch which will close and restart the app with the chosen cultureinfo.
The reason why i don't like this is because you rely on an external file (the batch) and not all applications can just be restarted like that. But it might do the trick.
The easiest solution I've found is to simply reopen the window - if you work with MVVM all the state (or the important state anyway) is preserved in the ViewModel(s) and only the view is refreshed.
I haven't used the extension you linked to, but any of these more advanced systems should handle refresh automatically. In my case, I just used {x:Static res:ResourceName} references to the resources, and refreshed the view when the language changed. Granted, I don't allow changing the language in the more complicated screens... :)

Browser.HtmlPage.Window.Navigate is blocked but HyperlinkButton isn't - why?

I have a certain UI element, which when clicked should navigate to another URL.
I tried handling the mouse down event and execute something like this:
System.Windows.Browser.HtmlPage.Window.Navigate(new Uri("http://google.com"), "_blank");
However, this gets blocked by the browser (I tried both Chrome and Firefox) unless I disable the popup blocker.
I did some research and it seems that the browser blocks navigations that don't occur as a result of user interaction and as far as the browser is concerned this navigation is initiated by a plugin (Silverlight), not a user.
OK, makes sense. But then I tried using a HyperlinkButton instead and it was NOT blocked.
I wonder why these two approaches get different treatment from the browser. Any idea?
I actually worked around the problem by wrapping the navigation triggering UI with a HyperLinkButton, but I'm still very curious...
I'm going to pull a fancy corporate quote and say "It is a feature, not a bug."
The Silverlight team is obviously worried about Security. They don't want crazy haxorz like you and I to do crazy things with our apps--you know, like popping up a bunch of browser windows all routing people to Zombo.com. Just imagine the choir! Zombo!
Summarized from their documentation: They want us to only use the HyperlinkButton to go outside of their application. In fact, they went the extra step, and depending on our settings, they will even throw a SecurityException for us if we navigate to an outside page--Even from a HyperlinkButton. How nice.
The real question: Why the Hyperlink Button and not something else?
Only one "thing" can navigate. this take saves time for Microsoft while testing Silverlight. This one thing can navigate to both internal XAML pages and external web pages--Might as well be consistent and have only one way to do navigation.
It is a UIElement. It's code behind likes to run in the primary visual thread. It can promise the browser that a Visual Element wants to go somewhere. Microsoft can also put its limiting logic in a control that requires a mouse-click/keyboard-input event tree.
All in all, it makes sense to start simple by making a control do the work.
Fun stuff! Hope this helps you.

Microsoft UI Automation Library Vs Coded UI Test

I'm very much new to Test Automation kind of thing. Recently I've been assigned to a project where I have to write an application (or, a script may be, I'm not sure) that will automate the UI testing of a CAD-like WPF application which misses lots of AutomationIds.
After doing a little searching on MSDN and other sources I'm a bit confused about whether I should use the Microsoft UI Automation Library or the new Coded UI Test feature included in VS2010. I'm not getting the clear picture of which one of these two applies in which scenarios, what advantages one has over the other and which one suits my purpose.
Please shade some light if you have experience/knowledge on the matter. Thanks in advance.
Basically Microsoft UIA is the new accesibility library in .Net 4.0. WPF applications and controls have built-in support for UIA through the AutomationPeer class.
Coded-UI test is a Record & Play automation tool which uses the Microsoft UIA Library underneath. Since being a tool compared to writing code in C# it improves QA productivity for recording more test cases.
For applications with automation support planned into it, Coded-Ui should be sufficient. If the AutomationIDs are missing make sure the controls have some unique property like Name. Use UIVerify or Inspect to check for this.
If NO unique property is avialble, there are the other below mentioned techniques you can use in combination with Coded-UI.
From an Event
When your application receives a UI Automation event, the source object passed to your event handler is an AutomationElement. For example, if you have subscribed to focus-changed events, the source passed to your AutomationFocusChangedEventHandler is the element that received the focus. For more information, see Subscribe to UI Automation Events.
From a Point:
If you have screen coordinates (for example, a cursor position), you can retrieve an AutomationElement by using the static FromPoint method.
From a Window Handle:
To retrieve an AutomationElement from an HWND, use the static FromHandle method.
From the Focused Control:
You can retrieve an AutomationElement that represents the focused control from the static FocusedElement property.
If you can leverage and use the Coded UI Test then go that route. Make sure to verify that your given configuration is supported.
The UI Automation Library resolves everything in the code behind. This then forces you to use a tool like UISpy to gain access to the controls internals so that you can then build out your test.
A Coded UI Test on the other hand still has code behind however it allows for the recording of steps through the given application which you are testing which will greatly increase the number of tests you can create.
UI Automation library is a low-level library. Usually, you don't want to write tests against it directly as it requires a pretty decent amount of work.
I would recommend looking at more high-level libraries. You mentioned one of them - Coded UI; another good choice would be White from TestStack. They both suits different kinds of projects. Coded UI is good when you don't want to invest a lot of efforts into your test suite. At the same time, it doesn't scale much so if you are going to write a lot of tests, you are better of choosing White.
Here I compare the two frameworks in more detail: Coded UI vs White
To complement the above responses, please look at CUITE that helps quite a bit and may be an appropriate approach for you.
I began 'rolling-my-own' 'semi-framework' using the CodedUITest library and devised a paradigm for separating the details of automation from the (C#) code.
Basically, I am creating a driver that reads what needs to be done from spreadsheet(s) where each line in it is a test step (or a pointer to a scenario in a different worksheet).
At present, incomplete, but promising, I have it working against a WPF application with partial success.
One of the main problems is that the developers neglected to identify controls uniquely and consistently.
Bey

Recommendations on developing a WPF application without using MVVM or similar

We were building out the next version of an in-house thick-client application using WPF/Prism (Composite Application Library). As we were nearly done with the client our team was put under new management and shortly thereafter:
We were then directed to drop the Prism framework to keep things simple. This includes not using any type of Inversion of Control.
We were directed to build out the WPF application without using MVVM or similar; and more along the lines of a traditional WinForm application. The idea is that if a developer sees a control in Visual Studio’s designer view, then (s)he should be able to click on the control and see exactly what it's doing without having to traverse through a view-model (or similar).
We have now been tasked with building out the WPF application using one primary Window, use a Frame Control to contain the content, and use a Ribbon outside of the frame for the menu items. Reason we were provided to use Frame Control:
a. We will show a view in the Frame with a Page (not a user control) and then load the page in the Frame.
b. When a new view is to be shown in the Frame, the current view (Page) will be closed/disposed and the new view (Page) will take its place in the Frame.
c. When a developer looks at the Page in design view, (s)he will be able to click on any control and see exactly what is being done.
Given the restrictions of 1 and 2 above, we’d like to present another method of building out the application that:
Can be presented as an alternative to using the “Frame Methodology” (item 3 above) but still provides the same type of functionality.
Does not use MVVM (see #1 and #2 above).
Provided the direction we’ve been given, any suggestions as to an alternative we can present? I’d request that the responses be kept on the professional level and thank you in advance.
I'd personally try to argue to use Martin Fowler's Presentation Model. (That's a joke, btw...)
Basically, you're being given a restriction that says "Use WPF, but don't use any of the features that make WPF usable." It really sounds like your requirements are such that you would be much better off explaining, reasonably, the advantages of patterns like MVVM.
It sounds like the weird requirements are really boiling down to this:
The idea is that if a developer sees a control in Visual Studio’s designer view, then (s)he should be able to click on the control and see exactly what it's doing
If that's the main issue, and the reason you're avoiding MVVM and other similar patterns, I would seriously take the time to educate the management. Looking at a Command, by name, instead of an event, by name (which is what you see in the designer) is really no more difficult.
However, in a large scale application, the separation of concerns is key. Even a properly designed Windows Forms application requires a clean separation of concerns - but with event based programming, this becomes much more difficult, especially from the designer. If you try to develop a large scale, clean, application using an event approach, you'll have event handlers, but those event handlers will all eventually need to delegate their work to a separate component.
This is actually adding an extra level of effort, from an understandability and maintenance point of view, on top of what you get with MVVM. With MVVM, you only look to the ViewModel, which is very discoverable.
BTW - The "rationale" for using a Page instead of a UserControl doesn't make any sense. You can do exactly the same thing you're describing with UserControls... The only reason to use a Frame and Page is if you want to take advantage of navigation, in which case, you can't dispose the old pages directly (or they get regenerated constantly). Also, the navigation tools probably wouldn't be used with a ribbon - the two conceptual models are quite different.
There are criticisms of MVVM which may be applicable to your project; however having unreasonable dictates of programming methodology is always a recipe for disaster.
One of the reasons that we have frameworks and spending time building layers and separation is to avoid the coding mess that always results when you can "simply click on the button in visual studio to see the code that is being executed".
There may not be a way of achieving what you've been asked to do without something similar to MVVM, because anything that has an architecture may well be labelled as being too similar.
However I have been using a system for many years that provides simple inter-object plumbing currently called Emesary you may want to read my C# .NET Emesary walkthrough.
But basically it allows my buttons to be implemented thus:
private void addButton_Click(object sender, RoutedEventArgs e)
{
GlobalTransmitter.NotifyAll(new Notification(NotificationType.CreateRecipe));
}
This may be an answer to your problem. It's under hyped, small and so simple but it just works well.
I've achieved a solution to the second question by using a Window, a user control for the ribbon bar (the user control contains the listview), and another user control for the Frame part. This second user control obvious is built using other user controls using a very simple view class. All views and controls are connected using Emesary.
As a school project I had to develop a WPF client which allowed for multiple people to make use of it at the same time. And I used Pages. My verdict: Save yourself a huge amount of effort, and use UserControls instead.
Sometimes the Page Navigator (which you'll use to scroll through) tends to bug out and cause you a lot of problems. Maybe it was my crappy coding, but who knows?
Though I must say, the control being called "Pages" is somewhat misleading... I went "Eureka!" when I found them, and swore at them thereafter.
I totally agree with #2 (MS bigs take note!). It would be cool if you could double-click a Control and it would take you straight to its command (or event if its command is lacking). However till then, make sure that you organize your Views and ViewModels in separate folders.
Having a dual screen (or a very wide one) will allow you to have two instances of VS open on the project, one focused around the View and the other around the ViewModel (my personal choice was having Expression Blend on the View).
Although not a very big application, I managed to convert my project to proper MVVM (ie. ViewModel for every UI element, RelayCommands and Mediator) in a matter of days, so once you understand it it's not too complicated to implement. Plus, there are tools out there (such as Josh Smith's RelayCommand and Marlon Grech's Mediator - totally free, by the way) which make MVVM half as difficult, and twice as powerful.
Using WPF without MVVM is like trying to eat rice without a fork. You'd be better off using WinForms if you're not going to take advantage of what WPF has to offer. My 2 cents.
I wish I could say your management is totally wrong.. but I cannot say that as it will not be the most accurate truth. I guess that the main reason to the changes you described is either because the new manager is not comfortable with the concept of MVVM being the new messiah of UI development or/and another reason could be the cost of educated sophisticated developers vs. cheap developers which can be instructed to get the things done as fast as possible, a concept which is widely known as lean development.
So, putting all I wrote so far under "not what you asked for", here is what I suggest:
you can still use object oriented pure approach, meaning you can have a model object which already have method to show UI information. so every object will be a window derived object, that way you will loose on SOC but you still going to be OOP/OOD.
But LOL, The next phase will bring you to seperation of model from view in order to not repeat the same code in many derrived windows which relay on the same data... so your management will endorse MVC/MVP as good solution .. and the distance from it to MVVM is kinda of short if they want WPF.
Conclusion: you will have to teach your manager why it is better to go for MVVM, unless the project is very short.

Where to put code in (primarily) windowless WPF app?

So I'm planning on writing an application that is largely a windowless application. There will be windows for user interaction, but only at the request of the user. Otherwise the application sits in the system tray and runs a timer, executing some logic every minute or so. My question is this: As far as I can tell, I would put all the related logic in App.xaml.cs (starting the timer, executing the logic at each interval), but for some reason this seems wrong to me.
The app will have a system tray icon that users can interact with to get details, adjust settings, etc., but otherwise the app just sits there and does what it does. Is it appropriate to put all the code in the code-behind for the App.xaml class? I don't know why, but it seems as if I shouldn't, and there should be somewhere else, but I can't really think of anything.
I've never written an app like this before, hence my ignorance. Any advice would be greatly appreciated. Thanks.
James
Even with applications where most interaction is done through windows it's usually a bad idea to put all the code in the code behind. Interactions are often initiated eventhandlers in the code behind but you can put your code in classes you create yourself.
The same goes for applications that do not show a user interface most of the time. Most of the actions will be initiated from the App.xaml.cs but that doesn't mean all the code has to live there. You can encapsulate timers in their own classes that can kick off other code to do work for example. Divide your code up along lines of responsibilities, a window class does UI stuff, domain logic goes into other files etc. That will enable you to create more maintainable applications.
It doesn't sound like the code belongs there, and at most just a call to start the timers.
What does sound like a perfect fit for your issues, is the M-V-VM (Model - View - ViewModel) pattern. As you noteded, it also will 'feel' more correct then attaching logic to your code behind. Using MVVM you can separate your sparse UI into a View, and your code can exist separately in the Model and ViewModel.
I would recomend using the toolkit here, as it also contains good overview documents and a sample you can digest as you create your own solution. Laurent Bugnion has also released a MVVM starter toolkit that you could use to get started.
Also, here is some good stuff to get you started on actually setting up your controls in the system tray.

Resources