Xamarin - Error while try to downloadString from SSL websites (WebClient) - ios

I have an iOS application that developed by Xamarin Studio.
When I try to get a string from server I got the following exception.
Exception in Class: WebClient
Line : 271
and Method:DownloadDataCore
with message Error: SendFailure (Error writing headers)
Stack Trace: at System.Net.HttpWebRequest.EndGetResponse (IAsyncResult asyncResult) [0x00065] in ///Library/Frameworks/Xamarin.iOS.framework/Versions/8.2.0.207/src/mono/mcs/class/System/System.Net/HttpWebRequest.cs:971
at System.Net.HttpWebRequest.GetResponse () [0x0000e] in ///Library/Frameworks/Xamarin.iOS.framework/Versions/8.2.0.207/src/mono/mcs/class/System/System.Net/HttpWebRequest.cs:985
at System.Net.WebClient.GetWebResponse (System.Net.WebRequest request) [0x00000] in ///Library/Frameworks/Xamarin.iOS.framework/Versions/8.2.0.207/src/mono/mcs/class/System/System.Net/WebClient.cs:1563
at System.Net.WebClient.ReadAll (System.Net.WebRequest request, System.Object userToken) [0x00000] in ///Library/Frameworks/Xamarin.iOS.framework/Versions/8.2.0.207/src/mono/mcs/class/System/System.Net/WebClient.cs:972
at System.Net.WebClient.DownloadDataCore (System.Uri address, System.Object userToken) [0x0000a] in ///Library/Frameworks/Xamarin.iOS.framework/Versions/8.2.0.207/src/mono/mcs/class/System/System.Net/WebClient.cs:271
When I try to download the string from a none-SSL website it is ok and loads the string without any problem.
The website certificate is completely valid and It doesn't refused by Safari both in simulator and OSX.
I am runing the application on simulator.
I will be so thankful if you can help me fix the issue.
The code that I used for getting string from server is :
System.Net.ServicePointManager.ServerCertificateValidationCallback += (o, certificate, chain, errors) => true;
WebClient wc = new WebClient ();
wc.CachePolicy = new System.Net.Cache.RequestCachePolicy (System.Net.Cache.RequestCacheLevel.NoCacheNoStore );
result = wc.DownloadString (Url);
Regards

Before accessing SSL site with mono, you have to run mozroots --import --sync to import list of mozilla trusted certificates.
Also, there is mono security FAQ which can help to resolve SSL issues.

Related

System.Net.HttpListenerException: Failed to listen on prefix 'http://localhost:8080

