WCF ServiceHost restricted user netsh/httpcfg - wpf

I use a self hosted service within a WPF application for certain tasks. The service host is started at runtime and its base address is http://localhost:Whatever-port-is-free-at-runtime. This works fine when the user has admin rights but problems arise when the application is ran by a restricted user.
I found some suggestions on the web that suggested reserving the url using netsh/httpcfg which works fine for admin users but fails for restricted users because they presumably do not have the rights to use these tools to reserve a url. As the port number is not known until runtime the url reservation command can logically only be run at runtime which means the process will be initiated by a restricted user without the right privilege to execute the command. Am i correct in thinking this?
What i would like to know is if there is a suitable work around? Also, i would like to know if a restricted user can open a locally hosted WCF service at all, since solving the aforementioned problem will be pointless if the restricted user couldn't do this.
This question perfectly describes my first issue of URL reservation

In WCF, the HTTP and HTTPS bindings use HTTP.sys under the cover to reserve a required URL for a specific WCF service, which is the same path IIS itself follows while doing the bindings for the websites it manages. This explains why the process performing the HTTP/HTTPS binding is required to run in elevated mode.
That being said, I would solve your issue in two different ways:
Option 1: use a different kind of binding. NetTcpBinding and NetNamedPipesBinding, for example, do not generally require administrative privileges: this is by far the easiest way to go.
Option 2: setup the required namespace reservation at installation time. This way you may ask your users to perform the installation in elevated mode and later allow restricted accounts to run it. While performing the initial installation/reservation you may also find out an available port to use (and perhaps save it in a configuration file for later reuse).

Related

Systems that Access AD Attributes

I have been assigned a task to export the AD Attributes than find out what systems are using these attributes. I have not had much luck in scripting or a tool that can provide just that. Is this feasible and if so how? I have already exported attributes. Just need to find what systems are using them.
This isn't possible with any reasonable accuracy, especially if "using" isn't defined for you.
The event logs on the domain controllers will tell you where login events are coming from, but only by IP. That doesn't tell you which application is authenticating. You would have to do monitoring on that computer and see which application is making the connection. But then the logs would be cluttered with connections made by Windows itself, or Exchange (if you use Exchange for email). It it would be very difficult to identify what is coming from an 3rd-party application rather than Windows itself.
Also, applications can request more information than they need. It's very easy when programming with LDAP to request every attribute for an object, even if you only intend to use one. For example, take this C# code:
var de = new DirectoryEntry("LDAP://example.com");
Console.WriteLine(de.Properties["name"].Value);
That only "uses" the name attribute. But because of the way LDAP works, it actually requests every non-constructed attribute that has a value. (there is a way to specifically ask for only one attribute, but you have to know that and use that)
So even if you could find logs saying that "this IP requested all of these attributes", and then figure out which application made that request, that doesn't mean it "used" all of those attributes.

C# SQL connection string best practice

I have a winforms application that connects to a database with a connection string and a generic user
"Database=DBADAS;Server=TMT123\\SQLEXPRESS;User ID=user; Password=*****;
After connecting into the database with a login dialog, we check if the user and password are existent in the user table from the database.
My question is now if this is a good practice? because basically in the connection string there is every information needed to crack the server.
There are a few ways to go about this safely. Since it's a Winforms app and not a web application, most of your security risks involve someone already in your network peeking at the connection string. This adds a layer of security in and of itself.
1. Hardcoded
You can hardcode the connection string that fetches the users into a DLL and make your application depend on that DLL. I only suggest this because it sounds like the "generic user" password is permanent; otherwise, you'd have to recompile code every time you changed the password, then deploy again. This is very secure, however, as the value isn't stored in plain text.
2. App.Config
You can stick it in a configuration file. Within a secured network, this is probably the most versatile option, as you can store multiple strings and easily update them without updating the full application. This goes well alongside settings like a "DebugMode" setting, etc. Using App.Config or another XML file is ideal, but you can roll a quick and dirty .txt file, too.
3. Database
Probably the most secure way of all, as you can encrypt your database and code your programs to fetch their connection strings and login information from that database by using an unrelated login. This allows greater control over what can be reached by the application when a user has not yet logged in. It also prevents the software from operating outside of the network, which may be desirable.
4. Internal API
Having a separate application serve this data divorces user capability from your concerns, as the API and your app can exchange verification keys to see if your app even has permission to try to connect. This is my personal favorite, but obviously the most work to set up.
5. Registry Entry
Depending on how you have this installed, it may work well to embed the tokens you need in the Registry. This guarantees the app requires admin permissions to install, and allows you to use Windows security to restrict access to the hive.
Again, since it's an internal non-web app, I wouldn't worry too much about the plain text of the connectionstring; if someone has gotten this far into your network, chances are you have much bigger problems already. I wouldn't leave it floating as a plain text file in a local directory, but any degree of security above that is probably acceptable for your purposes.
Encrypting Web.Config
Open Command Prompt with Administrator privileges
At the CommandPrompt, enter:
cd C:\Windows\Microsoft.NET\Framework\v4.0.30319
In case your web Config is located in "D:\Articles\EncryptWebConfig" directory path, then enter the following to encrypt the ConnectionString:
ASPNET_REGIIS -pef "connectionStrings" "D:\Articles\EncryptWebConfig"
Use Aspnet_regiis.exe tool with the –pef option and specify the application path as shown above.
Note: The parameter "connectionStrings" is case sensitive.
For Winforms: You need to rename your app.config to web.config encrypt it by using steps 1 to 3 and again rename it to app.config.
Reference: https://www.codeproject.com/Tips/795135/Encrypt-ConnectionString-in-Web-Config

