i want to save file upload file in 'C:\inetpub\wwwroot\Content\SpeechFile\' in visual studio i can save this files
if (file != null)
{
string urlfile;
string path = Server.MapPath("~" + "\\Content\\Apk\\");
string filename = System.IO.Path.GetFileName(file.FileName);
while (System.IO.File.Exists(path + "\\" + filename))
filename = "1" + filename;
urlfile = "../../Content/Apk/" + filename;
file.SaveAs(path + filename);
model.Fileurl = urlfile;
}
but on server i have an error
Access to the path 'C:\inetpub\wwwroot\Content\SpeechFile\nokia 700.jpg' is denied.
Generally the user account the application pool runs under will not have permissions to write to any sub-folders for security reasons. You will have to check which user your application runs under and then give that user write permissions to the SpeechFile folder. Make sure that is the only folder that you do give it write permissions to so that the security risk is minimised.
The only way to solve this problem is to not write to that folder. You are not allowed to write to that folder .Just Tried to Give Access Rights to your Folder SpeechFile.
You may also use Environment.SpecialFolder to help you find where you need to go.
Related
Find Snapshot here While running the [IBM Security AppScan] tool for one of my asp.net mvc web applications, I am getting path traversal vulnerabilities in my code. Please see snapshot attached and sample code to understand the issue better. Is there a way to fix such issues?
Sample Code:
var storagePath = ConfigurationManager.AppSettings.Get("DOCS_STORAGE_PATH") + #"\Attachments";
var strMonth = DateTime.Now.Month.ToString().Length == 1 ? "0" + DateTime.Now.Month : DateTime.Now.Month.ToString();
var strYear = DateTime.Now.Year.ToString();
var strFolder = strYear + #"\" + strMonth + #"\";
storagePath = storagePath + #"\" + strFolder;
if (!Directory.Exists(#"" + storagePath))
{
Directory.CreateDirectory(#"" + storagePath);
}
You need to enforce your input validation to solve your issue.
you should validate storagePath in the first line after the reading of the configuration.
But, anyway, If the path is store in a configuration on your server, I suspect a False Postive from AppScan Source
If you are using asp.net MVC framework then you don't need to worry about directory traversal at-least for the config files, dll , cshtml files etc. IIS will not server these types of sensitive information at any cost. But still its always better to encrypt your config files if it has some sensitive information like password , connection string etc ..
It's better to encrypt the machine key and connection string info in config files for ease of use.
The next point if the files we save our self, it may be in database or in server path.
In both cases we have to be careful about the attacks. Not only directory attack but also file upload attack.
If your file share is readable by the user that your app pool is
running under (Network Service by default) you can remove the virtual
directory completely and create an ASP.NET(any framework)application
that will stream the files to the browser. If you're using MVC it's
simply returning a file result. This has an added benefit in that you
will be able to restrict the users from downloading the files
Note : Since you are taking the path from web.config doesn't meant that, the files under that path are safe against directory attack. If a hacker somehow get the path , then he can try that directly in the browser\hacking tools\etc.. So the objective should be to secure the files not the path
Simple idea is to create another application/method which is capable of serving the file stream based on request. There you can validate the user and serve the file, file can even be saved in database or file system (there app pool user's doesn't have direct access)
Well, I already tried a lot of stuff to solve this issue, but none did.
I developed a Reporting Service (2005) and deployed it.
This report will be used by everyone who access a website (it's a internet site, so, won't be accessed by intranet) developed on the framework 3.5 (but I think the framework's version is not the source of the problem).
When the user clicks on the button to download the .pdf which the Reporting automatically generates (the end-user never sees the html version of the Report), it asks for windows credentials.
If the user enters a valid credential (and this credential must be a valid credential on the server which the Reporting Service is deployed), the .pdf is obviously downloaded.
But this can't happen. The end-user must download the .pdf directly, without asking for credentials. Afterall, he doesn't even have the credentials.
Response.Redirect("http://MyServer/ReportServer/Pages/ReportViewer.aspx?%2fReportLuiza%2fReportContract&rs:Format=PDF&NMB_CONTRACT=" + txtNmbContractReport.Text);
The code snippet above, shows the first version of my code when the user clicks the button. This one propmts for the Windows credentials.
I already tried to change on IIS the Authentication of the virtual directory ReportServer, but the only one which works is the Windows Credentials. The other ones doesn't even let me open the virtual directory of the Report or the Report Manager's virtual directory.
When I tried to change it to Anonymous Authentication he couldn't access the DataBase. Then I choose the option to Credentials stored securely on the report server. Still doesn't work.
The physical directory of my ReportServer virtual directory points to the reporting server folder on the Hard Disk (C:\Program Files\Microsoft SQL Server\MSSQL.5\Reporting Services\ReportServer). I moved the same folder to my wwwroot directory.
Didn't work. The virtual directory didn't even open. Then I read this could be a problem because I had the same name on two folders (one in C: and other in wwwroot). So I changed the name of the one in wwwroot. Same issue of the DataBase connection couldn't be done.
I returned the physical path to C:
Below, is the second version of my button's event code:
ReportExecutionService rs = new ReportExecutionService();
rs.Credentials = System.Net.CredentialCache.DefaultCredentials;
rs.Url = "http://MyServer/ReportServer/ReportExecution2005.asmx";
// Render arguments
byte[] result = null;
string reportPath = "/ReportLuiza/ReportContract";
string format = "PDF";
// Prepare report parameter.
ParameterValue[] parameters = new ParameterValue[1];
parameters[0] = new ParameterValue();
parameters[0].Name = "NMB_CONTRACT";
parameters[0].Value = txtNmbContractReport.Text;
string encoding;
string mimeType;
string extension;
Warning[] warnings = null;
string[] streamIDs = null;
ExecutionInfo execInfo = new ExecutionInfo();
ExecutionHeader execHeader = new ExecutionHeader();
rs.ExecutionHeaderValue = execHeader;
execInfo = rs.LoadReport(reportPath, null);
rs.SetExecutionParameters(parameters, "pt-br");
String SessionId = rs.ExecutionHeaderValue.ExecutionID;
try
{
result = rs.Render(format, null, out extension, out encoding, out mimeType, out warnings, out streamIDs);
execInfo = rs.GetExecutionInfo();
}
catch (SoapException se)
{
ShowMessage(se.Detail.OuterXml);
}
// Write the contents of the report to an pdf file.
try
{
using (FileStream stream = new FileStream(#"c:\report.pdf", FileMode.Create, FileAccess.ReadWrite))
{
stream.Write(result, 0, result.Length);
stream.Close();
}
}
catch (Exception ex)
{
ShowMessage(ex.Message);
}
For this code, I had to add a WebReference to the .asmx file mentioned in it.
When I'm debugging (on Visual Studio 2010), the code above works fine, doesn't asking for credentials (unfortunately, it doesn't prompt the option to open, save or cancel de file download. But this is another problem, no need to worry with it now) and save the file on C:.
When published, the code doesn't work. An erros says: The permission granted to user 'IIS APPPOOL\ASP.NET v4.0' are insuficient for performing this operation. So I added to the Reporting Service's users this user. When I tried again, the error is: Login failed for user IISAPPPOOL\ASP.NET v4.0. Cannot create a connection to data source 'MyDataSourceName'.
Both Report and WebSite are deployed/published on the same server with a IIS 7.5 version.
Summarizing: I need a solution where there is no credential prompt, and the user can choose where it wants to save the .pdf file.
Any help will be appreciated.
If you need more information to help me, just ask.
Thanks in advance.
One solution would be to create a new App Pool with an account that has the rights to access your restricted resources and then assign your web application to it.
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.
I have my upload control saving a file to a mapped network drive on the web server. Even if I hard code a path, it still saves the file in the root directory of the mapped network drive.
Here is my code for the upload...
protected void ASPxUploadControl1_FileUploadComplete(object sender, DevExpress.Web.ASPxUploadControl.FileUploadCompleteEventArgs e)
{
if (e.IsValid)
{
string uploadDirectory = "//DOCSD9F1/TECHDOCS/";
string fileName = e.UploadedFile.FileName;
string path = "T:/Manuals/";
e.UploadedFile.SaveAs(path + fileName);
e.CallbackData = fileName;
}
}
On the web server, the mapped network drive is used as an index to host some documents, and the path on IIS is //DOCSD9F1/TECHDOCS/ ... but in windows explorer it is T:/ .. I have tried hard coding each of these into the path name but the file still saves to the root T:/ directory and not the sub directory I give it..
The folders are not read-only like I first assumed so I am stuck from here
Have you tried with backslashes instead of slashes:
string uploadDirectory = #"\\DOCSD9F1\TECHDOCS";
...
e.UploadedFile.SaveAs(Path.Combine(uploadDirectory, fileName));
For local paths, use backslashes. For URLs use slashes.
Also note, that your web application will typically run under a system account where mapped network drives like "T:\" are not available (these are available for the logged in user).
Use backslashes, like in "\\DOCSD9F1\TECHDOCS".
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.