How to impersonate an account and start explorer.exe? - vb.net

I have the following code. Which results in error The application was unable to start correctly (0xc0000142). Click OK to close the application. Can someone tell me what is wrong?
Dim domain, username, passwordStr, remoteServerName As String
Dim password As New Security.SecureString
Dim command As New Process
domain = DBc.GetControlVal(34) 'Domain Name
username = DBc.GetControlVal(35) 'Network username
passwordStr = ENDC.DecryptData(DBc.GetControlVal(36)) 'password
remoteServerName = DBc.GetControlVal(37) 'Remote server Name
Dim impersonator As New clsAliasAccount(username, passwordStr)
For Each c As Char In passwordStr.ToCharArray
password.AppendChar(c)
Next
command.StartInfo.FileName = "C:\Windows\explorer.exe"
command.StartInfo.Arguments = "\\" & remoteServerName & "\"
command.StartInfo.UserName = username
command.StartInfo.Password = password
command.StartInfo.Domain = domain
command.StartInfo.Verb = "open"
command.StartInfo.UseShellExecute = False
impersonator.BeginImpersonation()
command.Start()
impersonator.EndImpersonation()

Related

Accessing file on remote computer

I am trying to open a file on a remote computer. The computer I am trying to access has a Domain/Username/Password that are required. I am unable to find out how to use the credentials to access the file.
I don't have much, but I have this so far.
Dim username = "domain\username"
Dim Pass = "password "
Dim path As String = "\\" & FIP & "\C$\Test.log "
Process.Start(path)
I cannot figure out how to incorporate the username/pass into the path to run it.
You need to initialize ProcessStartInfo object and pass that as parameter to Process.start.
Dim path As String = "\\" & FIP & "\C$\Test.log "
Dim RemoteMachine As New ProcessStartInfo(path)
RemoteMachine.UserName = "domain\username"
RemoteMachine.Password = "password"
Process.Start(RemoteMachine)

VB NET Read Remote Registry

I'm trying to get the architecture and the operating system of many remote pcs.
In order to do that i'm querying Win32_OperatingSystem and parsing the "Caption" for the O.S. and for the architecture im reading OSArchitecture .
In Windows XP this value does not exists, so i thought that reading the HKLM\SYSTEM\CurrentControlSet\Control\Session Manager\Environment\PROCESSOR_ARCHITECTURE
would have done the trick like this code:
Try
Dim co As New ConnectionOptions
co.Impersonation = ImpersonationLevel.Impersonate
co.Authentication = AuthenticationLevel.PacketPrivacy
co.EnablePrivileges = True
co.Username = username
co.Password = password
Dim scope As New ManagementScope("\\" & machine.Text & "\root\cimv2", co)
scope.Connect()
Dim environmentKey, asd2 As Microsoft.Win32.RegistryKey
Dim asd As String
environmentKey = RegistryKey.OpenRemoteBaseKey(RegistryHive.LocalMachine, machine.Text)
asd2 = environmentKey.OpenSubKey("SYSTEM\CurrentControlSet\Control\Session Manager\Environment", True)
asd = asd2.GetValue("PROCESSOR_ARCHITECTURE")
Debug.Print("asd: " + asd)
environmentKey.Close()
Catch ex As Exception
MessageBox.Show(ex.ToString)
End Try
My problem is: if im trying this code I get an System.Security.SecurityException: "Accessing remote registry not permitted"
I am, and i know the administrator username and password.
In fact if I run a simple cmdkey /add:targetname /user:username /pass:password
It works.
So why do I have to run a cmdkey /add even if i have alredy specified the username and password in the ConnectionOptions ??
P.S. Sorry for my bad English
This may very well be because remote registry access is not enabled on the target PC.
Even if you know the administrator credentials, remote access to the registry will not work if the feature isn't enabled on the target PC.
To enable it, see the following Microsoft Knowledge Base Article, which covers a variety of Windows Operating Systems: https://support.microsoft.com/en-us/kb/314837
All right, i got it:
Const HKEY_current_user As String = "80000002"
Dim options As New ConnectionOptions
options.Impersonation = ImpersonationLevel.Impersonate
options.EnablePrivileges = True
options.Username = ".\administrator"
options.Password = "my_password"
Dim myScope As New ManagementScope("\\" & RemotePCHostname & "\root\default", options)
Dim mypath As New ManagementPath("StdRegProv")
Dim mc As New ManagementClass(myScope, mypath, Nothing)
Dim inParams As ManagementBaseObject = mc.GetMethodParameters("GetDWORDValue")
inParams("hDefKey") = UInt32.Parse(HKEY_current_user,System.Globalization.NumberStyles.HexNumber) 'RegistryHive.LocalMachine
inParams("sSubKeyName") = "SYSTEM\CurrentControlSet\Control\Session Manager\Environment"
inParams("sValueName") = "PROCESSOR_ARCHITECTURE"
Dim outParams As ManagementBaseObject = mc.InvokeMethod("GetStringValue", inParams, Nothing)
If (outParams("ReturnValue").ToString() = "0") Then
MessageBox.Show(outParams("sValue").ToString())
Else
MessageBox.Show("Error retrieving value : " + outParams("ReturnValue").ToString())
End If

