WebRequest from localhost to localhost : why is it being denied? - asp.net

My app uses a WebRequest at certain points to get pages from itself.
This shouldn't be a problem. It actually works fine on the server, which is a "shared" hosting package with Medium trust. Locally, I use a custom security policy based on Medium trust, which includes the following — copied straight from the default Medium trust policy:
<IPermission
class="WebPermission"
version="1">
<ConnectAccess>
<URI uri="$OriginHost$"/>
</ConnectAccess>
</IPermission>
The offending line is in a custom XmlRelativeUrlResolver:
public override object GetEntity( System.Uri puriAbsolute, string psRole, System.Type pReturnType )
{
return _baseResolver.GetEntity( puriAbsolute, psRole, pReturnType );
}
The url being requested is on localhost, in the same application as the requester. Here's the top of the stack trace.
at System.Security.CodeAccessSecurityEngine.Check(Object demand, StackCrawlMark& stackMark, Boolean isPermSet)
at System.Security.CodeAccessPermission.Demand()
at System.Net.HttpWebRequest..ctor(Uri uri, ServicePoint servicePoint)
at System.Net.HttpRequestCreator.Create(Uri Uri)
at System.Net.WebRequest.Create(Uri requestUri, Boolean useUriBase)
at System.Net.WebRequest.Create(Uri requestUri)
at System.Xml.XmlDownloadManager.GetNonFileStream(Uri uri, ICredentials credentials)
at System.Xml.XmlDownloadManager.GetStream(Uri uri, ICredentials credentials)
at System.Xml.XmlUrlResolver.GetEntity(Uri absoluteUri, String role, Type ofObjectToReturn)
at flow.controls.XmlRelativeUrlResolver.GetEntity(Uri puriAbsolute, String psRole, Type pReturnType) in c:\flow\source\controls\DataTransform.cs:line 105
at System.Xml.Xsl.Xslt.XsltLoader.CreateReader(Uri uri, XmlResolver xmlResolver)
Anyone see the problem here?
#Sijin: Thanks for the suggestion. The url that gets sent to the resolver is based on the request URL, and I confirmed in the debugger that accessing the site at 127.0.0.1 yields the same result.

Does it work if you put 127.0.0.1 instead of localhost?

My ignorance. I didn't know that the $OriginHost$ token was replaced using the originUrl attribute of the trust level — I thought it just came from the url of the app. I had originally left this attribute blank.
<trust level="CustomMedium" originUrl="http://localhost/" />

This might not be the solution but when I saw your post I remembered this issue that I ran into about a year ago:
http://support.microsoft.com/default.aspx/kb/896861
You receive error 401.1 when you
browse a Web site that uses Integrated
Authentication and is hosted on IIS
5.1 or IIS 6
We were creating a WebRequest to screen scrape a page and it worked in our production environment because we were not using a loopback host name but on development machines we ended up with access denied (after applying Windows Server 2003 SP2). The one difference here is that this was under integrated authentication which caused it to fail... it worked when the request was anonymous (so that is why I am not sure this is the answer for you).

Related

DotNetNuke.Entities.Urls.UrlRewriterUtils - System.ArgumentNullException

Working on a DNN (9.2) module and am getting the following error in the DNN log file when trying to call http://dnndev.me/desktopmodules/rentalz/server.ashx directly from URL address bar in browser:
DotNetNuke.Entities.Urls.UrlRewriterUtils - System.ArgumentNullException:
Value cannot be null.
Parameter name: url
at System.Web.HttpResponse.Redirect(String url,
Boolean endResponse, Boolean permanent)
at DotNetNuke.Entities.Urls.AdvancedUrlRewriter.ProcessRequest(
HttpContext context, Uri requestUri, Boolean useFriendlyUrls,
UrlAction result, FriendlyUrlSettings settings,
Boolean allowSettingsChange, Guid parentTraceId)
When I remove the following entry from the Web.config file, the ASHX page works, but the rest of the site bombs out!
<add name="UrlRewrite" type="DotNetNuke.HttpModules.UrlRewriteModule,
DotNetNuke.HttpModules" preCondition="managedHandler" />
Does anyone know what's causing this?
This request shouldn't be handled by the URL rewriter, it ignores ashx requests by default. You can go to the SEO Settings page, and check the Expressions tab under URL Management to see if ashx is listed in the Do Not Rewrite URL Regular Expression. You can also go the the Test URL tab and put your URL in to see what sort of rewriting the system is trying to perform.
You shouldn't use a handler anymore. It's an old technique that can easily create security flaws on your website. You should instead us Web API. It's so much easier to do as well.
http://www.dnnsoftware.com/wiki/services-framework-webapi

