System.UnauthorizedAccessException - asp.net

Dim filePath As String = "~/Images/FleaMarket/uploadedImages/" & User.Identity.Name.ToString & "/" & itemID & Path.GetExtension(fuImage.FileName)
MsgBox(filePath)
If fuImage.HasFile Then
If Directory.Exists(Server.MapPath("~/Images/FleaMarket/uploadedImages/" & User.Identity.Name.ToString & "/")) = False Then
Directory.CreateDirectory(Server.MapPath("~/Images/FleaMarket/uploadedImages/" & User.Identity.Name.ToString & "/"))
End If
'lblMessage.Text = ""
If checkFileType(fuImage.FileName) Then
fuImage.SaveAs(Server.MapPath("../Images/FleaMarket/uploadedImages/" & User.Identity.Name.ToString))
i get an error "System.UnauthorizedAccessException: Access to the path 'D:\TriceDealsII Updated\13-10-11\Tricedeals II(4)\Images\FleaMarket\uploadedImages\mitali2054' is denied"
why??

ASP.NET Applications, which run in IIS use the User assigned to the specified Application Pool. For each Application Pool there will be a Windows User which is part of the Windows Group "IIS_IUSRS". As this User / Group do not have Write/Change Access to the directory of your Webapplication (or any other directory) you must manually grant these permissions.
To achive this: Navigate in the explorer to the specified path, where you wish to write your files / data open the Security Page of the directory to add the User of your AppPool or the Group "IIS_IUSRS" to the List and select the write (or change) permission.
Note: Write permission is always a security risk. Therefore you should restrict it as much as possible.

This is probably caused by a permissions issue on the file you're trying to access. You could try Procmon to see if it will tell you what account is trying to access the file then grant the necessary permissions to that account.

Related

Access denied to Network folder from .NET Web App with Everyone permission

Trying to get a web app I am developing to move a file from one location to another.
The code I am using is:
var oldlog = #"\\srvr-01\logs\" + file.Name;
var newlog = #"\\srvr-01\logs\archive\" + file.Name;
File.Move(oldlog, newlog);
Every time I hit the line, I am getting an "Access Denied" error.
I have tried:
Setting the identity that the Application pool runs under to a user that has confirmed Full Access to the source and destination folders
Turning Off Anonymous Authentication on the IIS server
Granting Everyone Full Control NTFS and Owner Share rights on the source and destination folders
I can't believe its THAT hard to do this, so its obvious it is something I am missing.

Changing file permissions results in IdentityNotMappedException (when code is ran on web server)

