copy file from local to remote server - asp.net

I'm dynamically creating html files on my local system (using HTMLTEXTWRITER, then save them using streamwriter to local file system). I want to copy this file to my remote server withour user interaction, so that my users can read file. I use C#
for instance I want to copy from d:\myfile.html to mysite.com\myfile.html, how can I do it?

I have used this and it worked. may be useful
for holding path of local
rPath = "\\" & Request.UserHostAddress & "\c$\temp\"
for output file
rOutput = Session.SessionID & "_" & Format(Date.Now(), "ddMMyyhhmmss") & ".pdf"
now: report will be created at localhost\c\temp

You can't use the System.IO classes for this (unless you have access to the remote server as a network drive), but you can programmatically POST the file from the client to the remote server over HTTP using System.Net.
Here's a snippet using the WebRequest class:
WebRequest request = WebRequest.Create( url );
request.Timeout = 1000; // some appropriate value
request.Method = "POST";
request.ContentType = "application/x-www-form-urlencoded";
request.ContentLength = 0; // set a length here
using( StreamWriter requestStream = new StreamWriter( request.GetRequestStream(), System.Text.Encoding.UTF8) ) {
// write to the stream here using requestStream.Write();
requestStream.Close();
}
More info for HTTP: http://msdn.microsoft.com/en-us/library/debx8sh9.aspx
Alternatively, you could use a protocol designed for transferring files like FTP (or something more secure) which isn't that hard to do in code.
FTP options: http://msdn.microsoft.com/en-us/library/ms229718

Is you remote server based on Windows and in the same workgroup or domain with you working machine ? If so, you can turn on the Windows File Sharing on the server. Then you can copy your file with cmd like this:
copy c:\test.txt \\mysite.com
The path "\\mysite.com" is also valid used by File.Copy in C#.
Otherwise, you need to set up a FTP environment on you server and use the FTP related API in C#.

You could set-up an FTP server and copy the files programmatically via FTP.
An example would be found here or here.

There are three ways by which you can copy the file to remote server.
Using normal file copy mode. Here you need to have access to the the webserver shared path. If the webserver is in same network as your application, then you can share the webroot and provide write access to the user who is running the application. He can then use File.Copy("source.txt", "\\Servername\SharedFolderName\target.txt").
The second approach is to use FTP to copy the file to the remote server. This MSDN example would help you on how to do this. This will work with most of the shared hosting providers.
You can use HTTP POST as noted by Tim. But this would let any user to perform the post. You may have to take care of user provisioning, authentication and authorization. IMO, keep this as last option as provisioning user and providing rights to certain path, may become cumbersome.

Related

How to fix directory traversal security vulnerability in C# asp.net?

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)

How do I decode data returned in the Remote Resources URL (webfeed.aspx) of an RDP server?

How do I decode the rdweb/feed/webfeed.aspx content from a Microsoft remote desktop(RDP) server?
I am having difficulty locating the encoding of the webfeed.aspx or more specifically https:// RDP url /rdweb/feed/webfeed.aspx url of the RDP client. In Microsoft's RDP client, the data resolves to references to directories and applications that can be used as shortcuts for the RDP connection.
The file that I get appears to be a base64 encoded file. From what I have read, this should be an XML file that describes the resources, but it seems to be compressed or encoded somehow. I am having no issue getting the data. I can read it via a browser (though not understand it) and Microsoft's RDP client is pulling the data appropriately, so the data is good. I need to decode/process the data because I am extending an open source RDP tool to do the same as Microsoft's RDP client.
Here is an example,from the text file from a test server's rdweb/feed/webfeed.aspx
46672D19C141995BFAA3317324E7595B8AF001B09CF315A3668E2335F383079AA7397E6E8ADF56379306F18DCCFFB4A542CC4C8B81609D5E9D738F8347BC0372EB7513DD797EF0BFA921F7D6E2A108C6A12F44712D57D6191FB068AF1733256291BC0BD7429AD585DA9E6ECC3D1380562A091E980D6908E2E0EF4184689329686AD132E2D63945810D93F88ECAEC6A0B9460F23B9ABF229F974D3B32D0D7415CD8EAF1B6B93678718C9E658F0CEDA604D5294FF3458FB2ABD798A668E8E6714939C8115EC00A13354F8EF22563CF65F5C6D053306D4C3276032D045752412BA760C683C5
Have you tried something like this?
HttpWebRequest httpWebRequest = (HttpWebRequest)WebRequest.Create("https://RDPurl/rdweb/feed/webfeed.aspx");
HttpWebResponse httpWebResponse = (HttpWebResponse)httpWebRequest.GetResponse();
string connectionXml;
using (StreamReader streamReader = new StreamReader(httpWebResponse.GetResponseStream()))
{
connectionXml = streamReader.ReadToEnd();
}
More detailed code is here.
The resulting connectionXml string should be Resource List Syntax.