Key not valid for use in specified state. After IIS Reset

I tried this:
runas /user: domain\user cmd with no luck
This seems to only occur now when IIS is reset and I try to resume my browsing session. So I am logged into the application, I reset IIS on the server, refresh the page and see the error.
I am building an application in .NET 4.0 MVC with a Secure Token Service that is using WIF 4.0. Everything works as expected, except this case. I even tried to use a custom error page, but the error is happening there as well. Because of that, I can't get the custom page to show either. Also, This is using a certificate that is located on both load balanced servers. This happens in my dev environment whihc consists of only one server (app, wfe, db operated there)
One thing I noticed is that if I switch my IIS APP Pool user back to Network Service account it doesn't throw the error any more. We have some restrictions (mostly network related) in the application that we need to use an account in our AD for the app pool sections
Anybody have any experience with this issue?
Key not valid for use in specified state.
Description: An unhandled exception occurred during the execution of
the current web request. Please review the stack trace for more
information about the error and where it originated in the code.
Exception Details:
System.Security.Cryptography.CryptographicException: Key not valid for
use in specified state.
Source Error:
An unhandled exception was generated during the execution of the
current web request. Information regarding the origin and location of
the exception can be identified using the exception stack trace below.
Stack Trace:
[CryptographicException: Key not valid for use in specified state. ]
System.Security.Cryptography.ProtectedData.Unprotect(Byte[]
encryptedData, Byte[] optionalEntropy, DataProtectionScope scope) +428
Microsoft.IdentityModel.Web.ProtectedDataCookieTransform.Decode(Byte[]
encoded) +54
[InvalidOperationException: ID1073: A CryptographicException occurred
when attempting to decrypt the cookie using the ProtectedData API (see
inner exception for details). If you are using IIS 7.5, this could be
due to the loadUserProfile setting on the Application Pool being set
to false. ]
Microsoft.IdentityModel.Web.ProtectedDataCookieTransform.Decode(Byte[]
encoded) +146
Microsoft.IdentityModel.Tokens.SessionSecurityTokenHandler.ApplyTransforms(Byte[]
cookie, Boolean outbound) +113
Microsoft.IdentityModel.Tokens.SessionSecurityTokenHandler.ReadToken(XmlReader
reader, SecurityTokenResolver tokenResolver) +647
Microsoft.IdentityModel.Tokens.SessionSecurityTokenHandler.ReadToken(Byte[]
token, SecurityTokenResolver tokenResolver) +105
Microsoft.IdentityModel.Web.SessionAuthenticationModule.ReadSessionTokenFromCookie(Byte[]
sessionCookie) +262
Microsoft.IdentityModel.Web.SessionAuthenticationModule.TryReadSessionTokenFromCookie(SessionSecurityToken&
sessionToken) +76
Microsoft.IdentityModel.Web.SessionAuthenticationModule.OnAuthenticateRequest(Object
sender, EventArgs eventArgs) +53
System.Web.SyncEventExecutionStep.System.Web.HttpApplication.IExecutionStep.Execute()
+148 System.Web.HttpApplication.ExecuteStep(IExecutionStep step, Boolean& completedSynchronously) +75
This issue is related to session cookies.
WIF protects session cookies using Data Protection API (DPAPI) by default, and the DPAPI is closely related to machine keys.
If the keys used to encrypt the session cookies change, it throws this exception.
It could be also related to your app hosting infrastructure.
if your app is running in an Network Load Balancer (NLB) environment
if you change the app pool settings (e.g., change the pool’s user)
More details about this scenario on the MSDN blog entry:
WIF 1.0 – ID1073 A CryptographicException occurred when attempting to decrypt the cookie using the ProtectedData API Archive.Today Shortlink
Todd Foust (October 29, 2012)
So, if your app runs in NLB environment, you could :
Configure your load balancer to use sticky sessions. This means that your user will be directed to the same server during the session duration. (I’m not very fond of that one)
Use a certificate to encrypt the session cookies
set all web.config files to use the same machine key in system.web
If you are not running the app in a NLB env, you could try:
set the machinekey in your web.config to use a pre-defined value instead of auto-generated values
Regarding auto-generated machinekey setting, please see:
How unique is your machine key?Archive.Today Shortlink