I am running the following code from Scott Allen's ASP.Net Fundamentals course
using System;
using Microsoft.Owin.Hosting;
using Owin;
namespace ConsoleApplication1
{
class Program
{
static void Main(string[] args)
{
string uri = "http://localhost:8080";
using (WebApp.Start<Startup>(uri))
{
Console.WriteLine("Started!");
Console.ReadKey();
Console.WriteLine("Stopping!");
}
}
}
public class Startup
{
public void Configuration(IAppBuilder app)
{
app.UseWelcomePage();
//app.Run(
// ctx => ctx.Response.WriteAsync("Hello Owin!"));
}
}
}
However when I run the console app I get a message
Unhandled Exception: System.Reflection.TargetInvocationException: Exception has
been thrown by the target of an invocation. ---> System.Net.HttpListenerExceptio
n: Failed to listen on prefix 'http://localhost:8080/' because it conflicts with
an existing registration on the machine.
at System.Net.HttpListener.AddAllPrefixes()
at System.Net.HttpListener.Start()
at Microsoft.Owin.Host.HttpListener.OwinHttpListener.Start(HttpListener liste
ner, Func`2 appFunc, IList`1 addresses, IDictionary`2 capabilities, Func`2 logge
rFactory)
at Microsoft.Owin.Host.HttpListener.OwinServerFactory.Create(Func`2 app, IDic
tionary`2 properties)
--- End of inner exception stack trace ---
at System.RuntimeMethodHandle.InvokeMethod(Object target, Object[] arguments,
Signature sig, Boolean constructor)
at System.Reflection.RuntimeMethodInfo.UnsafeInvokeInternal(Object obj, Objec
t[] parameters, Object[] arguments)
at System.Reflection.RuntimeMethodInfo.Invoke(Object obj, BindingFlags invoke
Attr, Binder binder, Object[] parameters, CultureInfo culture)
at Microsoft.Owin.Hosting.ServerFactory.ServerFactoryAdapter.Create(IAppBuild
er builder)
at Microsoft.Owin.Hosting.Engine.HostingEngine.StartServer(StartContext conte
xt)
at Microsoft.Owin.Hosting.Engine.HostingEngine.Start(StartContext context)
at Microsoft.Owin.Hosting.Starter.DirectHostingStarter.Start(StartOptions opt
ions)
at Microsoft.Owin.Hosting.Starter.HostingStarter.Start(StartOptions options)
at Microsoft.Owin.Hosting.WebApp.StartImplementation(IServiceProvider service
s, StartOptions options)
at Microsoft.Owin.Hosting.WebApp.Start(StartOptions options)
at Microsoft.Owin.Hosting.WebApp.Start[TStartup](StartOptions options)
at Microsoft.Owin.Hosting.WebApp.Start[TStartup](String url)
at ConsoleApplication1.Program.Main(String[] args) in e:\EShared\Dev2015\WebA
ppScottAllen\ConsoleApplication1\ConsoleApplication1\Program.cs:line 12
Press any key to continue . . .
I ran the Resource Monitor from the Task Manager Performance Tab and can see that there are 2 entries on Listening Ports for 8080.
Both have Image=System, PID=4, IPv6 unspecified, Protocol TCP, Firewall Status Not allowed, not restricted
I am new to Listening Ports, how do I get the code working?
When faced with error: "Failed to listen on prefix 'http://someURL:somePortNo/' because it conflicts with an existing registration on the machine." It is not really necessary that there is an application actively listening on that port - thus output of Netstat -abno may not always help. If the already registered application is running it can help you narrow down to which application is causing the issue by looking at the info Netstat provides.
However, you will get this error even after the application in question is stopped since the error indicates a registration. The correct diagnostic command therefore is:
netsh http show urlacl
We need to examine the output and check whether any of the listed reserved URLs is configured to listen on the specific port your application is trying to use. You need to note the value of the "Reserved URL" field for that specific application. You will need it later for deleting the registration which is causing the error.
Uninstalling that specific application - assuming their uninstall procedure does include an un-registration - may resolve the problem. Alternatively you could take a more direct and precise approach of using the command for deleting a URL reservation:
(Note that if the conflict is legitimate, it may be better to reconfigure your application to listen on a different port instead.)
netsh http delete urlacl url=<value of "Reserved URL" in the output of netsh http show urlacl>
When the command works you will see output: URL reservation successfully deleted.
Upon running netsh http show urlacl a second time you will now see that the url registration is indeed gone. And now running your application should not result in the error you were seeing earlier.
I was able to solve the problem by uninstalling several programs.
Unfortunately I did not test after each, so I don't know which one it was.
They included Dropbox, Goto Assist, Goto Meeting and a winforms application
I had the same issue, and it was a silly fix. I had other console apps open that was using the same port number, so after I have closed all the console apps, I was able to run and did not get this error.
I had the same error in Visual Studio which was kind enough to tell me which port was wrong. I then ran this command in an Administrator Command Prompt:
netsh http delete urlacl url=http://+:44308/
Note : It is important to remember to final slash. Otherwise you will get an error.

No Fedauth cookie are sent back as SAML token after reaching STS seems to miss XML tags. Happens only on Firefox