I have the following code (from msdn) to set file permissions:
' Adds an ACL entry on the specified file for the specified account.
Sub AddFileSecurity(ByVal fileName As String, ByVal account As String, ByVal rights As FileSystemRights, ByVal controlType As AccessControlType)
' Get a FileSecurity object that represents the
' current security settings.
Dim fSecurity As FileSecurity = File.GetAccessControl(fileName)
' Add the FileSystemAccessRule to the security settings.
Dim accessRule As FileSystemAccessRule = New FileSystemAccessRule(account, rights, controlType)
fSecurity.AddAccessRule(accessRule)
' Set the new access settings.
File.SetAccessControl(fileName, fSecurity)
End Sub
I call this using the group IIS_IUSRS (I've tried ComputerName/IIS_IUSRS too) and I'm trying to apply FileSystemRights.FullControl
But results in this error:
System.Security.Principal.IdentityNotMappedException: Some or all identity references could not be translated
Which suggests IIS_IUSRS doesn't exist (it does). My next step is to output the users and groups on the machine to see what my code thinks does exist. In the mean time does anyone know why, or what is causing this?
This code works fine on my local machine but not when run on my web server. The app pool runs as network service and Network Server has FULL permission on the folder the files are in. I noticed this question that suggests the user needs permission on the directory - but this isn't the problem.
To work around this, change the authentication on the website to run as "Same as app pool" (as opposed to anonymous). Not the best answer, but have tried everything else.

CDO.Message.1 error '80070005' Access is denied.

I am getting this error when I try to send via the local server
CDO.Message.1 error '80070005'
Access is denied.
/mail.asp, line xxx
Here is the code I am using
MailBodyText = "TEST"
Set objNewMail = CreateObject("CDO.Message")
objNewMail.To = sSendTo
objNewMail.From = "webmaster#EXAMPLE.com"
objNewMail.Cc = "webmaster#EXAMPLE.com"
objNewMail.Subject = "Information Request & Feedback"
objNewMail.HTMLBody = "The following information was sent from " & sEmail & ":" & "<br>" & CHR(13) & MailBodyText & "<br>copies of this mail we sent to :"& sSendTo
objNewMail.Send
Set objNewMail = Nothing
It looks like it is a permission error at the ISSUR doesn't have write permission to write to the mailroot/pickup folder.
But we have checked that and the services account that this site is using seems to have the rights.
Question is this error always a file permission error?
Question how to know / set the location that CDO is using? So we can confirm the permissions
What else should look at to fix this?
Use the .configuration property which allows for authentication and other fine tuning..
examples at : http://www.paulsadowski.com/wsh/cdo.htm
update
The .configuration property allows to set the pickup directory (as you request)
objNewMail.Configuration.Fields.Item("http://schemas.microsoft.com/cdo/configuration/sendusing") = 1
objNewMail.Configuration.Fields.Item("http://schemas.microsoft.com/cdo/configuration/smtpserverpickupdirectory") = "c:\inetpub\mailroot\pickup"
objNewMail.Configuration.Fields.Update
objNewMail.Send
IF YOU DON'T WANT TO CHANGE YOUR CODE
Grant IIS_IUSRS group write access to c:\inetpub\mailroot\Pickup folder or whatever is your pickup dir.
It must be IIS_IUSRS Group, not the IUSR User (you got it mispelled probably).
I was getting this error after performing steps specified in option 3 at blog.msdn.com
I didn't have to change the ASP code. Your code works fine on my server.
I am migrating some old classic asp sites to a new (windows 2008R2) server and I had "exactly" the same problem (well at least the same error and basically the same code). The solution presented by Gaby:
objNewMail.Configuration.Fields.Item("http://schemas.microsoft.com/cdo/configuration/sendusing") = 1
objNewMail.Configuration.Fields.Item("http://schemas.microsoft.com/cdo/configuration/smtpserverpickupdirectory") = "c:\inetpub\mailroot\pickup"
did not work for me, i still had the same error.
After some searching i found this suggestion:
myMail.Configuration.Fields.Item("http://schemas.microsoft.com/cdo/configuration/sendusing") = 2
myMail.Configuration.Fields.Item("http://schemas.microsoft.com/cdo/configuration/smtpserver") = "localhost"
(do NOT set the smtpserverpickupdirectory)
Now it works fine.
By the way if you need to set up the necessary SMTP service on Windows 2008 server (IIS7), I found this blog extremely helpfull.
UPDATE:
According to microsoft sendusing = 1 uses the SMTP server and sendusing 2 uses Outlook Express, I've looked on the server, and there doesn't seem to be outlookexpress or windows mail installed, still this setting workes for me. If anyone could explain that I'm curious to know.

Access Denied errors accessing IIS WMI provider from ASP

I have a Windows 2003 server running IIS 6 and have some scripts that do automated setup and creation of websites. They are not working on a new server I cam commissioning (they already work happily on 3 other W2K3 servers). The problem appear to boil down to WMI security on the IIS provider. The ASP code below represents the problem (although it is not the original code that causes the problem - this is a simplified demonstration of the problem).
Set wmiProvider = GetObject("winmgmts:\\.\root\MicrosoftIISv2")
If wmiProvider is Nothing Then
Response.Write "Failed to get WMI provider MicrosoftIISv2<br>"
End If
Response.Write "Querying for IISWebService...<br>"
Set colItems = wmiProvider.ExecQuery("Select * From IISWebServer",,0)
Response.Write "Error: " & Hex(Err.Number) & " (" & Err.Description & ")<br>"
If I run this in my browser, I get an access denied error reported after the ExecQuery call. I have set WMI access for the IUSR_ user from the Root branch all the way down. In fact, I can query for IP address information using the CIMV2 provider quite happily. If I put the IUSR user in the machine admins group it all works, but I don't really want to do that.
This must be a DCOM/WMI security problem, but I can't work out what else there is. Can anyone shed any light?
After reading G. Stoynev's comment asking if any events were logged in the Windows Logs, I checked the event logs on the server to which I'm attempting to access IIS remotely via WMI, and lo and behold I found an event with the following text:
Access to the root\WebAdministration namespace was denied because the namespace is marked with RequiresEncryption but the script or application attempted to connect to this namespace with an authentication level below Pkt_Privacy. Change the authentication level to Pkt_Privacy and run the script or application again.
See the code in this answer to the related SO question c# - "Access is denied" Exception with WMI.
Here's some example C# code that I added that seemed to resolve this issue for me:
ConnectionOptions options = new ConnectionOptions();
options.Authentication = AuthenticationLevel.PacketPrivacy;
ManagementScope managementScope = new ManagementScope(#"\\remote-server\root\WebAdministration", options);
// ...
If this is something that you intend to run as a tool for yourself or your admin (as opposed to the unwashed anonymous masses), here is a way I have used in the past (YMMV):
Set up a new directory in your website (e.g. /SiteCreate) and place your WMI scripts there
Configure a Windows user that has appropriate rights (probably admin in this case but you should use whatever is pertinent to your app)
Turn off the anonymous access to the directory you created in step 1 and then set the security to allow access only to the user you created in step 2 (turn on the authentication for that directory)
Now, when you navigate to that directory in your browser, you should get a login prompt. When you enter the username/password you created in step 2 your script will have the appropriate rights to perform your WMI requests.
Not a DCOM issue, more so a WMI security and encryption issue. Try changing the GetObject moniker to include impersonation and pktPrivacy, eg:
Set wmiProvider = GetObject("winmgmts:{impersonationLevel=impersonate;authenticationLevel=pktPrivacy}!\root\MicrosoftIISv2")
Refer to the follow MS article for more info:
http://msdn.microsoft.com/en-us/library/aa393618(v=vs.85).aspx

ASP.NET: System.UnauthorizedAccessException - Access to Path Denied

I have an ASP.NET web application which does the following:
Reads an Excel file.
The excel file will have an image URL located in it that points to somewhere on the internet.
The program reads each image URL and store it into a temporary folder in the web server.
The application then resizes (changes the width and height) of the image.
Finally, the application will save that image to another folder.
I am getting the following exception:
System.Net.WebException: An exception
occurred during a WebClient request.
---> System.UnauthorizedAccessException:
Access to the path
'\abcserver\target03\3111\35644\www.testing.com\web\content\images\TempStorage\tempImage.jpg'
is denied. at
System.IO.__Error.WinIOError(Int32
errorCode, String maybeFullPath) at
System.IO.FileStream.Init(String path,
FileMode mode, FileAccess access,
Int32 rights, Boolean useRights,
FileShare share, Int32 bufferSize,
FileOptions options,
SECURITY_ATTRIBUTES secAttrs, String
msgPath, Boolean bFromProxy) at
System.IO.FileStream..ctor(String
path, FileMode mode, FileAccess
access) at
System.Net.WebClient.DownloadFile(Uri
address, String fileName) --- End
of inner exception stack trace ---
at ProcessImage.GetFileFromUrl(String
imageFileUrl, String newFileName)
at
uploadexceldata.UploadExcelData(String
fileName)
foreach (DataRow dr in dt.Rows) // Reading each excel row
{
if (dr[0].ToString() != "")
{
id= "";
path = "";
manuId = "";
id= dr[0].ToString();
path = dr[1].ToString();
fileNameOnly = iProImg.GetFileNameOnly(path);
objDb.openConnection();
strSqlGroupInfo = "select ManufacturerID from manufacturers where id='" + id+ "'";
dTblManu = objDb.BuildDT(strSqlGroupInfo); // To Fill data to Datatable
objDb.closeConnection();
if (dTblManu.Rows.Count > 0)
{
manuId = dTblManu.Rows[0][0].ToString();
}
if (manuId != "")
{
tempUploadPath = "images/TempStorage/";
tempUploadPath = Server.MapPath(tempUploadPath);
if (!Directory.Exists(tempUploadPath))
{
Directory.CreateDirectory(tempUploadPath);
}
tempFilePath = tempUploadPath + "\\tempImage.jpg";
tempFilePath = tempFilePath.Replace("/", "\\");
previewPath = Server.MapPath("images/previews/" + manuId);
thumbNailPath = Server.MapPath("images/thumbnails/" + manuId);
if (!Directory.Exists(previewPath))
{
Directory.CreateDirectory(previewPath);
}
if (!Directory.Exists(thumbNailPath))
{
Directory.CreateDirectory(thumbNailPath);
}
fileNameOnly = "\\preview" + id+ ".jpg";
fileNameOnly = fileNameOnly.Replace("/", "\\");
previewPath = previewPath + fileNameOnly;
tempPartialPathP = "images\\previews\\" + manuId + fileNameOnly;
fileNameOnly = "\\thumbnail" + id+ ".jpg";
thumbNailPath = thumbNailPath + fileNameOnly;
tempPartialPathT = "images\\thumbnails\\" + manuId + fileNameOnly;
try
{
iProImg.GetFileFromUrl(path, tempFilePath);
rowCounter++;
iProImg.ReSizeImage(tempFilePath, previewPath, previewSize);
iProImg.ReSizeImage(previewPath, thumbNailPath, thumbNailSize);
}
catch (Exception ec)
{
errorRowCount++;
iLog.LogErrorToFile("uploadExcel", ec.ToString(), "path : " + path + ",tempFilePath :" + tempFilePath);
}
finally
{
if(File.Exists(tempFilePath))
{
File.Delete(tempFilePath);
}
}
} // If manuid!=""
} //if (dr[0].ToString() != "")
Does anyone have any suggestions on how to fix this exception?
Try setting the access permissions to "Full control" for the .Net user from where you are reading/saving the files.
No answers in the world solved this for me until I stumbled on the answer for myself:
UN-ENCRYPT THE FILE
You can grant full permissions to everyone on your entire hard drive, it still won't allow ASP.NET decrypt files.
If you are certain the file isn't encrypted, then you just need to add the ASPNET account to the file or folder you want to access. But make sure its not encrypted first!
In reply to what was said : "This is a remote server and the folder has full read/write permission granted.Still not working "
Make sure the .Net user / machine account user has full permissions for that Folder.
Also, add < identity /> to your config file
Make sure the ASP.NET account has read/write permission on the folder you're writing to (basic windows security).
How to:
http://www.microsoft.com/windowsxp/using/networking/security/permissions.mspx
(first 4 steps, check the boxes and click OK)
[EDIT]
You need to authenticate yourself with an account known on the remote server. You probably gave rights to the local ASP.NET account on the remote server, which won't work because that's not the user you access the folder with (from the webserver).
[/EDIT]
All of the above, plus you may need to add this tag:
<identity impersonate="true" userName="accountname" password="password" />
Read this KB article and if you are going from browser to iis to a file share, that counts as two hops and now you need to configure Kerberos Delegation. System administrators much smarter than me have tried to configure kerberos delegation and failed. Move your images or you IIS instance so that they are on the same machine.
First, narrow down your problem by temporarily granting Everyone full permission on that particular path. If it works, then you know for a fact it's a simple permission issue and you just need to figure out which acct needs proper permission. Probably the Anonymous User account (double check this setting in IIS Admin) and not the ASP.NET account. (don't forget to pull permission for Everyone)
If you need to, I believe you can use FileMon to see which account is attempting to access a particular file. Could be wrong, I haven't used this tool in a while.
One last thing... is the read-only flag set on the file? :)
I had the exact same problem today. After spending hours trying to track down what was causing the issue I found out that the permissions for the folder that was being written to were incorrect. Essentially, the folder was readonly from the perspective of the user being used to create the file.
Try doing the following for the folder in question:
Right Click on the folder and select properties
Click on the Sharing tab and then click on the Permissions button
Make sure to add whatever user is going to writing to the folder permissions to do so
Back at the properties page, click the Security tab
Make sure to add whatever user is going to write to the folder permissions to do so
Seeing as this question was asked 6 months ago, I'm assuming that you've already solved the issue...but I just thought I'd document my solution just in case it becomes useful to someone else in the future as they try to figure out how to solve this UnauthorizedAccessException.
Check that the image file (jpg) you're writing to the tempStorage has the proper permissions for the webuser account(aspnet or iis_wpg). You can set the TempStorage directory to replace permisson entries on all child objects.
Right Click TempStorage folder and select properties
Select the security tab (ensure the proper read/write/modify permissons are here)
Click the Advanced button
Check the second checkbox - Replace permissions entries on all child objects with entries shown here that apply to child objects.
Now all files that you add to the TempStoreage folder will inherit the permissions allowing you webuser account to read the jpg file.
Instead of granting permissions to ASPNET user, grant permissions to NETWORK SERVICE user. Modify permissions within the folder should be enough, no need to give full permissions (no reason to give more permissions than needed)
for more details read forum : http://forums.asp.net/t/1013434.aspx/1
the error is pretty obvious there Access to the path 'bin\myprojname.pdb\' is denied. the user the web console process is running under (not the user you created in the webconsole, the actual windows user), most likely "Network Service" doesnt have permissions to that folder.
You can either - Right click on that folder, goto permissions and add the "Network Service" user - Right click on that folder, goto permissions and add the "Everyone" user
that should fix that problem.

Resources