iis7 website accessed externally downloads files to server instead of local machine

I've a site set up in IIS. It's allows users to download files from a remote cloud to their own local desktop. HOWEVER, the context seems to be mixed up, because when I access the website externally via the IP, and execute the download, it saves the file to the server hosting the site, and not locally. What's going on??
My relevant lines code:
using (var sw2 = new FileStream(filePath,FileMode.Create))
{
try
{
var request = new RestRequest("drives/{chunk}");
RestResponse resp2 = client.Execute(request);
sw2.Write(resp2.RawBytes, 0, resp2.RawBytes.Length);
}
}
Your code is writing a file to the local filesystem of the server. If you want to send the file to the client, you need to do something like
Response.BinaryWrite(resp2.RawBytes);
The Response object is what you use to send data back to the client who made the request to your page.
I imagine that code snippet you posted is running in some sort of code-behind somewhere. That is running on the server - it's not going to be running on the client. You will need to write those bytes in the Response object and specify what content-type, etc. and allow the user to Save the file himself.

401 Unauthorised errors when attempting to download ASP page to file

Issue
Msxml2.ServerXMLHTTP keeps returning 401 - Unauthorised errors each time we attempt to read the contents of a file (ASP) from a web server.
Source server is running IIS6, using NTLM integrated login.
This process has been used successfully before, but only in as far as extracting XML files from external websites, not internal ones.
The proxy settings in the registry of the server on which the script is run has also been updated to bypass the website in question, but to no avail.
All paths identified in the VBScript have been checked and tested, and are correct.
User running the script has correct read/write permissions for all locations referenced in the script.
Solution needed
To identify the cause of the HTTP 401 Unauthorised messages, so that the script will work as intended.
Description
Our organisation operates an intranet, where the content is replicated to servers at each of our remote sites. This ensures these sites have continued fast access to important information, documentation and data, even in the event of losing connectivity.
We are in the middle of improving the listing and management of Forms (those pesky pieces of paper that have to be filled in for specific tasks). This involves establising a database of all our forms.
However, as the organisation hasn't been smart enough to invest in MSSQL Server instances at each site, replication of the database and accessing it from the local SQL server isn't an option.
To work around this, I have constructed a series of views (ASP pages) which display the required data. I then intend to use Msxml2.ServerXMLHTTP by VBScript, so I can read the resulting pages and save the output to a static file back on the server.
From there, the existing replication process can stream these files out to the site - with users having no idea that they're looking at a static page that just happened to be generated from database output.
Code
' Forms - Static Page Generator
' Implimented 2011-02-15 by Michael Harris
' Purpose: To download the contents of a page, and save that page to a static file.
' Target category: 1 (Contracts)
' Target Page:
' http://sharename.fpc.wa.gov.au/corporate/forms/generator/index.asp
' Target path: \\servername\sharename\corporate\forms\index.asp
' Resulting URL: http://sharename.fpc.wa.gov.au/corporate/forms/index.asp
' Remove read only
' Remove read only flag on file if present to allow editing
' If file has been set to read only by automated process, turn off read only
Const READ_ONLY = 1
Set objFSO = CreateObject("Scripting.FileSystemObject")
Set objFile = objFSO.GetFile("\\server\sharename\corporate\forms\index.asp")
If objFile.Attributes AND READ_ONLY Then
objFile.Attributes = objFile.Attributes XOR READ_ONLY
End If
Dim webObj, strURL
Set webObj = CreateObject("Msxml2.ServerXMLHTTP")
strURL = "http://sharename.fpc.wa.gov.au/corporate/forms/generator/index.asp"
webObj.Open "GET", strURL
webObj.send
If webObj.Status=200 Then
Set objFso = CreateObject("Scripting.FileSystemObject")
Set txtFile = objFso.OpenTextFile("file:\\servername.fpc.wa.gov.au\sharename\corporate\forms\index.asp", 2, True)
txtFile.WriteLine webObj.responseText
txtFile.close
ElseIf webObj.Status >= 400 And webObj.Status <= 599 Then
MsgBox "Error Occurred : " & webObj.Status & " - " & webObj.statusText
Else
MsgBox webObj.ResponseText
End If
Replace your line:
webObj.Open "GET", strURL
With:
webObj.Open "GET", strURL, False, "username", "password"
In most cases 401 Unauthorized means you haven't supplied credentials. Also you should specifiy False to indicate you don't want async mode.
It sounds like the O.P. got this working with the correct proxy settings in the registry (http://support.microsoft.com/kb/291008 explains why proxy configuration will fix this). Newer versions of ServerXMLHTTP have a setProxy method that can be used to set the necessary proxy configuration in your code instead.
In the O.P. code above, after webObj is created, the following line of code would set up the proxy correctly:
webObj.setProxy 2, "0.0.0.0:80", "*.fpc.wa.gov.au"
ServerXMLHTTP will pass on the credentials of the user running the code if it is configured with a proxy, and if the target URL bypasses that proxy. Since you are bypassing the proxy anyway, you can make it a dummy value "0.0.0.0:80", and make sure your target url is covered by what you specify in the bypass list "*.fpc.wa.gov.au"
I would first test if you can reach your url through a normal browser on the same server X you run your code on (A). I would try then reach the url from another PC. One never used to reach that url but in the same network as server X (B).
If B works but A doesn't I would suspect that for some reason your source server (i.e. that one that serves the url) blocks server X for some reason. Check the security settings of II6 and of NTLM.
If both A and B don't work, there is something wrong more in general with your source server (i.e. it blocks everything or NTML doesn't allow you in).
If A works (B doesn't matter then), the problem has to be somewhere in your code. In that case, I would recommend fiddler. This tool can give you the HTTP requests of both your browser and your code in realtime. You can then compare both. That should give you at least a very strong hint about (if not immediately give you) the solution.

Reading a remote URL in Domino LotusScript

I have a remote RSS feed which has to be transformed into Notes documents using LotusScript.
I've looked through the documentation, but I can't find how to open a remote URL in order to retrieve its contents. In other words, some sort of wget- or curl-like functionality. Can anyone shed some light on how to do this? Using Java is not an option.
Thanks.
Check out the NotesDOMParser class - available in LotusScript - which lets you (indirectly) pull XML from a remote URL and process in a an XML DOM object.
You can pull the XML into a string using the MSXMLHTTP COM object, then use NotesStream to send the XML to the NotesDOMParser.
I have not tested, but the code would look something like this:
...
Set objXML = CreateObject("Microsoft.XMLHTTP")
objXML.open "GET", sURL, False, "", ""
objXML.send("")
sXMLAsText = Trim$(objXML.responseText)
Set inputStream = session.CreateStream
inputStream.Open (sXMLAsText)
Set domParser=session.CreateDOMParser(inputStream, outputStream)
domParser.Process
...
Documentation: http://publib.boulder.ibm.com/infocenter/domhelp/v8r0/index.jsp?topic=/com.ibm.designer.domino.main.doc/H_NOTESDOMPARSER_CLASS.html
You can't open a remote URL (whether it's HTTP or some other protocol) using native Lotusscript: the object library simply doesn't support it. If you're running on a Windows server, you should be able to use the MS XMLHttp DLLs to get a handle on your remote file via a URL, as specified by the previous answer. (Alternatively, this link specifies how to parse and open a UNC path with Lotusscript—again, Windows only).
All that said, if I understand you correctly, you're not using HTTP to access the remote file at all. If the RSS file is just on a simple path, why can't you open the file for parsing in the normal way with Lotusscript?

Resources