I just upgraded a project from .NET 4.0 to .NET 4.5.1 which produced the following warning:
Public Shared Function Encode(data() As Byte, protectionOption As
System.Web.Security.MachineKeyProtection) As String' is obsolete:
'This method is obsolete and is only provided for compatibility with
existing code. It is recommended that new code use the Protect and
Unprotect methods instead.'
I have lots of values floating around in cookies and emails that were encrypted with Encode. If I am going to replace Encode/Decode with Protect/Unprotect, I still need to be able to decrypt those old encrypted values. Is it possible to Unprotect a value that was encrypted with Encode?
In .NET 4.0 you can use MachineKey API to Protect/Unprotect data like this:
string Protect(byte[] data)
{
if (data == null || data.Length == 0) return null;
return MachineKey.Encode(data, MachineKeyProtection.All);
}
byte[] Unprotect(string value)
{
if (String.IsNullOrWhiteSpace(value)) return null;
return MachineKey.Decode(value, MachineKeyProtection.All);
}
MachineKey.Encode accepts a byte[] to protect and returns a string. The second parameter is an enum that indicates if you want encryption, validation or both. I’d typically suggest both (MachineKeyProtection.All). The returned string can then be used to pass back to the client as a cookie value or a query string value without concern for viewing or tampering. MachineKey.Decode simply reverses the process.
And here’s the 4.5 usage:
string Protect(byte[] data)
{
if (data == null || data.Length == 0) return null;
var value = MachineKey.Protect(data, "");
return Convert.ToBase64String(value);
}
byte[] Unprotect(string value)
{
if (String.IsNullOrWhiteSpace(value)) return null;
var bytes = Convert.FromBase64String(value);
return MachineKey.Unprotect(bytes, "");
}
In 4.5 the old APIs are deprecated in favor of these new Protect and Unprotect APIs. The new APIs no longer accept the level of protection (they always encrypt and MAC now [which is good]) and instead now accept a new parameter which is called purpose. This purpose parameter is intended to act somewhat as a validation mechanism. If we use a value that’s specific to the user (as we do above with the GetMachineKeyPurpose helper) we then are verifying that the value can only be unprotected by the same user. This is a nice addition in 4.5.
No - the process is different. Not to mention you'll be trying to Unprotect data that has no additional parameter specified (which won't work) and sometimes decoding data with the additional parameter specified (if you are ideally taking advantage of how protect works)
I'd refactor the code to be able to tell when the old data is present and write a new cookie/etc out using Protect();
On the first case I mentioned - you cannot use a blank parameter in Protect like
var unprotect = MachineKey.Unprotect(Encoding.UTF8.GetBytes(myOldEncryptedStuff), "");
and if you in turn have some other code there like "User 12345" to help protect that data - this is called the purpose string and helps keep that string encrypted in a more unique way tied to that user.
var unprotect = MachineKey.Unprotect(Encoding.UTF8.GetBytes(myOldEncryptedStuff), "User 12345")
If the purpose strings don't match you'll just get a generic exception here like:
System.Security.Cryptography.CryptographicException: Error occurred
during a cryptographic operation.
So it won't work for you - the two methods operate very differently. You'll need to figure out when to use one vs the other. You could always catch the exception and then try to fallback to the old tech - but test that out :)
Related
I have a class which is used to perform Validation of Antiforgery tokens where the payload is Json. That class looks like this (from Phil Haacked):
[AttributeUsage(AttributeTargets.Method | AttributeTargets.Class, AllowMultiple = false, Inherited = true)]
public class ValidateJsonAntiForgeryTokenAttribute : FilterAttribute, IAuthorizationFilter
{
public void OnAuthorization(AuthorizationContext filterContext)
{
if (ReferenceEquals(filterContext, null)) throw new ArgumentNullException("filterContext");
var request = filterContext.HttpContext.Request;
// Only validate POSTs
if (request.HttpMethod == WebRequestMethods.Http.Post)
{
// Ajax POSTs and normal form posts have to be treated differently when it comes
// to validating the AntiForgeryToken
if (request.IsAjaxRequest())
{
var antiForgeryCookie = request.Cookies[AntiForgeryConfig.CookieName];
var cookieValue = ReferenceEquals(antiForgeryCookie, null) ? null : antiForgeryCookie.Value;
AntiForgery.Validate(cookieValue, request.Headers[AntiForgeryConfig.CookieName]);
}
else
{
new ValidateAntiForgeryTokenAttribute().OnAuthorization(filterContext);
}
}
}
}
This is the first Angular project I am using it on and it is not throwing an exception where I would expect it to. For example, the value in the header differs from the value in the cookie and the call to AntiForgery.Validate proceeds without exception.
The anti-forgery token is rendered in the shell view (i.e. Index.cshtml) and it is added to the headers in Angular's module run function:
// Handle routing errors and success events
theApp.run(['$http', '$route', '$rootScope', '$q', 'routeOverlord',
function ($http, $route, $rootScope, $q, routeOverlord) {
// Include $route to kick start the router.
routeOverlord.setRoutingHandlers();
// Include AntiForgeryToken to prevent CSRF attacks
$http.defaults.headers.common['__RequestVerificationToken'] = angular.element('input[name="__RequestVerificationToken"]').val();
}]);
Is this a known thing? Happy to provide a Fiddler screenshot of the differing strings in the cookie and header if requested.
Cheers
The cookie token and the form token (the one in the headers in your case) are not supposed to be identical (it would be easier to fake).
The cookie token contains a random blob. The form token contains the same blob, plus some identity data (and optionally some additional data).
AntiForgery.Validate() checks that both blobs are identical, and that the other data in the form token corresponds to the identity data and the optional additional data.
I have seen this as well. The cookie value and the field value being different but the .Net framework still letting them through.
This is because the .Net Framework's implementation is a little more complicated then a simple value matching check.
After looking over the source code on Github, see that the tokens contain additional information besides just a GUID (they are tying it to the current user).
I can see form the TokenValidator that the cookie value is a token representing a SessionToken where the field value (your header value) is not expected to be a session token.
// Do the tokens have the correct format?
if (!sessionToken.IsSessionToken || fieldToken.IsSessionToken)
{
throw HttpAntiForgeryException.CreateTokensSwappedException(_config.CookieName, _config.FormFieldName);
}
But the pair of them are still used to verify the action did come from the authorized user and not some precanned attack from a malicious person.
I personally need to do more studying of Microsoft's implementation, but from the little bit I see right now (and linked below) the values should most certainly be different.
References I looked at:
AntiXsrf AntiForgery
AntiXsrf AntiForgeryWorker
AntiXsrf TokenValidator
AntiXsrf AntiForgeryTokenSerializer
So, there are a wealth of Flex articles online about how to handle a .NET WebMethod that returns a DataSet or DataTable. Here is an example:
Handling web service results that contain .NET DataSets or DataTables
So, I know how to use result.Tables.<tablename>.Rows and the like. But what I cannot seem to figure out or find online is how to go the other direction - a method to pass objects or tables back to the .NET Webservice from Flex, without stooping to passing XML as a string, or making huge web service methods that have one parameter for each property/column of the object being stored. Surely others, smarter than I, have tackled this issue.
I am using ASP.NET 2.0 Typed DataSets, and it would be really nice if I could just pass one object or array of objects from Flex to the web service, populate my Typed DataTable, and do an Update() through the corresponding typed TableAdapter. My dream would be a [WebMethod] something like one of these:
public void SaveObject(TypedDataTable objToSave) { ... }
public void SaveObject(TypedDataSet objToSave) { ... }
I've had the typed datatables saving to the database, I know how to do that part and even a few tricks, but we had XML being passed back-and-forth as a string - eww. I'm trying to get to a more object-based approach.
The best object based approach is AMF. I assume its probably a bit late in your your development cycle to change your integration layer, but otherwise I dont know of a way to get around marshalling your object(s) back into XML or separating them out into their primitive components.
For .NET implementations of AMF check out:
FlourineFX(FOSS)
WebORB for .NET
Its amazing how easy things become once AMF is used, for example using the Mate MVC framework and an AMF call passing a complex object to the server looks something like this:
<mate:RemoteObjectInvoker instance="yourWebservice" method="saveComplexObject" showBusyCursor="true" >
<mate:resultHandlers>
<mate:CallBack method="saveComplexObjectSuccess" arguments="{[resultObject]}" />
</mate:resultHandlers>
<mate:faultHandlers>
<mate:MethodInvoker generator="{DataManager}" method="presentFault" arguments="{fault}" />
</mate:faultHandlers>
</mate:RemoteObjectInvoker>
With result and fault handlers being optional.
The direction I ended up going was close to what I hoped was possible, but is "hack-ish" enough that I would consider SuperSaiyen's suggestion to use AMF/ORM a better solution for new/greenfield projects.
For sake of example/discussion, let's say I am working with a Person table in a database, and have a typed DataSet called PeopleDataSet that has PersonTableAdapter and PersonDataTable with it.
READ would look like this in .NET web service:
[WebMethod]
public PeopleDataSet.PersonDataTable GetAllPeople() {
var adapter = new PersonTableAdapter();
return adapter.GetData();
}
... which in Flex would give you a result Object that you can use like this:
// FLEX (AS3)
something.dataProvider = result.Tables.Person.Rows;
Check out the link I put in the question for more details on how Flex handles that.
CREATE/UPDATE - This is the part I had to figure out, and why I asked this question. The Flex first this time:
// FLEX (AS3)
var person:Object = {
PersonID: -1, // -1 for CREATE, actual ID for UPDATE
FirstName: "John",
LastName: "Smith",
BirthDate: "07/19/1983",
CreationDate: "1997-07-16T19:20+01:00" // need W3C DTF for Date WITH Time
};
_pplWebSvcInstance.SavePerson(person); // do the web method call
(For handling those W3C datetimes, see How to parse an ISO formatted date in Flex (AS3)?)
On the .NET web service side then, the trick was figuring out the correct Type on the web method's parameter. If you go with just Object, then step into a call with a debugger, you'll see .NET figures it is a XmlNode[]. Here is what I figured out to do:
[WebMethod]
public int SavePerson(PeopleDataSet p) {
// Now 'p' will be a PeopleDataSet with a Table called 'p' that has our data
// row(s) (just row, in this case) as string columns in random order.
// It WILL NOT WORK to use PeopleDataSet.PersonDataTable as the type for the
// parameter, that will always result in an empty table. That is why the
// LoadFlexDataTable utility method below is necessary.
var adapter = new PersonTableAdapter();
var tbl = new PeopleDataSet.PersonDataTable();
tbl.LoadFlexDataTable(p.Tables[0]); // see below
// the rest of this might be familiar territory for working with DataSets
PeopleDataSet.PersonRow row = tbl.FirstOrDefault();
if (row != null) {
if (row.PersonID > 0) { // doing UPDATE
row.AcceptChanges();
row.SetModified();
}
else { // doing CREATE
row.CreationDate = DateTime.UtcNow; // set defaults here
row.IsDeleted = false;
}
adapter.Update(row); // database call
return row.PersonID;
}
return -1;
}
Now, the kluge utility method you saw called above. I did it as extension method, that is optional:
// for getting the Un-Typed datatable Flex gives us into our Typed DataTable
public static void LoadFlexDataTable(this DataTable tbl, DataTable flexDataTable)
{
tbl.BeginLoadData();
tbl.Load(flexDataTable.CreateDataReader(), LoadOption.OverwriteChanges);
tbl.EndLoadData();
// Probably a bug, but all of the ampersand (&) in string columns will be
// unecessarily escaped (&) - kluge to fix it.
foreach (DataRow row in tbl.Rows)
{
row.SetAdded(); // default to "Added" state for each row
foreach (DataColumn col in tbl.Columns) // fix & to & on string columns
{
if (col.DataType == typeof(String) && !row.IsNull(col))
row[col] = (row[col] as string).Replace("&", "&");
}
}
}
Ok, so I can't seem to find decent Windows Azure examples. I have a simple hello world application that's based on this tutorial. I want to have custom output instead of JSON or XML. So I created my interface like:
[ServiceContract]
public interface IService
{
[OperationContract]
[WebInvoke(UriTemplate = "session/create", Method = "POST")]
string createSession();
}
public class MyService : IService
{
public string createSession()
{
// get access to POST data here: user, pass
string sessionid = Session.Create(user, pass);
return "sessionid=" + sessionid;
}
}
For the life of me, I can't seem to figure out how to access the POST data. Please help. Thanks!
If you have an HttpContext there may be a Request object that would have the form data. I'm basing part of this off the ASP.Net tag on this question, so if that is incorrect then there may be the need to handle this another way but it looks a lot like a web service to my mind.
EDIT: HttpRequest is the class that has the Form property that should be where the POST data is stored if this is an HTTP request. This is part of System.Web so it should be ready to be used pretty easily, as I recall.
Sample code showing the Request.Form property:
int loop1;
NameValueCollection coll;
//Load Form variables into NameValueCollection variable.
coll=Request.Form;
// Get names of all forms into a string array.
String[] arr1 = coll.AllKeys;
for (loop1 = 0; loop1 < arr1.Length; loop1++)
{
Response.Write("Form: " + arr1[loop1] + "<br>");
}
This presumed there was an HttpRequest instance around.
WCF Simplified Part 4: Comparing the Request/Reply and One-Way Patterns passes in a parameter so that your "createSession" method would have to take in those strings it would appear. I'm used to the ASP.Net world where there are some built-in objects like Request, Response, Server, Application and Session.
Yes, if you did try changing the method signature as there are ways to pass in parameters in that last example I linked though I don't know if that would work in your case or not.
I am using ASP.NET (.asmx) web services with Silverlight. Since there is no way to find the client IP address in Silverlight, I had to log this on the service end.
These are some methods I have tried:
Request.ServerVariables("REMOTE_HOST")
HttpContext.Current.Request.ServerVariables["REMOTE_ADDR"]
HttpContext.Current.Request.ServerVariables["HTTP_X_FORWARDED_FOR"];
Request.UserHostAddress()
Request.UserHostName()
string strHostName = Dns.GetHostName();
string clientIPAddress = Dns.GetHostAddresses(strHostName).GetValue(0).ToString();
All the above methods work fine on my local system, but when I publish my service on a production server, it starts giving errors,
Error: Object reference not set to an instance of an object. StackTrace:
at System.Web.Hosting.ISAPIWorkerRequestInProc.GetAdditionalServerVar(Int32 index)
at System.Web.Hosting.ISAPIWorkerRequestInProc.GetServerVariable(String name)
at System.Web.Hosting.ISAPIWorkerRequest.GetRemoteAddress()
at System.Web.HttpRequest.get_UserHostAddress()
You should try to find out exactly where the NullReferenceException is coming from. Change your code to understand that certain things can return null. For instance, in
HttpContext.Current.Request.ServerVariables["REMOTE_ADDR"]
HttpContext.Current could retrun null, or .Request could return null, or .ServerVariables["REMOTE_ADDR"] could return null. Also, in
string clientIPAddress = System.Net.Dns.GetHostAddresses(strHostName).GetValue(0).ToString();
the GetHostAddresses(strHostName) could return null, or the .GetValue(0) could return null.
If a method or property could return null, then you should check for null before dereferencing it. For instance,
IPAddress[] hostAddresses = System.Net.Dns.GetHostAddresses(strHostName);
string clientIPAddress;
if (hostAddresses != null)
{
object value = hostAddresses.GetValue(0);
if (value != null)
{
clientIPAddress = value.ToString();
}
}
P.S. I don't know why you'd use GetValue(0). Use hostAddresses[0] instead.
If you take a look using Reflector at the System.Web.Hosting.ISAPIWorkerRequestInProc.GetAdditionalServerVar code, that's what we see:
private string GetAdditionalServerVar(int index)
{
if (this._additionalServerVars == null)
{
this.GetAdditionalServerVariables();
}
return this._additionalServerVars[index - 12];
}
I see two reasons why this could raise a NullReferenceException:
1) there is a multithreading issue on the _additionalServerVars member. I don't think this could happen because A) I don't see why there would be big load on your server during test, and B) the ISAPIWorkerRequestInProc instance is probably tied to a thread.
2) your server is not up to date and the code in production is not the same as the one I'm seeing on my machine.
So what I would do is check the server making sure it's up to date with the .NET Framework dlls.
The users of my web application may have more than one browser window (or tab) open and pointed to the same page. We're using cookie based session id's, and the user will usually work within the same session id in both browsers/tabs. I would like to be able to uniquely identify which browser window (and tab) that requested an ASP.NET page (in order to make sure, that data stored in the session does not get mixed up).
(e.g. I would be happy if the browser would generate and send a window/tab-id with the http request, as it publishes HTTP_USER_AGENT)
Any ideas?
--thomas
If I was going to implement something like this I would probably start with a Dictionary<Type, List<Guid>> and store this in the users session. I would also probably make this be a custom type that delegates the dictionary and have a factory method that works similar to
public Guid GeneratePageIdentifier(Page thepage)
{
var guid = Guid.New();
if(_dictionary[thepage.GetType()] == null)
_dictionary[thepage.GetType()] = new List<Guid> { guid };
else
((List<Guid>)_dictionary[thepage.GetType()]).Add(guid);
return guid;
}
Then embed the guid that's returned from that method on the VIewState of the page. On your page methods that execute actions that you need to validate which page it is you would be able to validate that guid is inside the collection do something. You might also want to implement a custom a type with a guid property to enscapulate more information about why you're doing this or what you need for it to be meaningful.
The Viewstate on each page will be different, maybe you can use some kind of unique identifier created on every page loaded?
It is by default not possible due to the stateless nature of the web, but you could add a "page identifier" that gets generated with each opened page and transmitted for every action.
I'd recommend that you refactor the application in a way that those mixups can't happen, no matter from which page/tab/window the request originates.
As Mark Redman said, you can use Viewstate + Session in order to store values specific to the page.
ViewState is good for storing the key (string), Session for storing whatever type of complex objects.
Use the ViewState or a hidden field in order to load at the first call a GUID.
public string PageUid
{
get
{
if (ViewState["UID"] == null)
ViewState.Add("UID", Guid.NewGuid().ToString());
return ViewState["UID"].ToString();
}
}
Then use the session to get/set your values using this key:
string MyPagesessionVariable
{
get
{
if (Session["MYVAR" + PageUid] == null)
{
Session["MYVAR" + PageUid] = "VALUE NOT SHARED WITH OTHER TABS/WINDOWS";
}
return Session["MYVAR" + PageUid];
}
set
{
Session["MYVAR" + PageUid] = value;
}
}