Visual Basic, Opening forms

I am trying to make a program that requires the user to sign in and if the right username and password is entered then open a form for that user. The way I have it done just now is the username is stored in a variable and I was wondering how I can use the text from the variable in the form name for example:
UserName = User1 then
FrmUser1.show
UserName = JohnSmith then
FrmJohnSmith.show
Here is an excerpt from the code I have so far:
Dim Path As String = "Account_File.text "
Dim Read_File() As String = File.ReadAllLines(Path)
Dim NoOfLines As Integer = Read_File.Length
Dim UserName(NoOfLines) As String
Dim Password(NoOfLines) As String
Dim LastNonEmpty As Integer = -1
Dim InputUserName As String = ""
Dim InputPassword As String = ""
If TxtUserName.Text = "" Then
MsgBox("Please enter a username.")
GoTo InvalidDetails
Else
InputUserName = TxtUserName.Text
End If
If TxtPassword.Text = "" Then
MsgBox("Please enter a Password.")
GoTo InvalidDetails
Else
InputPassword = TxtPassword.Text
End If
For i = 0 To NoOfLines
Dim SplitString() As String = Split(Read_File(i))
For j As Integer = 0 To SplitString.Length - 1
If SplitString(j) <> "" Then
LastNonEmpty += 1
SplitString(LastNonEmpty) = SplitString(j)
End If
Next
ReDim Preserve SplitString(LastNonEmpty)
LastNonEmpty = -1
UserName(i) = SplitString(0)
Password(i) = SplitString(1)
Next
For i = 0 To NoOfLines
If UserName(i) = InputUserName And Password(i) = InputPassword Then
frm.show()
Else
MsgBox("Either the username or password is incorrect.")
End If
Next
Some sample code:
Dim formname = "Form" + TxtUserName.Text
Dim typename = Me.GetType().Namespace + "." + formname
Dim type = Me.GetType().Assembly.GetType(typename)
If type IsNot Nothing Then
Dim form = CType(Activator.CreateInstance(type), Form)
form.Show()
End If
Which assumes that all forms live in the same assembly and have the same namespace. Do keep in mind that your customer isn't very likely to be thrilled to have to call you every single time he gets a new employee. Or for that matter is going to like you asking for username + password without providing the kind of security guarantees that a Windows logon already provides. Don't do this.

check connection sharing network folder using username and password