Ability to detect if this is the users first login to Windows 7

I have an windows application (WPF) in which we are running on each login, however when the user first logs into a new PC the application will need to do some specific tasks, but only on the users first login and never on subsequent times.
Is there a way in .Net 3.5 to query wether the user has logged in before (ie some kind of login count)?
Failing any native support I will create a txt file in the users registry however I wanted to know if there is a native way of achieving this first.
We use redirected folders so the user may have already logged into a PC on our network these special events should only occur when the user hasnt logged in onto the PC and Windows has had to create a new profile for the user on the PC.
If I am not clearly explaining what I am seeking, please dont hesiate in letting me know.
Matt
Failing any native support I will create a txt file in the users registry however I wanted to know if there is a native way of achieving this first.
I'd recommend going with this option. Don't try to detect it, just create your own state on first run.
I suggest this, not because it is technically impossible to achieve the functionality you describe, but because it is a better user experience. It provides an easy way to re-do the action without having to recreate the user.
... a txt file in the users registry ...
I'm not sure what this means. You can create text files under the user's profile directory, and you can insert string values in the registry (but not files of any sort).
As for the particular mechanism, I suggest you consider:
An App.Config value. Clearing out the value is easier to support or batch-script than a registry value, and makes the user less scared that their machine will explode if you have to tell them to edit the settings. Users are scared of the registry.
A sentinel text file under the user profile directory. Wiping out the file is super-easy to support and batch-script. Instead of editing a text file, they can just delete one. But this makes it so you have multiple config mechanisms, so multiple points of failure. I'd only do this if I were using the App.Config for additional settings in the program and thought the user wouldn't be technical enough to hand edit it.
The windows registry. Remote registry access might be easier than remote file access, if you're having to do remote troubleshooting. It also might be easier to mess with via group policy, in case this is an intranet app and you need to force a re-run on all machines in your org.
I'd carefully consider my options and which is most likely to ease support (be understandable by my users) before committing to one. I'd also consider the remote-troubleshooting/remote reset scenario.
This may not be what you're looking for but I'm hoping it will help you anyway.. I do not know from the top of my head how to do this in WPF but I do know you can use an "unattend.xml" file and the FirstLogonCommands to execute a script or application on first logon. I have used this for Windows 7, it may not apply to XP.

Logging when application is running as XBAP?