I am scratching my head over a peculiar problem that seems to work on IE and Chrome.
We have a custom passive STS which serves a RP. All is well till i authenticate via my custom authentication service and then STS returns token which i can see in my temp folder. The POST operation which then sends the SAML 1.0 token hangs and silently dies instead of getting back the FedAuth cookie which would normally redirect me the RP
Note : RP and IP are hosted on web server that is behind a reverse proxy server (Nginx). Reverse proxy is hosted over SSL and all traffic to and fro proxy server and webserver is non SSL
The following get logged on the webserver
Event code: 3005
Event message: An unhandled exception has occurred.
Event time: 12/11/2013 5:16:33 PM
Event time (UTC): 12/11/2013 5:16:33 PM
Event ID: eef80ad2bffe425780dd46e5f28c0306
Event sequence: 2
Event occurrence: 1
Event detail code: 0
Exception information:
Exception type: XmlException
Exception message: **Unexpected end of file. Following elements are not closed: RequestedUnattachedReference, RequestSecurityTokenResponse,** RequestSecurityTokenResponseCollection. Line 1, position 5852.
at System.Xml.XmlExceptionHelper.ThrowXmlException(XmlDictionaryReader reader, String res, String arg1, String arg2, String arg3)
at System.Xml.XmlExceptionHelper.ThrowUnexpectedEndOfFile(XmlDictionaryReader reader)
at System.Xml.XmlBufferReader.GetByteHard()
at System.Xml.XmlBufferReader.GetByte()
at System.Xml.XmlUTF8TextReader.ReadStartElement()
at System.Xml.XmlUTF8TextReader.Read()
at System.Xml.XmlBaseReader.ReadEndElement()
at Microsoft.IdentityModel.Protocols.WSTrust.WSTrustSerializationHelper.ReadRSTRXml(XmlReader reader, RequestSecurityTokenResponse rstr, WSTrustSerializationContext context, WSTrustConstantsAdapter trustConstants)
at Microsoft.IdentityModel.Protocols.WSTrust.WSTrust13ResponseSerializer.ReadXmlElement(XmlReader reader, RequestSecurityTokenResponse rstr, WSTrustSerializationContext context)
at Microsoft.IdentityModel.Protocols.WSTrust.WSTrustSerializationHelper.CreateResponse(XmlReader reader, WSTrustSerializationContext context, WSTrustResponseSerializer responseSerializer, WSTrustConstantsAdapter trustConstants)
at Microsoft.IdentityModel.Protocols.WSTrust.WSTrust13ResponseSerializer.ReadXml(XmlReader reader, WSTrustSerializationContext context)
at Microsoft.IdentityModel.Protocols.WSFederation.WSFederationSerializer.CreateResponse(WSFederationMessage message, WSTrustSerializationContext context)
at Microsoft.IdentityModel.Web.WSFederationAuthenticationModule.GetXmlTokenFromMessage(SignInResponseMessage message, WSFederationSerializer federationSerializer)
at Microsoft.IdentityModel.Web.WSFederationAuthenticationModule.GetXmlTokenFromMessage(SignInResponseMessage message)
at Microsoft.IdentityModel.Web.WSFederationAuthenticationModule.GetXmlTokenFromMessage(SignInResponseMessage message, WSFederationSerializer federationSerializer)
at Microsoft.IdentityModel.Web.WSFederationAuthenticationModule.GetSecurityToken(SignInResponseMessage message)
at Microsoft.IdentityModel.Web.WSFederationAuthenticationModule.GetSecurityToken(HttpRequest request)
at Microsoft.IdentityModel.Web.WSFederationAuthenticationModule.SignInWithResponseMessage(HttpRequest request)
at Microsoft.IdentityModel.Web.WSFederationAuthenticationModule.OnAuthenticateRequest(Object sender, EventArgs args)
at System.Web.HttpApplication.SyncEventExecutionStep.System.Web.HttpApplication.IExecutionStep.Execute()
at System.Web.HttpApplication.ExecuteStep(IExecutionStep step, Boolean& completedSynchronously)
I dont understand why just for FF i get this problem. Is there a limitation on the size of the content that is sent in the header for FF?
Another question is : I have installed two different certificates one at proxy server (SSL)and one at webserver(STS) to signing the token. Can i use the same certificate? Should i?
According to the top voted answer on the question Can HTTP headers be too big for a browser, Firefox does have the lowest individual header-size (or at least did back in FF3.6). The accepted answer may help you though as you've mentioned you're behind a proxy.

GetResponse giving exception always in Monodroid. I am using Dropnet Dll