ASP.NET Web Service call failing after changing consuming Site SSL certificate

I'm running into a very weird scenario, have tried a lot of solutions and also tried searching for people having similar issues but couldn't find anything.
I have a webforms ASP.NET application for which the SSL certificate expired a couple of months ago, and we just received the renewed certificate. It was a new certificate instead of a renewal one, but issued to the same URL/SANs. It's also an internal certificate, not externally issued.
After installing the new SSL certificate in our production environment, an internal web service (asmx reference) call that we are making (to a java web service) is failing, complaining about no parameters being sent to the web service. This only happens if I browse through the SSL enabled version of the site, and only in production. The site with SSL works correctly in our dev/stage environments. Prod also works but only if I don't browse through HTTPS.
I cannot paste all the technical exception details, as it's a work related thing, but any help/guidance is appreciated.
System.Web.HttpUnhandledException (0x80004005): Exception of type 'System.Web.HttpUnhandledException' was thrown. ---> System.Web.Services.Protocols.SoapHeaderException: Internal Server Error (Caught exception while handling request: java.lang.Exception: Last Name and/or First Name needs to be provided.)
at System.Web.Services.Protocols.SoapHttpClientProtocol.ReadResponse(SoapClientMessage message, WebResponse response, Stream responseStream, Boolean asyncCall)
at System.Web.Services.Protocols.SoapHttpClientProtocol.Invoke(String methodName, Object[] parameters)
at OurProgram.com.Company.corp.amssvc.DirWs2.getEmployeeDataByName(String lastName, String firstName, String attData, String strDelim) in D:\somecodehere
For additional data, it is also not an IIS website on its own, it's hosted as an application under the Default Website, which is the one that has the SSL binding for the certificat.e
Has anyone experienced this?
TL;DR -- Disabled Anonymous Authentication.
Well, after 6 hours of fiddling with and comparing IIS and website configurations, the issue was that for some reason, Anonymous Authentication got enabled somehow after the site had been restarted for the new SSL certificate to kick in. Our application is an intranet one, so the web service takes the credentials of the logged in user. When Anon Auth got enabled somehow, it must have not been passing the correct credentials.
After disabling Anonymous Authentication, the site worked just fine. While it might seem a little related in hindsight, I would've expected a different error, anything other than the web service complaining that no parameters were sent.
Hope this helps someone.

ASP.NET 4.0 application cannot find Default.aspx under IIS6