Anybody here has actually implemented any logging strategy when application is running as XBAP ? Any suggestion (as code) as to how to implement a simple strategy base on your experience.
My app in desktop mode actually logs to a log file (rolling log) using integrated asop log4net implementation but in xbap I can't log cause it stores the file in cache (app2.0 or something folder) so I check if browser hosted and dont log since i dont even know if it ever logs...(why same codebase)....if there was a way to push this log to a service like a web service or post error to some endpoint...
My xbap is full trust intranet mode.
I would log to isolated storage and provide a way for users to submit the log back to the server using either a simple PUT/POST with HttpWebRequest or, if you're feeling frisky, via a WCF service.
Keep in mind an XBAP only gets 512k of isolated storage so you may actually want to push those event logs back to the server automatically. Also remember that the XBAP can only speak back to it's origin server, so the service that accepts the log files must run under the same domain.
Here's some quick sample code that shows how to setup a TextWriterTraceListener on top of an IsolatedStorageFileStream at which point you can can just use the standard Trace.Write[XXX] methods to do your logging.
IsolatedStorageFileStream traceFileStream = new IsolatedStorageFileStream("Trace.log", FileMode.OpenOrCreate, FileAccess.Write);
TraceListener traceListener = new TextWriterTraceListener(traceFileStream);
Trace.Listeners.Add(traceListener);
UPDATE
Here is a revised answer due to the revision you've made to your question with more details.
Since you mention you're using log4net in your desktop app we can build upon that dependency you are already comfortable working with as it is entirely possible to continue to use log4net in the XBAP version as well. Log4net does not come with an implementation that will solve this problem out of the box, but it is possible to write an implementation of a log4net IAppender which communicates with WCF.
I took a look at the implementation the other answerer linked to by Joachim Kerschbaumer (all credit due) and it looks like a solid implementation. My first concern was that, in a sample, someone might be logging back to the service on every event and perhaps synchronously, but the implementation actually has support for queuing up a certain number of events and sending them back to the server in batch form. Also, when it does send to the service, it does so using an async invocation of an Action delegate which means it will execute on a thread pool thread and not block the UI. Therefore I would say that implementation is quite solid.
Here's the steps I would take from here:
Download Joachim's WCF appender implementation
Add his project's to your solution.
Reference the WCFAppender project from your XBAP
Configure log4net to use the WCF appender. Now, there are several settings for this logger so I suggest checking out his sample app's config. The most important ones however are QueueSize and FlushLevel. You should set QueueSize high enough so that, based on how much you actually are logging, you won't be chattering with the WCF service too much. If you're just configuring warnings/errors then you can probably set this to something low. If you're configuring with informational then you want to set this a little higher. As far as FlushLevel you should probably just set this to ERROR as this will just guarantee that no matter how big the queue is at the time an error occurs everything will be flushed at the moment an error is logged.
The sample appears to use LINQ2SQL to log to a custom DB inside of the WCF service. You will need to replace this implementation to log to whatever data source best suits your needs.
Now, Joachim's sample is written in a way that's intended to be very easy for someone to download, run and understand very quickly. I would definitely change a couple things about it if I were putting it into a production solution:
Separate the WCF contracts into a separate library which you can share between the client and the server. This would allow you to stop using a Visual Studio service reference in the WCFAppender library and just reference the same contract library for the data types. Likewise, since the contracts would no longer be in the service itself, you would reference the contract library from the service.
I don't know that wsHttpBinding is really necessary here. It comes with a couple more knobs and switches than one probably needs for something as simple as this. I would probably go with the simpler basicHttpBinding and if you wanted to make sure the log data was encrypted over the wire I would just make sure to use HTTPS.
My approach has been to log to a remote service, keyed by a unique user ID or GUID. The overhead isn't very high with the usual async calls.
You can cache messages locally, too, either in RAM or in isolated storage -- perhaps as a backup in case the network isn't accessible.
Be sure to watch for duplicate events within a certain time window. You don't want to log 1,000 copies of the same Exception over a period of a few seconds.
Also, I like to log more than just errors. You can also log performance data, such as how long certain functions take to execute (particularly out-of-process calls), or more detailed data in response to the user explicitly entering into a "debug and report" mode. Checking for calls that take longer than a certain threshold is also useful to help catch regressions and preempt user complaints.
If you are running your XBAP under partial trust, you are only allowed to write to the IsolatedStorage on the client machine. And it's just 512 KB, which you would probably want to use in a more valuable way (than for logging), like for storing user's preferences.
You are not allowed to do any Remoting stuff as well under partial trust, so you can't use log4net RemotingAppender.
Finally, under partial trust XBAP you have WebPermission to talk to the server of your app origin only. I would recommend using a WCF service, like described in this article. We use similar configuration in my current project and it works fine.
Then, basically, on the WCF server side you can do logging to any place appropriate: file, database, etc. You may also want to keep your log4net logging code and try to use one of the wcf log appenders available on the internets (this or this).

FindByIdentity in System.DirectoryServices.AccountManagment Memory Issues

I'm working on an active directory managament application. In addition to the typical Create A New User, Enable/Disable an account, reset my password etc. it also managages application permissions for all of the clients web applications. Application management is handled by thousands of AD groups such as which are built from 3 letter codes for the application, section and site, there are also hundreds of AD groups which determine which applications and locations a coordinator can grant rights to. All of these groups in turn belong to other groups so I typically filter the groups list with the MemberOf property to find the groups that a user directly belongs to (or everyone has rights to do everything). I've made extensive use of the System.DirectoryServices.AccountManagment namespace using the FindByIdentity method in 31 places throughout the application. This method calls a private method FindPrincipalByIdentRefHelper on the internal ADStoreCtx class. A SearchResultCollection is created but not disposed so eventually typically once or twice a day the web server runs out of memory and all of the applications on the web server stop responsing until iis is reset because the resources used by the com objects aren't ever relased.
There are places where I fall back to the underlying directory objects, but there are lot of places where I'm using the properties on the Principal - it's a vast improvement over using the esoteric ad property names in the .Net 2.0 Directory services code.
I've contacted microsoft about the problem and it's been fixed in .Net 4.0 but they don't currently have plans to fix it in 3.5 unless there is intrest in the community about it.
I only found information about it in a couple of places
the MDSN documentation in the community content state's there is a memory leak at the bottom (guess I should have read that before using the the method)
http://msdn.microsoft.com/en-us/library/bb345628.aspx
And the class in question is internal and doesn't expose SearchResultsCollection outside the offending method so I can't get at the results to dispose them or inherit from the class and override the method.
So my questions are
Has anyone else encountered this problem? If so were you able to work around it?
Do I have any option besides rewriting the application not using any of the .Net 3.5 active directory code?
Thanks
I have encountered the same error, and no, I don't have a workaround other than using the DirectoryEntry approach.
Wrap your calls to directorysearcher inside a using block and also wrap the resultcollection inside a using block and call .Dispose() on the results explicitly. See answer here:
Memory Leak when using PrincipalSearcher.FindAll()

Resources