I am working on Monodroid. I have added a Dropnet DLL (I have compiled it in Monodevelop).
I am trying to retrieve account info, below is my code
DropNetClient _client;
string dropbox_appkey = "XXX";
string dropbox_appsecret = "XXXX";
_client = new DropNetClient(dropbox_appkey, dropbox_appsecret);
_client.UserLogin = new DropNet.Models.UserLogin { Token = "XXX", Secret = "XXXX" };
var accountInfo = _client.AccountInfo();
I am getting error when the below code gets executed
return (HttpWebResponse)request.GetResponse();
error received is:
System.Net.WebException: Error getting response stream (Write: The
authentication or decryption has failed.): SendFailure --->
System.IO.IOException: The authentication or decryption has failed.
---> Mono.Security.Protocol.Tls.TlsException: Invalid certificate received from server. Error code: 0xffffffff800b010a at
Mono.Security.Protocol.Tls.Handshake.Client.TlsServerCertificate.validateCertificates
(Mono.Security.X509.X509CertificateCollection certificates) [0x00000]
in :0 at
Mono.Security.Protocol.Tls.Handshake.Client.TlsServerCertificate.ProcessAsTls1
() [0x00000] in :0 at
Mono.Security.Protocol.Tls.Handshake.HandshakeMessage.Process ()
[0x00000] in :0 at
Mono.Security.Protocol.Tls.ClientRecordProtocol.ProcessHandshakeMessage
(Mono.Security.Protocol.Tls.TlsStream handMsg) [0x00000] in :0 at
Mono.Security.Protocol.Tls.RecordProtocol.InternalReceiveRecordCallback
(IAsyncResult asyncResult) [0x00000] in :0 ---
End of inner exception stack trace --- at
Mono.Security.Protocol.Tls.SslStreamBase.AsyncHandshakeCallback
(IAsyncResult asyncResult) [0x00000] in :0 ---
End of inner exception stack trace --- at
System.Net.HttpWebRequest.EndGetResponse (IAsyncResult asyncResult)
[0x00000] in :0 at
System.Net.HttpWebRequest.GetResponse () [0x00000] in :0 at RestSharp.Http.GetRawResponse
(System.Net.HttpWebRequest request) [0x00002] in
e:\sujit\development\try5\restsharp-RestSharp-eef0c86\RestSharp\Http.Sync.cs:170
When I run URL in browser which is something like this:
https://api.dropbox.com/1/account/info?oauth_consumer_key=XXXX&oauth_nonce=3064850&oauth_signature_method=PLAINTEXT&oauth_timestamp=1347899148&oauth_token=XXXX&oauth_version=1.0&oauth_signature=XXX%26XXX
I get proper response like this:
{"referral_link": "https://www.dropbox.com/referrals/XXXX",
"display_name": "XXX XXX", "uid": XXXX, "country": "IN", "quota_info":
{"shared": XXX, "quota": XXXX, "normal": XXXX}, "email":
"XXXX#gmail.com"}
My question is why am I getting strange error using Monodroid Emulator ( I am using Monodevelop version 3.0.4.6 and I am testing on API_10 EMulator.
What should I do?
Note:
Just to add, using Authentication token of dropbox obtained by authenticating it in desktop application. I think we can reuse token of a user which uses our Desktop application for a Mobile application. Right?
I had a similar problem using RestSharp with Mono for Android. The cause was an invalid certificate for the development environment. I was using a static IP address (192.168.1.122) for the domain so that my phone could connect with a web service on my development machine. You can override this by adding the following line somewhere before making the web request:
ServicePointManager.ServerCertificateValidationCallback = delegate { return true; };

Uploading xml with Monotouch fails on the device

I am trying to send an XML via web client on Monotouch. Although everything is working on the iOS simulator I get an exception when the app is running on the device. Here is the code.
try
{
Byte[] sendData = System.Text.Encoding.UTF8.GetBytes(someXML) ;
WebClient client = new WebClient();
Byte[] forResp;
client.Headers.Add("Content-Type","text/xml");
bresp = wc.UploadData(URL, sendData);
string resp = System.Text.Encoding.ASCII.GetString(forResp);
XmlDocument xresp = new XmlDocument();
xresp.LoadXml(resp);
return xresp;
}
catch
{
// error
}
I tried the WebClient because I had the same issue with the HttpWebRequest.
Exception:
The request timed out
System.Net.WebException: The request timed out
at System.Net.HttpWebRequest.EndGetResponse (IAsyncResult asyncResult) [0x00065] in /Developer/MonoTouch/Source/mono/mcs/class/System/System.Net/HttpWebRequest.cs:830
at System.Net.HttpWebRequest.GetResponse () [0x0000e] in /Developer/MonoTouch/Source/mono/mcs/class/System/System.Net/HttpWebRequest.cs:836
at System.Net.WebClient.GetWebResponse (System.Net.WebRequest request) [0x00000] in /Developer/MonoTouch/Source/mono/mcs/class/System/System.Net/WebClient.cs:1433
at System.Net.WebClient.ReadAll (System.Net.WebRequest request, System.Object userToken) [0x00000] in /Developer/MonoTouch/Source/mono/mcs/class/System/System.Net/WebClient.cs:866
at System.Net.WebClient.UploadDataCore (System.Uri address, System.String method, System.Byte[] data, System.Object userToken) [0x00038] in /Developer/MonoTouch/Source/mono/mcs/class/System/System.Net/WebClient.cs:462
at System.Net.WebClient.UploadData (System.Uri address, System.String method, System.Byte[] data) [0x00035] in /Developer/MonoTouch/Source/mono/mcs/class/System/System.Net/WebClient.cs:441
The stacktrace tells us that the timeout occurs when WebClient tries to get a response from the server (and not when uploading the data to the server). That means access to the server is not the issue (and why stacktraces are very useful ;-)
The next steps depends if you have control, or not, of the server. If you control the server then check it's logs to find the request and see how it was handled. If possible also ensure you received/decoded the data identically between the simulator and device.
If you do not control the server then it's harder to know what's going on inside it. E.g. maybe it did not like the request (i.e. the server code can decide not to answer based on any condition, including the user-agent).
In such case using a tool, like wireshark, is often your best bet. Compare the session from the iOS simulator and from the device.
Is the request identical ? e.g. the data you uploaded could be different due to something else;
Is the server answering for the device ? with the same status code ? in the same time frame ?
If everything is identical then you might have found a bug. Please report it (along with the above informations and files) to http://bugzilla.xamarin.com
Otherwise you should have more precise clues to debug the issue and/or update the question to be more specific :-)