I've got an ASP.NET 4.0 web application (webforms, not mvc; asp.net routing isn't used) that runs fine under IIS7. When I try to run it under IIS6 and navigate to http://localhost/MyApp/, I get the following exception:
File does not exist.
System.Web.HttpException
at System.Web.StaticFileHandler.GetFileInfo(String virtualPathWithPathInfo, String physicalPath, HttpResponse response) (+0 IL, +2509040 JIT)
at System.Web.StaticFileHandler.ProcessRequestInternal(HttpContext context, String overrideVirtualPath) (+54 IL, +198 JIT)
at System.Web.DefaultHttpHandler.BeginProcessRequest(HttpContext context, AsyncCallback callback, Object state) (+263 IL, +347 JIT)
at System.Web.HttpApplication.CallHandlerExecutionStep.System.Web.HttpApplication.IExecutionStep.Execute() (+214 IL, +8967220 JIT)
at System.Web.HttpApplication.ExecuteStep(HttpApplication.IExecutionStep step, Boolean& completedSynchronously) (+54 IL, +184 JIT)
Note that this output comes from my own custom error page. Thus, .NET itself is working fine. I can even remotely debug it and stuff.
Now, if I enter http://localhost/MyApp/Default.aspx, all works fine, I get the default page, etcetera. The first thought would be that the default document isn't specified in IIS, but it is. Even worse - if I disable it altogether, I still get the same error message (and yes, I restarted IIS and cleared my browser cache)!
It seems as if the request for / is always sent directly to ASP.NET which then gets confused because it doesn't have any default document concept. But I don't have any wildcard mappings defined, so how can that be?
After Googling I found this one as a solution. Its unrelated but some commented its working.
Can you please try this.
In the Windows registry, open the following node: HKEY_LOCAL_MACHINE\SOFTWARE\Microsoft\ASP.NET\4.0.30319.0
1.Create a new DWORD value named EnableExtensionlessUrls.
2.Set EnableExtensionlessUrls to 0. This disables extensionless URL behavior.
3.Save the registry value and close the registry editor.
4.Run the iisreset command-line tool, which causes IIS to read the new registry value

EventLog permission failing in ASP.Net on Win7

I have an ASP.Net app .net 3.5 SP1, running in Win7 . During the login process, something within the ASP.Net login control is causing a write to the security log (this sounds acceptable to me) in the event log. The problem is that it seems the app doesn't have permission to do this. There error is:
Description: The application attempted to perform an operation not allowed by the security policy. To grant this application the required permission please contact your system administrator or change the application's trust level in the configuration file.
Exception Details: System.Security.SecurityException: Request for the permission of type 'System.Diagnostics.EventLogPermission, System, Version=2.0.0.0, Culture=neutral, PublicKeyToken=b77a5c561934e089' failed.
The stack trace doesn't show a single line of code from my application, its all in the framework.
The last 5 lines are:
System.Security.CodeAccessSecurityEngine.Check(Object demand, StackCrawlMark& stackMark, Boolean isPermSet) +0
System.Security.CodeAccessPermission.Demand() +61
System.Diagnostics.EventLog..ctor(String logName, String machineName, String source) +125
System.Diagnostics.EventLog..ctor() +24
System.Diagnostics.EventLog.WriteEntry(String source, String message, EventLogEntryType type, Int32 eventID, Int16 category, Byte[] rawData) +52
This same app works fine on XP SP2. I've hunted around and can't find how to give permissions. I've tried running hte app pool as LocalSystem and ApplicationPoolIdentity.
Whats the easiest way to get this running? Its my local dev machine and I don't care if I open up security holes, as long as I don't have to modify code (ie I need the solution to be an INETMGR change or web.config or some local permissions, etc).
Thanks!
This link appears to discuss the issue you are having.
I am not sure about the differences between the default CAS (code access security) on XP vs. win 7, however the assembly writing to the event log (and all calling assemblies) must have EventLogPermission.
You can add the AllowPartiallyTrustedCallers attribute or sign the assembly with a strong name key.
If you are writing to the default Application log you need to provide permisson to the LocalSystem before using it inside app pool.
Open RegistryEdit and goto
HKEY_LOCAL_MACHINE\SYSTEM\ControlSet002\services\eventlog\Application
RightClick over the Applicatuion and click permissions
If the user(LOCALSYSTEM) is not present in the list then Add and Allow full Control

Resources