In my application check network folder connection using following code
Dim myIP As IPHostEntry = Dns.GetHostEntry(txtNetworkDrive.Text.Trim.Split("\", options:=StringSplitOptions.RemoveEmptyEntries)(0))
Dim IPAddress As String = myIP.AddressList.GetValue(0).ToString
Dim xStr As New System.Security.SecureString
For Each c As Char In txtNetworkPassword.Text.Trim
xStr.AppendChar(c)
Next
Dim psi As New ProcessStartInfo()
psi.UserName = txtNetworkusername.text
psi.Password = xStr
psi.Domain = IPAddress
psi.FileName = txtNetworkDrive.Text
psi.UseShellExecute = False
Process.Start(psi)
The Input like
Network drive = "\\Sys4\shareddocs"
Network password= "sys4"
Network Username="user"
IPaddress="198.168.0.24"
But all time it show login failure bad username and password. what am doing wrong?
How get the solutions?

Insert value into row in linq vb by calling record

I have a LINQ VB.NET project. I have a table "User". I enter all the user details into the table. This includes and email address. I have a method which randomly generates a password. I have another method which calls an email address, based on what has been entered in a text box, and sends the password to that email address. My problem is that I can't figure out how to insert the newly generated password into the row belonging to the email address I have just called. The text box that the email address is entered into is "txtEmail". It can be assumed that the entry a "User" has already been completed, minus the password. The following method generates the password:
Public Function GeneratePassword() As String
'String variables tells how many characters password will contain.
Dim PasswordLength As Int16 = "12"
'Empty string will hold randomly generated password
Dim NewPassword As String = ""
'Characters allowed in this new password
Dim allowedChars As String = ""
allowedChars = "1,2,3,4,5,6,7,8,9,0"
allowedChars += "A,B,C,D,E,F,G,H,I,J,K,L,M,N,O,P,Q,R,S,T,U,V,W,X,Y,Z,"
allowedChars += "a,b,c,d,e,f,g,h,i,j,k,l,m,n,o,p,q,r,s,t,u,v,w,x,y,z,"
'Declare array to house each character generated from allowed list of characters
Dim sep As Char() = {","c}
Dim arr As String() = allowedChars.Split(sep)
Dim IDString As String = ""
Dim temp As String = ""
'utilize the "random" class
Dim rand As New Random()
'loop through the character generation process until PasswordLength is met
For i As Integer = 0 To Convert.ToInt32(PasswordLength) - 1
temp = arr(rand.[Next](0, arr.Length))
IDString += temp
NewPassword = IDString
Next
'places new password in variable
Return NewPassword
End Function
Following on from that the following method fetches the email address from the database, calls the "GeneratePassword" method and emails the password to the user. It does not save the password to the database, which is the problem I have.
Protected Sub btnPassword_Click(sender As Object, e As System.EventArgs) Handles btnPassword.Click
If True Then
'establish connection with database
Dim db As New OrionDataClassesDataContext()
'initialise global variabel to take email string entered in text box
GlobalVariables.SearchUserEmail = txtEmailAddress.Text
'initialise global variable to hold email address retrieved from database
GlobalVariables.CurrentEmailAddress = (From u In db.Users
Where u.Email = SearchUserEmail
Select u.Email).FirstOrDefault
'calls generatepassword method
Dim stNewPassword As String = GeneratePassword()
'create new mailmessage to construct and sendemail
Dim Mail As New MailMessage
Try
Mail.Subject = "Your Password Has Been Reset"
'gets email address from database when user enters it
Mail.To.Add(GlobalVariables.CurrentEmailAddress)
'address for email to be sent from
Mail.From = New MailAddress("XXX#XXXX.com")
Mail.Body = "Your new pasword is: " + stNewPassword + ". Please keep this safe."
'define smpt server to be used
Dim SMTP As New SmtpClient("smtp.gmail.com")
SMTP.EnableSsl = True
'authenticate connection with smpt server and email address
SMTP.Credentials = New System.Net.NetworkCredential("XXXX#XXX.com", "XXXXX")
SMTP.Port = 587
SMTP.Send(Mail)
'alert when message is sent correctly
MsgBox("Email sent successfully!")
txtEmailAddress.Text = ""
Catch ex As Exception
'displays error message when email is not sent
MsgBox("Email not sent - Check address")
txtEmailAddress.Text = ""
End Try
End If
End Sub
I have been playing around with a few scenarios but I always seem to end up just trying to create a brand new row entry, which is not what I want to do. Any advice would be appreciated.