Html.AntiForgeryToken() causeing errors after upgrading to .NET 3.5 SP1

I've just updated to .NET 3.5 SP1 and my once working ASP.NET MVC page has now stopped working.
When trying to load a page I get the following YSOD
[CryptographicException: Padding is invalid and cannot be removed.]
System.Security.Cryptography.RijndaelManagedTransform.DecryptData(Byte[] inputBuffer, Int32 inputOffset, Int32 inputCount, Byte[]& outputBuffer, Int32 outputOffset, PaddingMode paddingMode, Boolean fLast) +7596702
System.Security.Cryptography.RijndaelManagedTransform.TransformFinalBlock(Byte[] inputBuffer, Int32 inputOffset, Int32 inputCount) +208
System.Security.Cryptography.CryptoStream.FlushFinalBlock() +33
System.Web.Configuration.MachineKeySection.EncryptOrDecryptData(Boolean fEncrypt, Byte[] buf, Byte[] modifier, Int32 start, Int32 length, IVType ivType, Boolean useValidationSymAlgo) +225
System.Web.UI.ObjectStateFormatter.Deserialize(String inputString) +195
[ViewStateException: Invalid viewstate.
Client IP: 127.0.0.1
Port:
User-Agent: Mozilla/5.0 (Windows; U; Windows NT 5.1; en-GB; rv:1.9.0.6) Gecko/2009011913 Firefox/3.0.6 (.NET CLR 3.5.30729)
ViewState: hC6BC8KsuD/yoy2iG74bUZ8TYhGfuDDeIjh9fg/L18yr/E+1Nk/pjS5gyn9O+2jY
Referer: http://localhost:1092/admin/product
Path: /admin.aspx/product/edit/4193]
[HttpException (0x80004005): Validation of viewstate MAC failed. If this application is hosted by a Web Farm or cluster, ensure that <machineKey> configuration specifies the same validationKey and validation algorithm. AutoGenerate cannot be used in a cluster.]
System.Web.UI.ViewStateException.ThrowError(Exception inner, String persistedState, String errorPageMessage, Boolean macValidationError) +106
System.Web.UI.ViewStateException.ThrowMacValidationError(Exception inner, String persistedState) +14
System.Web.UI.ObjectStateFormatter.Deserialize(String inputString) +242
System.Web.UI.ObjectStateFormatter.System.Web.UI.IStateFormatter.Deserialize(String serializedState) +4
System.Web.Mvc.AntiForgeryTokenSerializer.Deserialize(String serializedToken) +73
If I remove the line
<%= Html.AntiForgeryToken() %>
Everything works again, any ideas what might be causing this? I would have expected more luck in finding a solution if this was an MVC or .NET issue so I'm guess it is something to do with my configuration.
I've tried reinstalling the MVC framework to see if it was because I installed before SP1 but I still get the same issue. Google and SO search hasn't resulted in any firm conclusions.
Doh, just solved it.
Cleared my browser cache and cookies and everything works fine again.
Clearing the browser cache isn't an option if the site is already deployed and you're doing maintenance including an ASP.NET MVC assembly update. Here's the solution I used:
#Html.AntiForgeryTokenReset() #* use this instead*#
here is the extension method
public static MvcHtmlString AntiForgeryTokenReset(this HtmlHelper htmlHelper)
{
try
{
return htmlHelper.AntiForgeryToken();
} catch (Exception ex)
{
var request = HttpContext.Current.Request;
request.Cookies.Clear();
return htmlHelper.AntiForgeryToken();
}
}
Looks like this problem has been solved now. Take a look at http://forums.asp.net/p/1388671/2960554.aspx

Resources