I'm developing the authentication/authorization architecture for several APIs.
I'm using IdentityServer4 as a Security Token Service (STS).
From what I've read from "Dominick Baier" (one of the persons that built IdentitySever4), there are only two types of Flows that should be used:
Client Credentials Flow. (machine-to-machine)
Authorization Code Flow + PCKE. (for iteractive users).
I have several C# Web API's that will communicate with each (Machine-To-Machine), and I will use the Client Credentials Flow.
But then there are some WPF Desktop Applications, that will need to access some APIs, and don't have a user.
Which flow should be used?
I've read that:
Desktop/Native & Mobile Applications should use Authorization with Authorization Code Flow (with Public Client and PKCE), since they are hosted on the Client side, and the Client/Secret is can be leaked (maybe on a Desktop application we can Encrypt the Secret? But then will need to manage a way how to store the secret that decrypts that right?)
Then I've read:
"Anytime you have a system that isn’t concerned with the end-user identity (and just needs to authenticate the system), use the OAuth2 Client Credential Grant."
For now, this is my case, I'm not concerned with the end-user identity (but maybe in a near future I will).
So since the above points conflict with each other:
- Which flow should I use?
- Can I have a Desktop Client using Clients Credential Flow and be safe?
Also, I've read a bit about Mutual TLS, If I use that, does this change which flow should I use?
You can't trust a client because you can't be sure a request originates from the client. And another problem is that clients are not good in keeping secrets. But there are different types of clients.
Clients that run on servers often having a single task, like synchronizing data which is user independent, are suitable to use the client credentials flow. To some degree they can keep a secret (running on a server).
You can use unique credentials for each instance but that doesn't make it safer. It helps you to identify the client, but doesn't add security. Security is about monitoring behaviour and detecting anomalies. Or perhaps narrowing access by filtering on ip address.
But you are not limited to use the two flows you've mentioned. Being a token provider, you can extend IdentityServer with custom flows using extension grants.
Without user the client credentials are somewhat similar to the resource owner password credentials (ROPC) flow (another option that is no longer covered in the grant type documentation but still exists, see the old docs). Neither are really safe in the sense that both can be automated. The user factor can be eliminated since user interaction isn't required for these flows.
But I wonder why your app has no user, running on a user machine. Because ideally you have a client (without secret) where the user logs in and let the client contact the api (delegation).
So there are two things: do you need to identify the client? If not you could suffice with an ApiKey, like e.g. Sendgrid. And you can never trust a client. Security has to be server side.
So basically it doesn't really matter, there is nothing you can do to make it much safer client side. The only thing you can do is add the requirement of user interaction. So perhaps now you don't need it, but it will increase security and allows you to delegate api access to the client.
This question is not about HOW something can be done. Everything is working fine. I like to know, if it is "ok" to do the authentication / authorization process inside a WCF message inspector.
Currently I am working on a client/server application with a WPF client and a self-hosted WCF server. The used protocol is Net.Tcp and all SOAP messages are AES256 message-encrypted and signed. Also all send SOAP message-headers are always message-encrypted and signed.
The complete auth process looks like this:
Both server and client are always sending certificates to authenticate each other
Client receives a list of all endpoints it can connect to
Client sends User/Pass to authenticate and gets a session-id from the login-service
The session-id, the user-id and all user-rights associated with the user-id are stored into RAM in a singleton service, which is available system-wide inside the server application.
On every further request after the first login, the client only sends the session-id and a certificate inside a custom message-header, no more user/pass combination.
The situation:
Before a request from the client reaches any webservice operation, a message inspector reads the session-id and the requested webservice operation. It then uses the available singleton-service to determine if the session-id is still valid and if the associated user-id has the right to do this webservice operation. If not a fault-exception is thrown.
The question:
Is there anything wrong, to do the authentication / authorization process inside a WCF inspector?
If its working then dont break it :) But to answer you, I have put some insights for your to consider:
1- For service operations that dont require authentication, you would have to change the inspector code to whitelist them. This contradicts with the open close principle where your class must be open for extensions and closed for modification.
2- If later on, you decide to modify your authentication mechanism and use a third party component, you would have to modify your interceptor code drastically.
I usually use the WCF inspector to pass the token and other related info into my services classes where i normally implement the cross cutting concerns (Validation, Authentication, Authorization, Logging and exception handling). When you inject your authorization engine into your services, it becomes easier for you to first swap the mechanism when need be, second unit test your service method in isolation of whatever authentication mechanism you are using.
I'm starting in .net and wcf services, sorry if what i'm asking is wrong or has nosense. By the way, sorry for my english too.
I'm trying to build several WCF services hosted on IIS where the internet clients can login with their username / password (info stored in db). When they are logged, they can access their info, see their private documents, change their profile and more actions related to their account.
Well, in asp.net if I get the session after success login, i can build services like "GetMyDocs" and i know "who is", just checking the session username stored with the session ID when he calls the login and his session don't timed-out. But i've noticed that WCF Services are stateless, so this seems i have to send in all requests the username / pwd and check them in the DB before executing the service... always!?
Later, if i want to build a client desktop / Android / iOS application, i will use those services. They then can manage their personal and private data through those apps after a success login.
How should i handle this?
Are WCF Services the way to go or WCF aren't a good choice for that?
How can i handle the user identification with WCF? Because all my services are linked to a user and "GetMyDocs", "SaveNewConfig", "PayItem"... needs to identify who is calling.
Thanks in advance!! Regards!
But i've noticed that WCF Services are stateless
This statement is kind of wrong. Because you could easily create a "WCF-based" web service with state enabled. Furthermore, state is such a broad term that is not worth covering here. For example, you could use session state with a WCF service, or you could set the InstanceContextMode property of a service to one of the following:
PerCall
PerSession
Single
and of course, it all depends on how you configure the service itself.
If your service needs to be consumed by different clients, you should consider at implementing a RESTful service along with OAuth 2.0 or something similar where you can authenticate a request using the Basic Authentication header or by issuing an access token after a successful authentication.
There are a number of ways to provide authentication to a WCF service. One of them is by using a session (basicHttp does not support session, you have to use wshttp, or any of several other transports that support session). However, enabling session is a huge amount of overhead simply to avoid sending credentials on each request.
Session reduces scalability by quite a bit, but if you aren't worried about it... it's an option.
I have a client, which calls a service (passing it a user id and password). The first service can validate these credentials against users in a database. The first service then needs to call another service, but this second service cannot be passed the user id and password given to the first service (this is a requirement outside of my control).
The services will most likely be on different domains and both exposed to the internet (so security is a big issue here).
I am therefore looking at options for how the second service should check/validate that it is being called by my first service (and not by someone else trying to impersonate it).
One idea I've had is to add an additional service that acts as an authentication service, this could issue a token that is then passed to the second service which in turn calls the authentication service to check the token. Another idea (from a colleague) has been to assign an SSL certificate to each service, and check the certificate when the call comes into Server B - I haven't seen certificates used in this way though so am not sure if it's viable.
This is still at the design stage, so I am open to alternative ideas/approaches.
If you need an easy fix, then creating an extra set of credentials for service A so that service B can be sure it's called from an authorized party without knowing the clients credentials might be enough.
In the long run, something like Windows Identity Foundation sounds exactly like your plans with the authentication service.
So, both A and B parties are exposed to the internet (distrusted environment). Taking into account security requirements what you need is mutual WCF authentication. Certificates are the easiest way to achieve the goal - your server has to ensure that proper client calls it and the client has to be sure it calls proper server (DNS attacks, etc.). That means each party must have public key of the other to authenticate. Check this article for the details on how to configure your server and client.
I was thinking about how to secure the Data Layer in a C# Application, the layer could in this case be either a LINQ to SQL Model Diagram stored with the Application itself containg the connection string to the SQL Server Database.
Or it could be connectivity between the application and webservices.
Either you need to impement some sort of security, for instance, the Connection String in a Application can easily be reverse engineered and Webservices can easily be tracked and used for other reasons than the applications original purpose.
So my question is in a shorter way: How do you solve the security issues when handling Webservices and/or direct connection to a SQL Server From a Windows Forms Application?
In your case there are two main attack possibilities:
Steal the connection string and then access the database directly
Call methods in your C# code directly without using the UI
For the connection string you need to store it in an encrypted form in a config file. Problem is that there need to be enough information in the winforms app so that it can decrypt and use it.
For accessing the code directly you can use code access security and obfuscation.
In your case I would not give the windows app direct access to the database. Let the windows app call a WCF service, the the WCF service would access the database.
The user's user account is allowed to call the WCF service, the WCF service is running under an account that is allowed to access the database, the user's user account has no rights to the database.
Windows App with 3 Layers:
UI
Business (Security check what UI should be shown to the user)
Proxy
WCF Service with 2 Layers:
Facade / Business Layer (Security check is user allowed to call this method with this data)
Entity Framework datamodel
Common dll's to both Layers
Contracts / WCF Interfaces
Data Transfer Objects
For info on proxy, contracts and DTO's see this video:
http://www.dnrtv.com/default.aspx?showNum=103
Shiraz Bhaiji came close, but I think they missed the key step.
Yes, you want access to the database to be mediated by a middle tier, exposed through WCF, which imposes whatever business logic you require, including full access control. This service does have the connection string that you want to keep secret, but it's not accessible to the WinForm clients.
The key step is that the client uses the user's authentication to gain appropriate levels of access, and never has any ability to contact the database or even get full control of the middle tier. The middle tier grants access to methods based on the groups that the client user is a member of. This means that a user with low security can call any method they like, but they'll get access denied exceptions, or data filtering, or whatever other failure mode is appropriate. The user account, on its own, has no access to the database, so the middle tier can do whatever it likes.
The obvious way to bypass this would be for the client to use the account of someone with full access. Of course, if they could do that, they'd already have what they wanted.
Hopefully, this approach would be useful in solving your problem.
edit
This solution does not allow LINQ-to-SQL in the client, just the middle tier. If that's a dealbreaker, then this isn't for you. Then again, the moment the client can access the database directly, a gigantic security door is opened up, and it's hard to close. There's a huge amount of extra work involved in securing the database itself so that it provides the sort of user-based, row-level security that comes naturally from a three-tier solution. I would generally recommend against it, although I do recognize that there are times when it is entirely appropriate.
One way would be to use a Trusted Connection to SQL Server, that way you don't store the username / password in code.
I don't think there is any one-solution-fits-all to this problem, you will need analyze and adjust your solution to the particular problem you are having.
As far as I know there are no known ways of securely storing your connection information on the client side as your client is a "trusted" part of the communication to the server. No matter how you store the information, the client has to be able to reverse it or send it directly to the server, which also means that a potential attacker can repeat the process. Also any external communication directly to your database can potentially be intercepted/hacked.
The best way I can think of to protect your data is having a webservice (over a secure connection) as middleware controlling the communication with your database(which you need to secure) and adding logic to enforce whatever level of security you wish to attain. You can make it account based to grant different levels of access if needed. But the main thing is that it only allows safe/isolated operations.
To secure the webservice(middleware) there are two concerns, authentication and isolation.
Authentication
You can use the standard .NET authentication as Steven suggested. I normally prefer rolling my own solution though for two reasons. First off, so far I've mostly ended up handling more complex users/roles. For example using permission based roles so that you can check for permissions instead of specific roles.
And second, it gives you more control. You can avoid session based authentication and you can also use challenge-response, for example challenge with a timestamp and expect a hash of the timestamp+password(which the user has to enter at application start) or some other creative combination as answer, I am sure there are better hash combinations to respond with. This should also be done two-way, to make sure that the client verifies whatever it gets from the server.
Also here are some SO topics about WCF Authorization that might be interesting:
WCF Service authorization patterns
Authorization and Authentication using WCF
WCF Authorization - access to operations via claims
And also a book and a paper (not free)
Isolation
No matter how secure your authentication is, there is always the possibility of someone being able to access your webservice for malicious intents. As far as I know there is no one solution to this problem, but it is rather dependant on the specific application and how the data is structured and shared between users.
You will need to identify layers of isolation such that users cannot affect each other or the system in general, and also how the application is used. Will clients need to write data, or only read? If they write, is written data shared in any way and in what way can you isolate/verify that data? If they read, is the information private for the user, private for the system or shared among users?
For example a system for storing medical journals or personal task lists will have very isolated data and you can restrict access to your private information only (and possibly your doctor/boss depending on user groups). In this case you can isolate all data read/writes to the particular user, thus the attacker can only affect his own data, keeping everyone else safe.
If the data is shared between users you will need some way of verifying the input that is given from the user. Preferably you should also have some kind of trust-level for the user such as SO's reputation to prevent any one-time users to attempt a hack. This is really too specific to give any good advice on.
You also properly need to verify the input that you recieve to prevent hacks such as buffer overflow hacks and SQL injections. Allthough I don't know if buffer overflow is a problem with .NET, and SQL injections should be easily preventable with LINQ-to-SQL.
All in all there is no 100% guaranteed way of securing your data, and you should keep regular backups (separate from your database) of your data in case you get compromised and probably also transaction logs.
And as a final advice, if you are really serious about the security you should probably hire a security consultant and have a peek at how banks have set up their security infrastructure.
Also you can still use LINQ with webservices through LINQ to ADO.NET, though I haven't tried this myself.
This link might be more explaining How to move from LINQ to SQL to “LINQ to WCF”?
Where security is that important, for example when you are storing credit card information, you'll usually want the data repository and the webserver on seperate boxes, with a firewall between and both locked down by IP Security.
This way, only the webserver is exposed to the outside world. Your database server is sitting comfortably behind the firewall, and can only be accessed by the webserver through a certain port.
You might also consider SSL encryption on the web services and expose only HTTPS endpoints.
I am not completely clear here. If the winforms application calls webservice then use a appropriate model for mutually trusted authentication. This can be based on client and server certificates or SSL with client certs or even Net.Tcp if you are all .Net. Then however the webservice is exposed only trusted clients can communicate. The webservice can then stay behind a DMZ and the DB behind another DMZ. Use appropriate firewall rules and IPSec connection between webservice and SQL is an option.
For direct connection to SQL server to many winforms application the challenges are many.The connection to your DB has to authenticated and encrypted. In any case your SQL server will be exposed and I would not recommend such a model.
You don't secure it because you can't secure it. First you can't properly hide credentials, even though you figure out how to do that then an attacker can sniff (yes even if it's encrypted you can locally sniff) or do SQL Injection directly on the wire.
You need to write all of you webservice calls in a secure manner which doesn't require to transfer raw SQL Query or direct SQL Server connection.
Also it doesn't matter how much obfuscate or encrypt it if the code is not running your system it's not your code any more. By reverse engineering, debugging, modifying the code a potential attacker can change your application into something else and do whatever they want.
Also as someone else wrote your webservice will be open to direct access. Someone can make a call directly to your web service and ignore the GUI at all.
A secure method is:
Place the data layer behind a (WCF) service on an physically separate Application Server and have WinForms clients connect to the service using their Windows Credentials. The service then validates whether users can access the various methods in the service based on an Authorisation store (such as Active Directory), and database or combination thereof.
The data service can then use a single pooled identity to connect to a database.
One of the more common approaches with web services is to pass an encrypted username and password via the web method signature in order to validate that the user attempting to invoke the web method indeed has rights to do so.
In terms of the configuration file it is possible to encrypt the file itself or use integrated security as another poster mentioned.
It's difficult to provide a precise answer because I'm not sure what specific issues you are trying to solve and which is the key driver for securing the system.
However, in the past I have used WinForms -> WebService secure communication by utilising WSE
We used X509 certificates and WS-Security. This has the distinct advantage of providing End To End Security rather than relying on standard SSL transport.
However this in of itself doesn't solve issues like user authentication per se, in that case Mitch Wheat's answer seems a good solution.
However, your user authentication model will depend on whether this is a public distributed app, whether the number of users of the tool is large or small etc.
For small numbers of users, or where cost is not an issue, you could implement RSA SecurID authentication by setting up a RADIUS server or such like. This has the advantage in that each RSA key is unique and tied to that user ( though you can never stop a user giving out their credentials and PIN )
HTH
The answer is simple to protect sql strings is simple. NEVER make a direct connetion to SQL in the client side.
Only accept well formed, schema-validated xml serialized objects as the entrance of your program, after being authenticated in a hashed public private key pair (http://msdn.microsoft.com/en-us/library/6f05ezxy.aspx) , being the public key certificate shipped within your program, so someone eavesdropping wont discover the password.
Also, watch out for DDOS attacks. Measure the use of each webservice exposed for each client, and if the use rises above a given limit, block all incoming connections from the user, and from the user´s ip.
If I understand the OP correctly, the immutable design characteristics are a WinForms client connecting directly to a publicly accessible SQL Server?
Almost everyone who responded has basically said 'don't do this, use a web service instead'. This is good advice. Even if the ws is hacked, it can only do things it was designed to do. So an RPC WS can only execute methods already written whereas hacking a SQL Server connection would allow arbitrary SQL Execution. Also, I think you would find that a well designed web service would be more performant.
However, if you are going to do this then you must secure your SQL connection over SSL (see technet) as a start. As with secure web services (which also would use SSL) this will hide the contents of the traffic from the men in the middle.
You can't rely on the authentication of the connection string (but using it adds another layer for a hacker to get through), so you must have an application level authentication layer that you most likely would roll yourself.
Don't allow the WinForms application to connect to your operational database. Create another database instead and allow the connection string based auth to connect to it. Do not do dynamic SQL with this design, use stored procedures instead. Create stored procedures in your public database that would act as your "rpc web service" to hide the real SQL (which would query your operational database and return the results). This will hide the operational details of your schema and reduce the surface area of attack.
If procedures are out of the question because you must use dynamic SQL, still keep the public/operational database structure and use views to expose as little of the data as possible. Leverage user id and any multi-tenancy features you have in the database to pre-filter data in the view. If you can do that you reduce the surface area of attack to the connected user's data.
Without understanding why you must allow a direct sql connection, I can only say again that you shouldn't do it. What you are gaining by doing so in the short term is at the cost of your system's long term security.