Monitoring malicious PowerShell usage through log analysis1333165/FULLTEXT01.pdf · Security has...

79
Monitoring malicious PowerShell usage through log analysis Jesper Magnusson Computer Science and Engineering, master's level 2019 Luleå University of Technology Department of Computer Science, Electrical and Space Engineering

Transcript of Monitoring malicious PowerShell usage through log analysis1333165/FULLTEXT01.pdf · Security has...

Page 1: Monitoring malicious PowerShell usage through log analysis1333165/FULLTEXT01.pdf · Security has become a hot topic around the world but focuses more on the perime-ter than inside

Monitoring malicious PowerShell usage

through log analysis

Jesper Magnusson

Computer Science and Engineering, master's level

2019

Luleå University of Technology

Department of Computer Science, Electrical and Space Engineering

Page 2: Monitoring malicious PowerShell usage through log analysis1333165/FULLTEXT01.pdf · Security has become a hot topic around the world but focuses more on the perime-ter than inside

(This page is intentionally left almost blank)

Page 3: Monitoring malicious PowerShell usage through log analysis1333165/FULLTEXT01.pdf · Security has become a hot topic around the world but focuses more on the perime-ter than inside

Abstract

Security has become a hot topic around the world but focuses more on the perime-ter than inside networks which opens up vulnerabilities. Directed cyber-attackstowards the energy sector which leverages this fact has increased and can have dis-astrous effect, even on national level. To counter this, a solution to monitor theusage of the most powerful and popular built-in tool among attackers - PowerShell- was implemented.

A test-bed was set up reflecting a corporate network with two separate activedirectory domains, one for office clients and one for critical infrastructure. It wasshown that attackers only needed to overtake the office active directory domain inorder for gain easy access to the critical active directory domain. To simulate attacksof this type, a collection of malicious scripts was gathered from which a number ofpossible scenarios for taking over the office active directory domain via PowerShellwas created.

Windows has several options for logging executions of PowerShell commands onmachines. The one used and deemed most beneficiary was ”Module logging” withthe addition of a filtered result of process creation logs. To monitor the logs createdon the office client from PowerShell executions, a system based on the ”ELK stack”was set up. This system gathered, processed, stored and visualized logs along withthe result of their analysis. The system analyzed logs with the aid of a customsoftware called ”ESPSA” which based on different parameters and contexts assignedevery execution with a risk value indicating the level of maliciousness. To be able toassign risk values, the maliciousness of every command had to be evaluated. Thiswas done with the aid of a mathematical expression that gave values between 0 and100 based on the probability of benign execution and the security risk of the actualcommand.

The evaluation shows that all simulated attack scenarios were detected as mali-cious by reaching total risk values above the threshold of 100 in their exact imple-mentation. It also shows that possible branching of these attacks could instead leadto a value below the threshold and become undetectable. Evaluation also showsthat ”Module logging” is unable to detect certain types of executions, primarilythose of .NET Framework interactions, which affects the monitoring possibilities formalicious behavior severely.

i

Page 4: Monitoring malicious PowerShell usage through log analysis1333165/FULLTEXT01.pdf · Security has become a hot topic around the world but focuses more on the perime-ter than inside

List of Figures

1 Industroyer overview . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 102 Test-bed used for vulnerability evaluation . . . . . . . . . . . . . . . . . . 153 Test-bed with implemented solution . . . . . . . . . . . . . . . . . . . . . 244 Process flow between solution components . . . . . . . . . . . . . . . . . . 255 Process flow between ESPSA components . . . . . . . . . . . . . . . . . . 276 Example graph of Akima Cubic Spline Interpolation for time risk factoring

with working hours between 8 and 17 . . . . . . . . . . . . . . . . . . . . 317 3D plot of equation 2 . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 42

List of Tables

1 Malicious PowerShell scripts . . . . . . . . . . . . . . . . . . . . . . . . . . 162 enabled GPOs for PowerShell logging . . . . . . . . . . . . . . . . . . . . . 233 PowerShell command risk assignments . . . . . . . . . . . . . . . . . . . . 324 Outcome of simulation - Local files . . . . . . . . . . . . . . . . . . . . . . 375 Outcome of simulation - MSI packages . . . . . . . . . . . . . . . . . . . . 386 Outcome of simulation - Saved browser credentials . . . . . . . . . . . . . 39

List of Listings

1 PowerShell logon script . . . . . . . . . . . . . . . . . . . . . . . . . . . . 202 PowerShell logoff script . . . . . . . . . . . . . . . . . . . . . . . . . . . . 213 Added log structure by Logstash . . . . . . . . . . . . . . . . . . . . . . . 26

List of Equations

1 PowerShell execution risk evaluation . . . . . . . . . . . . . . . . . . . . . 302 PowerShell command risk assignment . . . . . . . . . . . . . . . . . . . . . 32

ii

Page 5: Monitoring malicious PowerShell usage through log analysis1333165/FULLTEXT01.pdf · Security has become a hot topic around the world but focuses more on the perime-ter than inside

Abbreviations

AD Active Directory. 5, 7, 8, 14–16, 18–22, 36, 37, 39, 40

AD DS Active Directory Domain Services. viii, 14–16, 20–22

AI Artificial Intelligence. 49

BHIPS Behavioural Host Intrusion Prevention System. 3

BIOS Basic Input/Ouput System. 7, 16

C# C Sharp. 24, 27

C&C command-and-control. 5–9, 11, 12, 20

CLI Command Line Interface. 13

CMD Command Prompt. iii, 45, 48, Glossary: Command Prompt

CNN Convolutional Neural Network. 3

COM Component Object Model. 12

CPU Central Processing Unit. 8

DC Domain Controller. viii, 15, 16, 21, 40

DCOM Distributed COM. 12

DHCP Dynamic Host Configuration Protocol. 16

DLL Dynamic-Link Library. 6–8, 11, 12

DMS Distribution Management System. 9, 10

DNS Domain Name System. 17, 19

DoS Denial-of-Service. iii, 10, 12, Glossary: Denial-of-Service

FIFO First In First Out. 28

FTP File Transfer Protocol. 21

GPO Group Policy Object. ii, viii, 4, 13, 15, 16, 20, 21, 23, 25, 43–45

HMI Human-Machine Interface. 9

HTML HyperText Markup Language. 7, 19

iii

Page 6: Monitoring malicious PowerShell usage through log analysis1333165/FULLTEXT01.pdf · Security has become a hot topic around the world but focuses more on the perime-ter than inside

HTTP Hyper-Text Transfer Protocol. 5, 7, 8, 25

HTTPS Hyper-Text Transfer Protocol Secure. 11

ICS Industrial Control System. 9

IP Internet Protocol. 6–8, 11, 12, 16, 18, 22

IT Information Technology. 1, 9

JAR Java Archive. 6, 7

JS JavaScript. 7

JSON JavaScript Object Notation. 25–29, 31

MAC Media Access Control. 16

MMS Manufacturing Message Specification. 12

MSI Microsoft Windows Installer. ii, viii, ix, 18, 21, 22, 37, 38, 40

NLP Natural Language Processing. 3

OLE Object Linking and Embedding. iv, 7, 12

OPC OLE for Process Control. iv, 7, 8, 12

OPC DA OPC Data Access. 12

OS operating system. 1, 6–8, 13, 16, 22

PDF Portable Document Format. 6

PLC Programmable Logic Controller. 7

RADIUS Remote Authentication Dial-In User Service. 22

RAT Remote Access Trojan. iv, 1, 8, 22, 42, 45, Glossary: Remote Access Trojan

RDP Remote Desktop Protocol. 16, 18, 20

RTU Remote Terminal Unit. 11

SCADA Supervisory Control And Data Acquisition. 7–10, 20

SIEM Security Information and Event Management. 4, 46

SMB Server Message Block. 7

iv

Page 7: Monitoring malicious PowerShell usage through log analysis1333165/FULLTEXT01.pdf · Security has become a hot topic around the world but focuses more on the perime-ter than inside

SQL Structured Query Language. 12

TCP Transmission Control Protocol. 11, 25, 27, 29

UAC User Access Control. v, 5, Glossary: User Access Control

UPS Uninterruptible Power Supply. 10

URL Uniform Resource Locator. 18, 22

VLAN Virtual Local Area Network. 16

VPN Virtual Private Network. 9

WLAN Wireless Local Area Network. 17

WMI Windows Management Instrumentation. 2

WPA Wi-Fi Protected Access. 16

WSL Windows Subsystem for Linux. 45, 48

XDP XML Data Package. 6

XML Extensible Markup Language. v, 6, 21, 36

Glossary

Command Prompt a command line interpreter application available in most Windowsoperating systems. It is used to execute entered commands. Most of those com-mands automate tasks via scripts and batch files, perform advanced administrativefunctions, and troubleshoot or solve certain kinds of Windows issues. iii, 45

Denial-of-Service a type of cyber-attack in which a malicious actor aims to render acomputer or other device unavailable to its intended users. attacks typically func-tion by overwhelming or flooding a targeted machine with requests until normaltraffic is unable to be processed. iii, 10

keylogger software or hardware which records (logs) the keys struck on a keyboard,typically covertly, so that person using the keyboard is unaware that their actionsare being monitored. 20–22, 37

machine learning the scientific study of algorithms and statistical models that computersystems use to effectively perform a specific task without using explicit instructions,relying on patterns and inference instead. 3, 22

v

Page 8: Monitoring malicious PowerShell usage through log analysis1333165/FULLTEXT01.pdf · Security has become a hot topic around the world but focuses more on the perime-ter than inside

non-malware attack attacks in which an attacker uses existing software, allowed appli-cations and authorized protocols to carry out malicious activities. Non-malwareattacks can gain control of computers without downloading any malicious files,hence the name. Non-malware attacks are also referred to as file-less, memory-based or “living-off-the-land” attacks. 2, 3, 13, 21

phishing the fraudulent attempt to obtain sensitive information such as usernames, pass-words and credit card details by disguising oneself as a trustworthy entity in anelectronic communication. Typically carried out by email spoofing or instant mes-saging, it often directs users to enter personal information at a fake website whichmatches the look and feel of the legitimate site. vi, 11

polling a technique that continually interrogates a peripheral device to see if it has datato transfer. 8

regex regex is a sequence of characters that define a search pattern. 31–36

Remote Access Trojan a type of malware that allows a malicious party access to acomputer system through a remote network connection. iv, 1

sandboxing a security mechanism for separating running programs, usually to mitigatesystem failures or software vulnerabilities from spreading. It is often used to exe-cute untested or untrusted programs or code, possibly from unverified or untrustedthird parties, suppliers, users or websites, without risking harm to the host machineor operating system. 2

social engineering attack the term used for a broad range of malicious activities accom-plished through human interactions. It uses psychological manipulation to trickusers into making security mistakes or giving away sensitive information. 2

spear phishing a phishing method that targets specific individuals or groups withinan organization. It is a potent variant of phishing, a malicious tactic which usesemails, social media, instant messaging, and other platforms to get users to divulgepersonal information or perform actions that cause network compromise, data loss,or financial loss. While phishing tactics may rely on shotgun methods that delivermass emails to random individuals, spear phishing focuses on specific targets andinvolve prior research. 9

User Access Control security feature in Windows that aims to improve security by lim-iting application software to standard user privileges until an administrator autho-rizes an increase or elevation. v, 5

watering hole attack a computer attack strategy, in which the victim is a selected group(organization, industry, or region). In this attack, the attacker guesses or observeswhich websites the group often uses and infects one or more of them with malware.Eventually, some member of the targeted group becomes infected. 7

vi

Page 9: Monitoring malicious PowerShell usage through log analysis1333165/FULLTEXT01.pdf · Security has become a hot topic around the world but focuses more on the perime-ter than inside

web scraping extracting data from websites either manually or by automated bots orweb crawlers. 19

wrapper a method of making one type of software act as an encapsulation of anothersoftware, enabling its execution by acting as an adapter. 21, 22, 37

vii

Page 10: Monitoring malicious PowerShell usage through log analysis1333165/FULLTEXT01.pdf · Security has become a hot topic around the world but focuses more on the perime-ter than inside

Table of Contents

1 Introduction 11.1 Background . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 11.2 Motivation . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 11.3 Problem definition . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 11.4 Delimitations . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 21.5 Thesis structure . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 2

2 Related Work 22.1 Fileless attacks . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 22.2 Deep neural networks . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 32.3 LogRhytm SIEM . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 42.4 ELK stack threat hunting . . . . . . . . . . . . . . . . . . . . . . . . . . . 4

3 Theory 43.1 Attacks . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 43.2 Shamoon analysis . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 5

3.2.1 Infiltration . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 53.2.2 Attack . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 5

3.3 Energetic bear analysis . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 63.3.1 Infiltration . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 63.3.2 Attack . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 7

3.4 Black energy analysis . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 83.4.1 Infiltration . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 93.4.2 Reconnaissance . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 93.4.3 Attack . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 9

3.5 Industroyer analysis . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 103.5.1 Structure . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 11

3.6 Choice of PowerShell . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 123.7 PowerShell . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 13

3.7.1 Logging capabilities . . . . . . . . . . . . . . . . . . . . . . . . . . 133.8 Elastic stack . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 133.9 Active Directory Domain Services (AD DS) . . . . . . . . . . . . . . . . . 14

3.9.1 Group Policy Object (GPO) . . . . . . . . . . . . . . . . . . . . . . 153.9.2 Domain Controller (DC) . . . . . . . . . . . . . . . . . . . . . . . 15

4 Implementation 154.1 Testing . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 15

4.1.1 Test-bed . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 154.1.2 Test tools . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 16

4.2 Attack Simulation Scenarios . . . . . . . . . . . . . . . . . . . . . . . . . . 194.2.1 Local files . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 214.2.2 Microsoft Windows Installer (MSI) packages . . . . . . . . . . . . 21

viii

Page 11: Monitoring malicious PowerShell usage through log analysis1333165/FULLTEXT01.pdf · Security has become a hot topic around the world but focuses more on the perime-ter than inside

4.2.3 Saved browser credentials . . . . . . . . . . . . . . . . . . . . . . . 224.3 Solution . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 22

4.3.1 Prerequisites . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 234.3.2 System Overview . . . . . . . . . . . . . . . . . . . . . . . . . . . . 234.3.3 Beats . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 254.3.4 Logstash . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 254.3.5 Elasticsearch . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 264.3.6 Kibana . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 264.3.7 ESPSA . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 27

4.3.7.1 Overview . . . . . . . . . . . . . . . . . . . . . . . . . . . 274.3.7.2 Architecture . . . . . . . . . . . . . . . . . . . . . . . . . 274.3.7.3 TCP Reader/TCP Sender . . . . . . . . . . . . . . . . . . 294.3.7.4 Aggregator . . . . . . . . . . . . . . . . . . . . . . . . . . 294.3.7.5 Processor . . . . . . . . . . . . . . . . . . . . . . . . . . . 294.3.7.6 Command risks . . . . . . . . . . . . . . . . . . . . . . . . 31

5 Evaluation 365.1 Local files . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 365.2 MSI packages . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 375.3 Saved browser credentials . . . . . . . . . . . . . . . . . . . . . . . . . . . 39

6 Discussion 406.1 Evaluation results . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 406.2 Assigned risk values . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 416.3 Browser security . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 426.4 PowerShell . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 42

6.4.1 Logging capabilities . . . . . . . . . . . . . . . . . . . . . . . . . . 426.4.2 Choice of enabled GPOs . . . . . . . . . . . . . . . . . . . . . . . . 436.4.3 Other defences . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 44

6.4.3.1 ExecutionPolicy . . . . . . . . . . . . . . . . . . . . . . . 446.4.3.2 Disabling PowerShell . . . . . . . . . . . . . . . . . . . . . 45

6.4.4 Monitoring obstacles . . . . . . . . . . . . . . . . . . . . . . . . . . 456.5 Elastic Stack . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 466.6 ESPSA . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 46

6.6.1 Execution time risk interpolation . . . . . . . . . . . . . . . . . . . 466.6.2 Risk half-life . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 476.6.3 Aggregator . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 476.6.4 Output waste . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 48

7 Conclusions and future work 487.1 Future work . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 48

References 50

ix

Page 12: Monitoring malicious PowerShell usage through log analysis1333165/FULLTEXT01.pdf · Security has become a hot topic around the world but focuses more on the perime-ter than inside

Appendices 52

x

Page 13: Monitoring malicious PowerShell usage through log analysis1333165/FULLTEXT01.pdf · Security has become a hot topic around the world but focuses more on the perime-ter than inside

1 Introduction

1.1 Background

Security has become a hot topic around the world, especially in the world of InformationTechnology (IT). Although a lot of focus lies on ensuring security at the perimeter [1] - inother words protecting things from the outside coming in, there is less work concerningsecurity post-infection where attackers have successfully infected a system and has gainedremote access via for example a Remote Access Trojans (RATs). One reason couldbe that it is trickier to separate actions made by legitimate users and those made bymalicious parties. Nonetheless it is as important as protecting the perimeter as it canbe bypassed by various techniques, and not having security measures past the perimeterthus gives the attacker maximum chances of reaching their goal.

PowerShell is a very powerful tool that is increasingly used in cyber-attacks. Itswide scope in usability and interoperability with other tools along with its capability ofrunning in the background makes it favorable for attackers. It also helps to blend intonormal system usage and avoid detection by other security measures such as anti-virussoftware as its built into the Windows operating system (OS).

1.2 Motivation

Directed cyber-attacks has increased lately and has become more and more sophisticated.In some cases, these attacks have resulted in disruptions and damage to cyber-physicalinfrastructure, in other words digital systems controlling physical processes. This isespecially true in the case of attacks directed towards the energy sector and attacks thatare suspected to be funded by governments. These attacks often leverage the fact thatsecurity inside the network is incomplete. This can have disastrous effects, if consideringpower deliverance, since most societal function today are dependent on a steady supplyof electricity. It could possibly even have effects on national security if functions such asmilitary or health care are affected.

1.3 Problem definition

This thesis focuses on securing the existence of PowerShell by monitoring how it is beingused. The goal is to use built-in logging functionality to extract executed commands intoa system that analyzes them and assigns quantitative risk levels based on risk definitionsof PowerShell commands. These risk levels are then to be used as means of detecting badbehavior by the event of surpassing a threshold value. By being detected, attacks areable to be mitigated before they make damage to critical infrastructure. The problem isderived from a performed analysis of major directed cyber-attacks that has been doneagainst the energy sector around the world.

1

Page 14: Monitoring malicious PowerShell usage through log analysis1333165/FULLTEXT01.pdf · Security has become a hot topic around the world but focuses more on the perime-ter than inside

Delimitations

1.4 Delimitations

This thesis does not examine actual malicious PowerShell script executions done againstcorporations because of the lack of access to such a database. It does also not considerbaselines for what constitutes normal behavior around PowerShell usage at a global oreven national level. Even with access to such information, the time required to processit would be too great. Additionally, only a subset of possible PowerShell commands isconsidered in this thesis. The work of examining and defining risks of every commandis to extensive because of the vast amount of possible executions.

1.5 Thesis structure

In section 2, related work is presented that describes works of others that has relationswith the work conducted in this thesis.

Section 3 describes the analyses of directed cyber-attacks towards the energy sector. Italso describes the steps taken to conclude that PowerShell is a good point of mitigationto prevent similar attacks.

Section 4 describes the setup used to test attacks against a corporate network aswell as the construction of the attack scenarios used to successfully compromise thisnetwork. It also describes the architecture of the solution, how it operates and aroundwhich attributes it was constructed.

Section 5 displays the results of running the simulated attacks formed in section 4inside an environment where the solution is actively monitoring.

Section 6 delves into details around topics such as the evaluation results formed insection 5, the implementation of the solution, PowerShell and logging capabilities.

Section 7 summarizes the conclusions made of this thesis as well as what future workcan be done to improve the solution.

2 Related Work

2.1 Fileless attacks

In the article Fileless attacks: compromising targets without malware [1] Steve Mansfield-Devine describes how attackers have gone from using capabilities in injected malwareto attack to using built in functionality such as Windows Management Instrumentation(WMI) or PowerShell. He also mentions that attackers use ”tried-and-trusted” methodssuch as application vulnerabilities, environment misconfigurations and social engineeringattacks to gain initial foothold in environments.

People and the security industry are also homed in on malware and how to detect itand not the threat of non-malware attacks which are on the rise and far more successfullyexecuted. One reason for their success rate - he writes - could be the reduced number ofscreenings. Things like sandboxing and reduced privileges does not occur for PowerShellas it does for unknown files. This reduced scrutiny along with the fact that PowerShelloffers the same functionality contributes to the fact that attackers are moving towards

2

Page 15: Monitoring malicious PowerShell usage through log analysis1333165/FULLTEXT01.pdf · Security has become a hot topic around the world but focuses more on the perime-ter than inside

Deep neural networks

non-malware attacks. According to Steve the use of these attacks - that involves recon-naissance and tailored social engineering - usually were conducted by nation-state actorsbut have increasingly become attractive for ordinary cyber-criminals.

He also states that non-malware attacks are more varied and harder to test as com-pared to malware samples by the fact that standardized testing environments are hardto create, and the process of testing requires high levels of skill and knowledge. Samplescan also easily be shared and transferred as information about non-malware attacks isharder to share.

Steve writes that we should shift our attention from what files exist on systems to whatactivities that takes place to identify malicious behavior. Existing Behavioural Host In-trusion Prevention Systems (BHIPSs) which is supposed to make up for the failings ofsignature-based anti-virus tools are inflexible and conservative around behavioral analy-sis since endpoint computers house all kind of user interactions that would be identifiedas malicious.

The way he thinks is to go is something called ”event sharing”, where actions arenot judged in a single point in time but put in context. Things like past events andhistorical re-occurrence are things to take into consideration. This is where machinelearning comes in handy. He also describes a solution in which endpoint devices areless impacted in regard to performance compared to current anti-viruses as all dataprocessing is performed at a remote location and instructions are passed to the endpointdevices when alerts occur.

2.2 Deep neural networks

In the paper Detecting Malicious PowerShell Commands using Deep Neural Networks [2]

Danny Hendler, Shay Kels and Amir Rubin describes their approach to analyzing Pow-erShell commands. They evaluated two types of machine learning detectors - of typesConvolutional Neural Networks (CNNs) and Recurrent Neural Networks - as well asNatural Language Processing (NLP) detectors based on character n-grams and bag-of-words. The end aim was to detect malicious commands based on commands as well asobfuscation methods.

For evaluation and model training they used a dataset totaling 66388 distinct Pow-erShell commands of which 6290 were labeled as malicious. Their detectors worked oncommands in clear-text (as they are inputted). It was shown that every detector gen-erally decreased their success-rate in response to lowered rates of false-positives, whichrequired a trade-off to be found as both rates are equally important. The outcome oftheir evaluation was that the best detection results were given by combining the deeplearning model and natural language processing model that performed best separately -4-CNN and 3-gram - at a false-positive rate lower than 10−3.

Their ensemble detector tested 12004 clean commands and 471 malicious commandswith a success rate of 0.995 and a false-positive rate of 5.831e−4.

3

Page 16: Monitoring malicious PowerShell usage through log analysis1333165/FULLTEXT01.pdf · Security has become a hot topic around the world but focuses more on the perime-ter than inside

LogRhytm SIEM

2.3 LogRhytm SIEM

Greg Foss released a guide in which he described how to setup PowerShell monitoring inthe LogRythm Security Information and Event Management (SIEM) tool.[3] His solutionworks by enabling PowerShell logging via PowerShell profiles, inserting these logs intothe SIEM and configuring it to alert when certain commands are executed.

The solution has some downsides that are of concern. Configuring logging via profilefiles brings with it the need to ensure the integrity of that file in order to maintain thecreation of logs. It is also questionable if not the ”−NoProfile” parameter to PowerShellwill bypass this. Another downside is that the logging enabled by the profile generates avast number of logs since it logs both a starting and stopping event for each command.The solution can also be bypassed quite easily - as Greg Foss even mentions in the paper- by obfuscating the code they execute. This comes from the fact that the commandsthat are alerted upon are the function names of functions in well-known open-sourcePowerShell attack frameworks, which anti-virus vendors already reacts upon (at leastWindows Defender).

2.4 ELK stack threat hunting

Roberto Rodriguez wrote a guide in 2017 where he described how to collect logs fromPowerShell, insert them into the ELK Stack and handle the results.[4] The solutioninvolved enabling logging via Group Policy Object (GPO), mutating the logs in Logstashand in the end visualize all the gathered data in Kibana.

The negative side of this solution is that none of the gathered data is automaticallyanalyzed. Manual analysis of all incoming data must be done in order for threats tobe discovered. This wastes a lot of human resources, especially in the case of highgeneration of data. The detection and response time also become unnecessarily highbecause of this.

3 Theory

3.1 Attacks

The biggest cyber-attacks made towards the energy sector[5] are:

• Slammer

• Stuxnet

• Shamoon

• Energetic Bear

• Black Energy

• Industroyer

4

Page 17: Monitoring malicious PowerShell usage through log analysis1333165/FULLTEXT01.pdf · Security has become a hot topic around the world but focuses more on the perime-ter than inside

Shamoon analysis

Of those six, Slammer and Stuxnet was excluded from evaluation. The reason forthat is that they occurred for ten years ago or more and has not re-emerged in newerinstances.

3.2 Shamoon analysis

Shamoon was an attack that targeted a Saudi Arabian company in 2012 and damaged 30000 systems with a malware called ”Disttrack”.[6] The malware spreads in the networkand is efficient in destroying data and making systems inoperable. Since then, numerousnew variants of this attack have been found up until December 2018.[7]

3.2.1 Infiltration

The attackers used spear phishing via email with a Microsoft Office document (primarilyWord documents) as an attachment.[8] This attachment in turn contained macros thatenabled the malicious document to run two PowerShell scripts. These scripts deployedtools and malware on the compromised machine which in turn is used to study andgather information such as Active Directory (AD) domain name, credentials, networktopology and critical servers. The system access is also used to connect to other systems,escalate privileges and spread the tools and malware to aid information gathering. Theseactions were performed weeks in advance of the actual Disttrack outbreak.

3.2.2 Attack

The Disttrack malware consists of three parts: ”the dropper”, ”communications” and”wiper” components.[6] It spreads to other systems by logging in to remote systems inthe same network segment by using hard-coded credentials and AD domain names thatmost likely were stolen prior to the execution of the malware. Additionally, the malwareis able to download extra applications to the system as well as remotely setting wipingdates.

Dropper The dropper extracts the communications and wiper components from em-bedded resources by reading a specified number of bytes from a given offset and decrypt-ing it with a specified key. Upon logging into remote systems in the step of spreading themalware, the dropper attempts to open the service manager and start the RemoteReg-istry. By doing so the malware tries to disable User Access Control (UAC) by alteringthe registry.

After disabling UAC it copies itself to an executable in the Windows/system32 folderand checks if it has administrator privileges on the system. If it does it creates a serviceto launch itself. If it does not it creates a scheduled task to launch itself 90 seconds fromthe current time for 3 minutes instead of creating a service.

Communications The communications component interacts with a command-and-control (C&C) server using Hyper-Text Transfer Protocol (HTTP) requests. In these

5

Page 18: Monitoring malicious PowerShell usage through log analysis1333165/FULLTEXT01.pdf · Security has become a hot topic around the world but focuses more on the perime-ter than inside

Energetic bear analysis

attacks this module was configured with an Internet Protocol (IP) address not pointingto a C&C server, suggesting that the attackers were uninterested in having remote accessto the systems but instead only wanted to cause damage. In the case of an operationalC&C server the module sends a GET request with parameters indicating running timeof the system, IP address, OS version and keyboard layout. The response of the requestcan be one of two commands: Content of an executable to run on the system or savinga time-stamp to a file on which to start wiping the system.

Wiper The dropper does not install the wiper component until it decides it is time towipe the system. The time-stamp for this decision is either hard-coded or exists in a filethat is created on command from the C&C server. When the dropper decides it is timeto start wiping, it saves the wiper component as an executable in the Windows/system32folder. and immediately launches it.

The wiper starts by extracting a driver from its resource section and installs it bycreating a service. The driver is a commercial product called ”RawDisk” which providesdirect access to files, disks and partitions. With the driver it starts to write to protectedsystem locations such as the master boot record and to partition tables of storage volumes.It also overwrites the local profile folders in C:/Users and all the files therein. Aftercompleting all overwrites it issues a command to force the computer to reboot, afterwhich it can no longer boot because of the overwritten partition tables.

The wiper can be configured to wipe systems in three different ways. It can usea predefined image by overwriting files and partition tables with it. It can also userandom values either to overwrite contents directly with it or use it as a key and overwritecontents with the RC4 stream cipher algorithm.

3.3 Energetic bear analysis

”Energetic Bear”/”Crouching Yeti” is a hacker group which targets many sectors, withthe primary being the industrial and energy sector.[9,10] They have actively been involvedin attacks since 2010.

3.3.1 Infiltration

The attackers make use of three different approaches to infect the victim’s environments.

Spear-phishing The attackers use a malicious XML Data Package (XDP) file whichis actually a Portable Document Format (PDF) file packaged within a Extensible MarkupLanguage (XML) container. This is a known obfuscation method that makes detectionharder. the XDP file contains two files, one is a ”Havex Loader” Dynamic-Link Library(DLL) malware and the other is a Java Archive (JAR) file. It then infects the machineby using a Flash exploit to execute the JAR file and eventually copy the malware untothe system and run it.

6

Page 19: Monitoring malicious PowerShell usage through log analysis1333165/FULLTEXT01.pdf · Security has become a hot topic around the world but focuses more on the perime-ter than inside

Energetic bear analysis

Waterholing The attackers also infect legitimate websites to perform watering holeattacks. One variant is performed by inserting a link into the web page or the JavaScript(JS) file used on the web page. This link initiates a request for an image when the pageloads from a specific IP address. This link then redirects to another link forcing the useof the Server Message Block (SMB) protocol. This way the attacker can extract the IPaddress, user name, AD domain name, and hash of the user’s password from the session.The second approach compromises legitimate websites by making them redirect visitorsto malicious JAR or HyperText Markup Language (HTML) files. These files in turnuses exploits in Java and Internet Explorer (version 7 and 8) to download the ”Havex”malware, the ”Karagany” backdoor and other helper tools onto the victim’s computer.

Software installers The attackers also infect machines by infecting legitimate soft-ware installers of third-party providers. One example is the hijacking of a camera driverby SwissRanger, which was altered to load a malicious ”Sysmain” backdoor DLL file andset the registry to run it on the next startup. Another example is the infection of an in-staller from the company eWon, which is a Belgian producer of Supervisory Control AndData Acquisition (SCADA) systems and industrial network equipment. Their installerwas altered to load the Havex malware onto the system. A third example is that of thecompany MB Connect Line which specializes in remote maintenance of ProgrammableLogic Controller (PLC) systems. Their freely downloadable installer for the softwarembCHECK was compromised.

3.3.2 Attack

Havex Once the systems have been breached by the Havex malware, it begins todownload additional DLL files from C&C centers by hijacking the Windows Explorerprocess to send HTTP requests. The entire DLL files are encoded as text commentsinside the response from the C&C server and are identified by a specific start and endtag. The contents are also usually encrypted and compressed before encoded into theresponse.

The additional malware downloaded have different goals in mind. They are usedfor different purposes, including collecting information about the victim’s system, thevictims file system, other systems in the network or harvesting passwords. All theharvested information is then compressed, encrypted and sent back to the C&C centersby the Havex malware. The identified purposes are:

• OLE for Process Control (OPC) scanning to enumerate and extract informationabout the OPC servers running in the local network.

• Gaining a wide variety of system information including OS information, list of filesand file structure, running processes, internet settings, Basic Input/Ouput System(BIOS) versions and email addresses.

• Stealing contacts by collecting details from local Outlook files.

7

Page 20: Monitoring malicious PowerShell usage through log analysis1333165/FULLTEXT01.pdf · Security has become a hot topic around the world but focuses more on the perime-ter than inside

Black energy analysis

• Stealing passwords by embedding the tool ”BrowserPasswordDecryptor 2.0” whichdecrypts and dumps credentials stored by password managers of various browsers.

• Scanning the local network and looking for hosts listening on ports related toOPC/SCADA software.

Sysmain The Sysmain backdoor is a RAT. It starts by permanently attaching itselfto the system and then begins to gather information. It gathers information regardingrunning processes, files in the file system, default browser, user- and computer namesand network information. At completion it sends this information to its C&C serverand then begins polling the server for further instructions using the HTTP protocol.11 commands make the backdoor able to execute shell commands, launch additionalexecutables or libraries, collect unauthorized data and examine the filesystem. But itcan also be commanded to change cipher keys or delete its traces from the system.

ClientX The ClientX backdoor is a .NET RAT similar to the Sysmain backdoor. Bypolling its C&C servers it receives its next order. In the orders it looks for ”havexhavex”tags which envelops encrypted and encoded data of its next command. It has 13 com-mands which include taking screenshots, updating itself, downloading DLLs, startingexecutables, running shell commands and listing directories. The results of the com-mands are stored in the registry and later posted to the C&C server.

Karagany The Karagany backdoor connects to its C&C servers and waits for com-mands. It is able to download and run executables, load/delete modules, read files,reboot the system, update itself and remove all of its components. It also extracts cre-dentials from the password manager of Internet Explorer and injects a DLL file intoprocesses of web browsers. This DLL listens to outgoing traffic and extracts any authen-tication details sent over unencrypted HTTP.

The known modules of this backdoor are:

• A screenshot module which uses the ”Ducklink CmdCapture” third party freesoftware. Besides saving a screenshot it also logs additional information aroundthe screenshot. This information includes time-stamp of capture, computer name,username, Central Processing Unit (CPU) architecture, OS version, IP address,AD domain name, logon server, desktop details and environmental variables.

• A module for listing documents and other files. It is used for listing files of specificextensions or who have names that includes specific substrings.

3.4 Black energy analysis

In 2015 three power companies where victims of a coordinated cyber-attack which re-sulted in 225 000 customers being without electricity for three hours.[11] These were thefirst publicly acknowledged attacks that resulted in power outages.

8

Page 21: Monitoring malicious PowerShell usage through log analysis1333165/FULLTEXT01.pdf · Security has become a hot topic around the world but focuses more on the perime-ter than inside

Black energy analysis

The attacks were sophisticated and is likely to been carried out by an actor withconsiderable structure and resources at disposal. The attacker demonstrated a variabilityin its methods and tactics to match the different security measures and environments ofthe three companies. Hence Ukrainian government officials claimed that Russian securityservices were behind the attack.

3.4.1 Infiltration

The attacker’s way into the corporate network relied on three components working to-gether. They used variants of the ”BlackEnergy3” malware contained inside manipulatedMicrosoft Office documents distributed by spear phishing via email. The main targetsof the distribution were people working in administration or IT at the companies. Uponopening the documents, a message displayed that asked the users to enable using macros.Upon allowing macros, the BlackEnergy3 malware was installed.

3.4.2 Reconnaissance

Once installed, the malware connected to C&C centers and enabled the attackers tocommunicate with the infected systems and gather information. Then the attackersspent six months harvesting credentials, escalate privileges and move laterally throughthe companies to systemically take over IT systems and ensure persistent access to thenetworks. The attackers however quickly moved away from their vulnerable C&C accessto blending into the victim’s systems as authorized users to further secure their control.

The attackers continued by identifying Virtual Private Network (VPN) connectionsand other means of access into the Industrial Control System (ICS) network and even-tually found their way into network segments where SCADA servers and workstationsexisted. Although not proven, the attackers must have performed reconnaissance ac-tions to discover seriel-to-ethernet devices that interpret commands from the SCADAnetwork to the substation control systems. Each of the three victims all used differentDistribution Management Systems (DMSs) that required the attackers to gather networkinformation specifically around each of those systems.

3.4.3 Attack

The attack was performed primarily by using native means of access into the SCADAsystems and use their Human-Machine Interface (HMI) to take substations offline, butseveral sub-parts of the attack was made to worsen the effect of the entire attack.

A custom written firmware was created for the serial-to-ethernet devices. This firmwarewas uploaded by using existing remote administration tools on operator workstations andwas designed to render the devices inoperable and unrecoverable. Thus, ensuring thatremote commands could not be issued to bring the substations back online.

A customized ”KillDisk” software was also installed throughout the environment tolock out the operators from their systems. On some Windows systems, the softwaremade the systems unbootable by manipulating or deleting the master boot record. Onother systems, the software merely deleted log files and system events.

9

Page 22: Monitoring malicious PowerShell usage through log analysis1333165/FULLTEXT01.pdf · Security has become a hot topic around the world but focuses more on the perime-ter than inside

Industroyer analysis

One of the victims also had a Uninterruptible Power Supply (UPS) that was reconfig-ured in such a way that when the attack caused the power outage, the UPS would failand impact the power in the company’s buildings or data centers.

Finally, the attackers also issued a Denial-of-Service (DoS) attack on the company’stelephonic call center. The goal was first seen as keeping customers from relaying in-formation of the extensiveness of the outage to the companies but was later changed tocausing frustration among the customers for not being able to reach customer supportor gain clarity regarding the outage.

It is highly likely that this attack was developed and tested in the attacker’s ownenvironments prior to the actual attack. The multitude of stages in the attack and theprofessionalism in executing them indicates that the attacker’s capabilities and customcode were evaluated before actually used. To efficiently interact with the three differentDMS, the attackers also had to study and evaluate the systems individually.

3.5 Industroyer analysis

Figure 1: Industroyer overview

”Industroyer” is a malware specifically designed to target electric power systems. Itis suspected to be used in the cyber-attack on Ukrainian grid operators in 2016.[12] Itis notable that this malware does not infect embedded industrial equipment, it infectsWindows machines in SCADA environments and substations that has access to critical

10

Page 23: Monitoring malicious PowerShell usage through log analysis1333165/FULLTEXT01.pdf · Security has become a hot topic around the world but focuses more on the perime-ter than inside

Industroyer analysis

devices. The malware itself has no function of reaching such a host on its own. Therefore,initial compromises are required beforehand, such as phishing attacks followed by lateralmovement inside the network from other vectors.[13]

3.5.1 Structure

The overview of the structure of the malware can be seen in figure 1.

Main backdoor The core component in the malware is the ”Main backdoor”. Itconnects to a C&C center via Hyper-Text Transfer Protocol Secure (HTTPS) to receiveinstructions from the attacker. Most of the servers it connects to uses Tor software.

Once the attacker gets a hold of administrator privileges, they are able to update theMain backdoor into a version with higher privileges running as a Windows service. Itdoes so by hijacking registries of an already existing non-critical service.

Additional backdoor The ”Additional backdoor” is a backup solution for cases wherethe Main backdoor is detected or/and disabled. It is a trojan inserted into the WindowsNotepad application. Once the attacker has administrator privileges it replaces theoriginal Notepad with the infected version. Every time the infected application starts,it contacts a C&C center different from the original one. Other than that, the Notepadapplication remains fully functional.

Launcher component This component is a separate executable. It contains a specifictime stamp that once reached launches two separate threads. The first thread will try toload a payload DLL file and configuration file supplied by a parameter when the attackerlaunches the executable. The second thread will launch the ”Data wiper” componentafter one or two hours.

101 payload This payload partly implements the protocol IEC 101 for monitoringand controlling electric power systems. The configuration file identifies a process namethat this component tries to terminate on the running machine. This process is theapplication the attacker suspects to be the one communicating with the Remote TerminalUnit (RTU). The file also contains names of serial ports which it uses to communicatewith the RTU and maintain its control over it.

104 payload This payload leverages the IEC 104 protocol that extends IEC 101 withTransmission Control Protocol (TCP)/IP capabilities. The configuration file of thispayload is highly configurable and contains multiple entries of ”STATION ”. Each entrylaunches a separate thread in which actions described within the entry takes place, whichincludes terminating a given process, start communicating with the given IP address ona given port.

11

Page 24: Monitoring malicious PowerShell usage through log analysis1333165/FULLTEXT01.pdf · Security has become a hot topic around the world but focuses more on the perime-ter than inside

Choice of PowerShell

61850 payload This payload - unlike the previous payloads - is a standalone exe-cutable. It implements a subset of the IEC 61850 protocol used to perform protection,automation, metering, monitoring and control of electrical substation automation sys-tems. It begins by reading its configuration file in order to obtain a list of IP addressesit will try and communicate with. The payload then manipulates the targets switchesand breakers with the use of Manufacturing Message Specification (MMS) commands.

OPC DA payload This payload implements a client for the OPC Data Access (OPCDA) protocol. OPC is a standard based on Microsoft technologies such as Object Link-ing and Embedding (OLE), Component Object Model (COM) and Distributed COM(DCOM) where OPC DA enables real-time data exchange between distributed com-ponents in a client-server fashion. This payload is standalone with an executable anda DLL file. It requires no configuration file because it enumerates all OPC servers andtries to change the state of OPC items therein.

Additional tools Additional tools included in this malware is a custom-made portscanner that can scan defined ranges of IP addresses and ports. Another tool is a DoStool that targets Siemens SIPROTEC devices, rendering them unresponsive.

Data wiper This component is used in the final stage of the attack. It manipulatesthe registries for all windows services, making the system unbootable. Next it scans theentire system and partially rewrites file with selected extensions. The extensions includeWindows binaries, archives, backup files, Structured Query Language (SQL) server filesand various configuration files. Finally, it tries to terminate all processes (includingsystem processes) except for its own, which will leave the system unresponsive andeventually crashing.

3.6 Choice of PowerShell

From the description of the attacks in sections 3.2, 3.3, 3.4 and 3.5 the combined attacktree for all attacks depicted in appendix A formed.

Examining the attack tree leads to the conclusion that there exist two domains inwhich all of these attacks have in common that can be directly targeted to render themunsuccessful. The domains are malware installation and communication with C&C cen-ters. Both of these however is highly difficult to control. Malware installation is donethrough exploits and obfuscations that is ever changing and even big security companieshave trouble mitigating. Communication with C&C centers is also done with differ-ent obfuscation methods and shifting endpoint addresses, making it hard to detect andblock.

The best approach is a mix of infection spreading and malware installation directly oncritical infrastructure. The reason being that the attackers are at their most vulnerableduring the infection spreading. The lateral movement within the network is mostlyperformed by individuals and not automated malware since anti-virus software are quitesuccessful at detecting and stopping it.[14] Secondly the attacker must be creative to

12

Page 25: Monitoring malicious PowerShell usage through log analysis1333165/FULLTEXT01.pdf · Security has become a hot topic around the world but focuses more on the perime-ter than inside

PowerShell

gather information and take control over the network without being compromised butseen as a legitimate user in the network. Since attackers do not have control over theother systems in the network they must perform more traditional methods of scanning,stealing credentials and other means of gaining more control in the network and findingthe critical infrastructure. This makes the attackers vulnerable as they are more visibledoing this and it takes longer time. This puts higher odds on succeeding the mitigationat this stage than any other. The mitigation of malware installation is required tocompletely remove all routes to the compromise of critical infrastructure.

To minimize the risks of being compromised and being removed before gaining afoothold in the network, attackers tend to ”live of the land” or in other words performnon-malware attacks. That is why PowerShell was chosen as the tool used by the sim-ulated attacker. Not only is PowerShell a very powerful tool in skilled hands, but it isalso delivered as a part of the Windows OS and already proven to be widely used incyber-attacks as Steve Mansfield-Devine mentions.[1]

3.7 PowerShell

3.7.1 Logging capabilities

There are three different logging options for PowerShell that can be enabled via GPO.

Module Logging enables log creations in the Windows ”Event Center” at the ex-ecution of PowerShell cmdlets. The term ”Module logging” comes from the fact thatPowerShell has a setup of modules that consists of predefined functions called cmdlets.Some modules are built in and some can be dynamically loaded into PowerShell at timeof need. Modules can also be created and loaded into PowerShell by normal users, wherea .PSM1 file is created that contains the code for the module cmdlets.

The logs created by this option contains the executed command along with all param-eters passed to it in clear-text.

Script Block Logging enables the logging of script blocks in the Windows ”EventCenter” as they are processed by PowerShell. Running a script would lead to the contentof the script being logged. If the logged script in turn launches another script, that scriptwould be subsequently logged.

Transcription logging logs records of every PowerShell session locally on the com-puters file system. The logged content is essentially what would be visible through theCommand Line Interface (CLI) if the execution was made through it, in other wordswhat was inputted, and the result written back to the user.

3.8 Elastic stack

The Elastic stack is a collection of open-source solutions designed to collect, analyze andvisualize data. It is made available on a freemium business model, meaning that it is

13

Page 26: Monitoring malicious PowerShell usage through log analysis1333165/FULLTEXT01.pdf · Security has become a hot topic around the world but focuses more on the perime-ter than inside

Active Directory Domain Services (AD DS)

free to download and use but requires a license for certain features such as integratedmachine-learning analytic tools. It contains four solutions designed to not only integratewith each other but with many other applications.

Elasticsearch is a RESTful distributed search engine built on top of Apache Luceneand released under an Apache license. It is Java-based and can search and index docu-ment files in diverse formats.

Logstash is a data collection engine that unifies data from disparate sources, enrichesit, transforms it and distributes it. The product was originally optimized for log databut has expanded the scope to take data from all possible sources.

Kibana is an open source data visualization and exploration tool that is specialized forlarge volumes of streaming and real-time data. The software makes huge and complexdata streams more easily and quickly understandable through graphic representation.

Beats are “data shippers” that are installed on servers as agents used to send differenttypes of operational data to Elasticsearch either directly or through Logstash, where thedata might be enhanced or archived. There are seven different types of Beats, one being”Winlogbeat” that extracts logs from ”Windows event center”.

3.9 Active Directory Domain Services (AD DS)

Active Directory (AD) has been renamed to Active Directory Domain Services (AD DS)following the launch of Windows Server 2008, at which time the directory service becamea server service among other services.

Through Active Directory Domain Services (AD DS) you can create a scalable, secureand manageable infrastructure for users and for resource management. One can alsobenefit from directory-prepared applications such as Microsoft Exchange Server.

The AD DS server role means that a distributed database stores and manages in-formation about network resources and application-specific data. Administrators canuse ADDS to organize users, computers and other hardware into a hierarchical con-tainer structure. The hierarchy facilitates delegation of permissions and facilitates thehandling of large amounts of information.

AD DS can be used to simplify access and publication of resources using Role-BasedAccess Control. The basic idea is that new members/resources are made to membersin predefined roles. The membership of these predefined roles is also managed by otherpredefined administrative roles. This can ultimately mean, for example for a new user,it becomes a member of an institutional role that gives access to the user’s file area,common file area, provides computer settings, installs applications, installs print queues,and provides security settings.

This minimizes the work involved in managing new users/resources and gives greatercontrol over the environment, both for administrators and operators.

14

Page 27: Monitoring malicious PowerShell usage through log analysis1333165/FULLTEXT01.pdf · Security has become a hot topic around the world but focuses more on the perime-ter than inside

4. IMPLEMENTATION

It is also possible to provide settings/applications to devices other than Microsoft-based, for example. Linux, Android, iOS and Macintosh.

3.9.1 Group Policy Object (GPO)

a Group Policy Object (GPO) is a collection of settings that define what a system willlook like and how it will behave for a defined group of users. The GPO is associatedwith selected AD containers, such as sites, domains, or organizational units. GPOs canbe created that defines registry-based polices, security options, software installation andmaintenance options, scripts options, and folder redirection options.

3.9.2 Domain Controller (DC)

a AD Domain Controller (DC) is the server in the network that runs AD DS and is thusresponsible for authenticating users, storing user information and enforcing the securitypolicies of the AD domain.

4 Implementation

4.1 Testing

4.1.1 Test-bed

Figure 2: Test-bed used for vulnerability evaluation

The test bed used for evaluating the vulnerability of PowerShell exploitation is depictedin figure 2. It was constructed as a typical partial setup of a corporate network involvingoffice clients as well as critical servers.

15

Page 28: Monitoring malicious PowerShell usage through log analysis1333165/FULLTEXT01.pdf · Security has become a hot topic around the world but focuses more on the perime-ter than inside

Testing

The colored arrows depict the ability for traffic to flow by restrictions of Virtual LocalArea Networks (VLANs) and firewall rules. All arrow groupings equal traffic withoutany restrictions except for the green arrow which the firewall limited to Remote DesktopProtocol (RDP) traffic against ”Jump server” by filtering on port 3389.

The two greyed areas represent virtual environments. As such there were two separatevirtual environments hosting the servers in the test-bed.

The laptop used was a physical HP ProBook 6570b with the latest drivers and BIOSversion. The OS running on it was Windows 10 1803. The laptop had two ways ofconnecting to the network, either by ethernet or a wireless access point over an Wi-FiProtected Access (WPA)2 Enterprise connection. The anti-virus run on the client wasthe built in Windows Defender.

All the virtual servers were running Windows Server 2016 version 1607. Both the ADdomain controllers started with the default implementation of the AD DS along withthe addition of two users each, one administrator account and one normal user account,all with different credentials. The first-tier DC (the one on the right in figure 2) houseda custom GPO to map a network drive on the laptop to a local folder on the DC.

The firewall used was a pfSense 2.4.4 running on FreeBSD.

4.1.2 Test tools

Table 4.1.2 shows the PowerShell commands considered during testing along with thesecurity risk they posed and why attackers might have used them. All the commandsare ordered in regard of potential execution order, going from local commands that areless visible to commands that are more visible by example network connections.

Table 1: Malicious PowerShell scripts

ID(Appendix)

Security risk

1 (C.1)

Finding OS, OS version, organization name, language, ADDC server name, processor, BIOS version, AD domain name,installed hotfixes, network cards, IP address, Media AccessControl (MAC) address, Dynamic Host ConfigurationProtocol (DHCP) settings, computer name

2 (C.2)Prints local user accounts. Can be used to find out names oflocal administrator accounts.

3 (C.3)Prints AD domain username and group memberships. Can beused to find out what permissions the current account has.

4 (C.4)Prints previously logged in users. Can be used to get a betteridea of who uses the machine.

16

Page 29: Monitoring malicious PowerShell usage through log analysis1333165/FULLTEXT01.pdf · Security has become a hot topic around the world but focuses more on the perime-ter than inside

Testing

ID(Appendix)

Security risk

5 (C.5)Prints local administrator account information. Can be usedto find out if the local admin account is active, when it lastlogged on, what its password policy is, and more.

6 (C.6)Prints password policy information for local accounts. Can beused to help brute forcing unnoticed.

7 (C.7)Prints local groups and their members. Can be used to get anunderstanding of what local accounts there are and whatpermissions they have.

8 (C.8)Prints the configured Domain Name System (DNS) servers.Can be used to locate internal DNS servers without scanningthe network.

9 (C.9)Finds files with the word password in their content. Can findclear-text passwords that help advance the attack.

10 (C.10) Finds files in which clear-text passwords usually may reside.

11 (C.11)Finds registries containing the word password or are known tocontain clear-text passwords. Can find passwords that helpadvance the attack.

12 (C.12)Finds config files in development codebases. These filesnormally contain passwords that can help advance the attack.

13 (C.13)Prints stored Wireless Local Area Network (WLAN)passwords from saved connections.

14 (C.14)Prints installed programs and packages. Can help findprograms that are exploitable to help advance the attack.

15 (C.15)Prints system processes/services. Gives a better picture ofhow the machine is used.

16 (C.16)Prints processes running as system. Aids in finding processesexploitable for privilege escalation.

17 (C.17)Prints the version of PowerShell. Gives knowledge of whatfeatures PowerShell has and thus what is possible to executeand not.

18 (C.18) Prints scheduled tasks

19 (C.19) Prints programs run at startup

20 (C.20)Prints file permissions for service executables. Can be used tolocate executables that can be replaced and run at a higherprivilege level.

17

Page 30: Monitoring malicious PowerShell usage through log analysis1333165/FULLTEXT01.pdf · Security has become a hot topic around the world but focuses more on the perime-ter than inside

Testing

ID(Appendix)

Security risk

21 (C.21)

Finds services with unquoted pathnames. Can be used tolocate services that can help gain privilege escalation byexploiting how the function CreateProcess interpretspathnames.

22 (C.22)Checks if MSI packages installed by users are installed underelevated privileges. Can be used to package own malwarescripts as a MSI package to run scripts elevated.

23 (C.23)Installs a MSI silently without user interaction. Can be usedto escalate privileges after script 22 returns true.

24 (C.24)Disables the real-time monitoring of Windows Defender. Canbe used to bypass malware detection when using/downloadingmalicious tools. Requires administrator privileges.

25 (C.25)

Prints hosts previously connected to through RDP along withsaved credentials. Can be used to find normal RDPdestinations for the infected user without scanning thenetwork as well as pivoting through the network with normalpatterns without the need for brute forcing.

26 (C.26)Prints all mapped network drives and their network locations.Can be used to locate file servers and potentially sharedfolders to spread infections via infected files.

27 (C.27)

Finds all Uniform Resource Locators (URLs) and intranet IPaddresses that web-browsers have cached content from. Canbe used to locate ip-addresses of internal web-services withoutscanning for them.

28 (C.28)

Extracts collections of URLs, usernames and passwords thathave been saved by Chrome. Can be used to find credentialsfor AD domain accounts, alternatively passwords of otheraccounts to try brute forcing AD domain accounts.

29 (C.29)

Extracts collections of URLs, usernames and passwords thathave been saved by Edge or Internet Explorer in theirpassword manager. Can be used to find credentials for ADdomain accounts, alternatively passwords of other accounts totry brute forcing AD domain accounts.

30 (C.30)Looks up the usernames of all users in the AD domain. Canbe used to locate high privilege account names or accountnames in general to look for in results of other scripts.

18

Page 31: Monitoring malicious PowerShell usage through log analysis1333165/FULLTEXT01.pdf · Security has become a hot topic around the world but focuses more on the perime-ter than inside

Attack Simulation Scenarios

ID(Appendix)

Security risk

31 (C.31)Looks up DNS results with host-names within a networksubnet. Can be used to find out ip-addresses and names ofhosts alive on a subnet.

32 (C.32)Searches for addresses in subnet responding to ping. Can beused to find ip-addresses of running hosts in a subnet.

33 (C.33)Scans a host for a range of ports. Can be used to find outwhat applications or protocols a certain host uses and thus itsnature.

34 (C.34)Scans a whole subnet for a specific port. Can be used tosearch for hosts running specific applications or using specificprotocols.

35 (C.35)

used for web scraping static HTML page contents of a websitereachable through link chains from the root. Can be used toextract information from internal websites only accessible tocorporate users.

36 (C.36)Opens a remote PowerShell session towards the target server.Can be used to pivot into the network unnoticed and executePowerShell commands on other systems.

37 (C.37)Tests if a given AD domain username and password matches.Can be used in brute force attacks.

38 (C.38)

Returns a timestamp of the last successful login of theaccount. Can be used in brute force attacks to know when theconsecutive failed login attempts have been reset in order toavoid account lockouts.

39 (C.39)Returns the description fields of all AD domain users. Couldbe used to search for users where the corresponding passwordis written in the description field

40 (C.40)Returns group membership of users. Could be used to searchfor users in a particular group or the groups a compromiseduser is a member of.

4.2 Attack Simulation Scenarios

To enable evaluation of any type of solution, testing scenarios had to be implementedthat mimics real attacks.

As described in section 3.2, 3.3 and 3.4, one common denominator in the infection

19

Page 32: Monitoring malicious PowerShell usage through log analysis1333165/FULLTEXT01.pdf · Security has become a hot topic around the world but focuses more on the perime-ter than inside

Attack Simulation Scenarios

Listing 1: PowerShell logon script

i f (−Not ( Test−Path ”$env : appdata\Microso f t \Windows\ Star t Menu\Programs\Startup \WindowsShell . lnk ” −PathType Leaf ) )

{copy ”$env : l o g o n s e r v e r \SYSVOL\StupidKeylogger−a p p l i c a t i o n \

WindowsShell . exe ” $env : appdata$copy ”$env : l o g o n s e r v e r \SYSVOL\StupidKeylogger−a p p l i c a t i o n \

WindowsShell . lnk ” ”$env : appdata\Microso f t \Windows\ Star tMenu\Programs\Startup ”

s t a r t ”” ”$env : appdata\Microso f t \Windows\ Star t Menu\Programs\Startup \WindowsShell . lnk ”

}

methods used by the examined attacks is spear fishing. That means that the attackershave researched the organization prior to the infection to locate targets of high value,meaning targets whose device and accounts yield higher levels of access and permissionsin the network. As such the premise is taken that the simulated attacks have successfullyinfected a high privilege user with an unnoticeable C&C malware. In this case this useris the one having the permission to connect to the jump server by RDP. As also describedin the sections 3.2, 3.3 and 3.4; the step following gaining access to critical infrastructureis the deployment of automated software to do damage. Thus, the assumption is alsomade that when access is gained to the SCADA server, the battle is lost.

The premise for the goal of the scenarios is however successfully taking over the firsttier AD DS. As seen in the test-bed (figure 2), the attackers have not at that stage foundtheir way into the critical infrastructure, another AD environment outside their controlis in the way. This however is no major problem since the devices connecting into thatenvironment resides in the AD domain they control. There is a wide variety of waysfor attackers to gain access into the next AD domain. The procedure tested and provenhere is the injection of a keylogger on all computers by a GPO.

Step one was to inject ”StupidKeylogger”[15] into the shared SYSVOL folder of the ADdomain controller. This action has two advantages. Firstly, this folder replicates betweenAD domain controllers which makes it easier in environments of multiple controllers tofind the files from the user computers. Secondly this folder is used for sharing of groupor user policy information without user interaction, making actions in it less likely to bediscovered.

Step two was to inject the logon PowerShell script in listing 1 as well as the logoffPowerShell script in listing 2 into a GPO. The choice of GPO is arbitrary. The moreGPOs to choose from the better since it lessens the probability of the alterations tobe discovered by chance. The one requirement is that it has as broad appliance in theenvironment as possible.

This approach also required two more alterations to the GPO. The anti-virus runningon the endpoints - Windows Defender - blocked and removed the keylogger initially, as

20

Page 33: Monitoring malicious PowerShell usage through log analysis1333165/FULLTEXT01.pdf · Security has become a hot topic around the world but focuses more on the perime-ter than inside

Attack Simulation Scenarios

Listing 2: PowerShell logoff script

copy ”$env : appdata\Record . l og ””\\DCExt\Publ ic$ \Record−$env : computername−$env : username . l og ”

it should. Luckily Defender is also manageable through GPO. By setting the keys ”Turnon behavior monitoring” and ”Monitor file and program activity on your computer” in”Computer Configurations\Administrative Templates\Windows Components\WindowsDefender\Real-time Protection\” to disabled, the keylogger was left unnoticed by De-fender without Defender making any sign at all to the user that functions had beendisabled. The logoff script in listing 2 pushes the collected data by the keylogger to amapped network drive located on the DC, but could as easily be rewritten to push thedata for example by File Transfer Protocol (FTP) to a remote server to minimize thevisibility of malicious activity.

As just described, attackers can quite easily find users that accesses servers in theuncontrolled AD domain and steal the credentials from them in order to delve deeperinto the network if they gain control of the first-tier AD DS. Since the credentials ofeveryone accessing the jump server can be sniffed and all such users normally reside inthe first-tier AD domain, full access is achieved despite eventual access controls in thesecond-tier AD DS.

The following test scenarios thus works from these premises and work towards the goalof gaining control of the first-tier AD DS through PowerShell on the laptop, executingcommands in user-context. All scenarios are executed in a non-malware attack fashion,meaning that they for example do not exploit bugs to gain access to the AD DS butconnects ”legally” with administrative credentials found in different ways.

4.2.1 Local files

This scenario involves searching local files for credentials. There are many local files thatmay contain credentials other than those written manually by users. Configuration filesor source-code for applications are two examples of such files.

After running script 9 in table 4.1.2, the attackers found credentials saved in a localXML file. By running script 37 and 40 they confirmed that the found credential wherefor a AD domain administrator privileged account.

Once the attackers got control of a AD domain administrator account, script 36 en-abled them to open a PowerShell remote session towards the logon server found by script1. At this point the attackers has full access to the organizations AD DS and most likelystarts by injecting their own administrator account into the AD domain userbase.

4.2.2 MSI packages

In this scenario the attacker is able to gain administrator privileges by running scriptswith a MSI package wrapper. This behavior for MSI packages can be enabled by settings.One reason for it may be to allow users to install applications that require administrative

21

Page 34: Monitoring malicious PowerShell usage through log analysis1333165/FULLTEXT01.pdf · Security has become a hot topic around the world but focuses more on the perime-ter than inside

Solution

permissions, without the administrator being required to handout local administratoraccounts or manually approve each installation.

First the attackers run script 22 from table 4.1.2 which returns indications that MSIpackages are automatically installed under elevated forms. Then they run their maliciousscript wrappers through script 23 to gain administrator privileges.

At this point the attackers can choose from a variety of ways to go forward. Forexample, they can now run modules of Mimikatz, Metasploit or Powersploit that requireselevated privileges in PowerShell. In this case the attackers continue with the sameapproach described in the beginning of section 4.2. By running script 24 they disablethe real-time monitoring of Windows Defender and then continue by running a keyloggerdownloaded via the RAT (not through PowerShell). The attackers can then sit back andawait the collection of AD domain administrator credentials that they later use in script36 to take control over the AD DS as described in section 4.2.1.

4.2.3 Saved browser credentials

This scenario searches for credentials saved by browsers internal password vaults. Allmodern browsers have the functionality of saving used credentials for sites. These cre-dentials are also synced between machines, making all credentials saved by users acces-sible regardless of location as long as the same browser was used. These credentials areencrypted based on user-context, making them secure for outsiders but accessible forapplications running under the same user-context.

By running script 14 in table 4.1.2 the attackers find that the user has Google Chromeinstalled. They then continue by running script 28 and 29 (since Microsoft Edge is in-stalled per default in Windows 10) to gain all saved credentials in the two browsers.Unfortunately, the user had saved credentials for an internal administrative web appli-cation which used Remote Authentication Dial-In User Service (RADIUS) (or somethingsimilar) for authentication via AD domain users.

Since script 28 and 29 both yields credentials and the site URL/IP address thatthey were saved for, intranet sites are easily distinguished from other globally accessiblewebsites. Besides that, there is also a high chance for the username of administratoraccounts to contain the word admin, meaning that it is feasible in this case to argue thatscript 37 and 40 only needed to be run once in order for attackers to ensure the findingsof administrator credentials.

The continuance of this scenario involves running script 36 with the found credentialsto take control over the AD as described in section 4.2.1.

4.3 Solution

The solution to mitigate the malicious possibilities of PowerShell was chosen to be mon-itoring and analyzing logs from Windows ”Event center”. As opposed to using machinelearning to detect maliciousness in clear-text commands as Danny, Shay and Amir did,[2]

the chosen approach is to let built-in functionality in the Windows OS aid in the de-obfuscation of commands, thus making analyzing easier.

22

Page 35: Monitoring malicious PowerShell usage through log analysis1333165/FULLTEXT01.pdf · Security has become a hot topic around the world but focuses more on the perime-ter than inside

Solution

Windows have several built-in logging options for monitoring the executions of com-mands on machines, all with their strengths and weaknesses which can be read about insection 6.4.1.

4.3.1 Prerequisites

To be able to monitor and analyze logs, one must first enable the creation of these logson the Windows machine. This was done with the aid of GPOs. The GPOs that wasenabled can be seen in table 4.3.1. The result of this activation is Module Logging logsfrom all modules (see section 3.7.1) as well as logs describing the creation of processes.The latter is used to monitor usage of administrative executables such as ”ipconfig.exe”.

Table 2: enabled GPOs for PowerShell logging

ID PathParameter(if needed)

1Computer Configuration\AdministrativeTemplates\Windows Components\WindowsPowerShell\Turn on Module Logging

*

2Computer Configuration\AdministrativeTemplates\System\Audit Process Creation\Includecommand line in process creation events

3Computer Configuration\Windows Settings\SecuritySettings\Advanced Audit Policy Configuration\AuditPolicies\Detailed Tracking\Audit Process Creation

Success

4.3.2 System Overview

The solution set up was composed of several components. Most of these components arefrom ”The Elastic Stack”.[16] The Implementation can be seen in figure 3 which depictsthe layout of the test-bed with the implemented solution.

23

Page 36: Monitoring malicious PowerShell usage through log analysis1333165/FULLTEXT01.pdf · Security has become a hot topic around the world but focuses more on the perime-ter than inside

Solution

Figure 3: Test-bed with implemented solution

A new Windows server was added to the test-bed named ”ELK”. It housed most ofthe components used from The Elastic Stack - Logstash, Elasticsearch and Kibana. Italso housed ”ESPSA” (Elastic Stack PowerShell Analyzer) - a custom designed programwritten in C Sharp (C#). A variant of Beats called ”Winlogbeat” was installed on theclient (the laptop) as well.

The work-flow between all these components can be seen in figure 4 and a descriptionof each step is listed below:

1. Beats reads logs from Windows Event Log and forwards them to Logstash.

2. Logstash processes the logs by extracting and structuring wanted data and remov-ing unnecessary data. It then forwards the processed logs to ESPSA.

3. ESPSA analyzes the incoming logs and assigns to them a risk-value calculated byfactors around which command was executed and in what context it was executed.It then forwards the evaluated logs along with their risk-value back to Logstash.

4. Logstash forwards the evaluated logs into Elasticsearch.

5. Kibana makes queries to Elasticsearch based on its user-defined configuration.

6. Elasticsearch returns the data queried for, after which Kibana uses it to createvisualizations.

24

Page 37: Monitoring malicious PowerShell usage through log analysis1333165/FULLTEXT01.pdf · Security has become a hot topic around the world but focuses more on the perime-ter than inside

Solution

Figure 4: Process flow between solution components

4.3.3 Beats

The Winlogbeat client installed on the laptop as seen in figure 3 was responsible forcollecting certain types of logs that Windows creates and forward them to Logstash.The configuration file for Winlogbeat can be seen in appendix E.1.1.

The client searches for two kinds of event logs, those with an ID of 800 and thosewith an ID of 4688. 800 is an operational log of PowerShell and contains informationaround module execution. This type of log is the result of enabling GPO 1 in table 4.3.1.An example log can be seen in appendix F.1 generated by executing the PowerShellcommand ’Get−LocalGroupMember −Name ”Administrators”’. The Winlogbeat clientsends all generated logs of this type to Logstash encoded as JavaScript Object Notation(JSON).

4688 is an audit event for creating new processes on the machine and is enabled byGPO 3 in table 4.3.1. Enabling GPO 2 enriches these logs by appending the commandline issued for creating this process. An example log can be seen in appendix F.2 gener-ated by executing the command ’ipconfig’. These types of logs are filtered before sentto Logstash. The Winlogbeat client only sends those which describes processes createdby the application powershell.exe or cmd.exe.

4.3.4 Logstash

Logstash was responsible for handling log entries incoming both from Winlogbeat clientsbut also from ESPSA. It had several configuration files: pipelines.yml, PsPre.conf,PsPost.conf and powershell.rb, which can be found in appendix E.2.1, E.2.2, E.2.3,and E.2.4 respectively. It also has a configuration file called logstash.yml which waskept unaltered from installation defaults.

The configuration files told Logstash to run two pipelines in parallel. One whichdirectly forwarded input from ESPSA by TCP into Elasticsearch by HTTP and onewhich mutated the logs from Beats prior to forwarding them into ESPSA by TCP. The

25

Page 38: Monitoring malicious PowerShell usage through log analysis1333165/FULLTEXT01.pdf · Security has become a hot topic around the world but focuses more on the perime-ter than inside

Solution

Listing 3: Added log structure by Logstash

” power she l l ” = {” scr ipt name ” = ” PsScr ipt . ps1 ” ,” h o s t a p p l i c a t i o n ” = ”C:\Windows\System32\WindowsPowerShell\v1 .0\ power she l l . exe −NoPro f i l e ” ,

”main command” = ”Get−LocalGroup | ForEach−Object { $ ; Get−LocalGroupMember −Group \” $ \”}” ,

” ve r s i o n ” = ”5 . 1 . 17 134 . 590 ” ,”command” = ”Get−LocalGroupMember ” ,” parameters = [

”−Group Admini s t rators ”]

}

mutating pipeline was configured by PsPre.conf and handles 800 events and 4688 eventsin different ways since they contain different information’s in different structures. In theend they both resulted in added structure to the root of the log JSON object that wasvital for the goal of the solution. The added structure contained what command wasrun, what parameters it had, the application running the command along with additionalparameters to the application and lastly the name of the script-file the command wasrun from. An example of the resulting structure can be seen in listing 3. The mutatingpipeline was also responsible for aggregating event logs of type 800, this due to theexistence of limitations on the size of logs that resulted in splitting if exceeded.

Before it forwarded logs to ESPSA, it removed unwanted fields from it, like the onesused to extract vital information. Logstash also drops logs of executions that is explicitlydefined to be dropped. This was done merely to early cut out harmless commands thatalso tended to generate a lot of data.

4.3.5 Elasticsearch

Elasticsearch acted as the database for all incoming logs and was kept as close to defaultconfigurations as possible. The configuration file for it - elasticsearch.yml in appendixE.3.1 - was only altered to enable communications with Kibana.

4.3.6 Kibana

Kibana was the visualization tool used to visualize queries on the data stored in Elas-ticsearch. It too was kept as close to default configuration as possible. Its configurationfile kibana.yml in appendix E.4.1 only contains a connection string to Elasticsearch. Thegoal of using Kibana was the creation of a dashboard containing a single line chart. Thisline chart was set to query for the maximum risk-value of inserted logs by ESPSA inrelation to the time-stamps on the logs. This way, high numbers of log sources could be

26

Page 39: Monitoring malicious PowerShell usage through log analysis1333165/FULLTEXT01.pdf · Security has become a hot topic around the world but focuses more on the perime-ter than inside

Solution

visualized in a single chart. An increase in the risk-value displayed in the graph wouldthen indicate that at least one machine was at risk.

4.3.7 ESPSA

4.3.7.1 Overview

The ESPSA software was composed mainly by four components, the data flow betweenthem is depicted in figure 5. The ”TCP Reader” is responsible for reading incomingdata and parse it into JSON formatted logs that it then forwards. The ”Aggregator”accepts the incoming logs and accumulates them for a while before forwarding them in achronological order, the reason for this is described in section 4.3.7.4. The ”Processor”is the module that does the actual log analysis. In the end it stamps the logs with aquantitative risk value based on various contexts and circumstances before passing italong. The ”TCP Sender” is the last module in the line and is essentially the oppositeof the sender in the beginning. It takes JSON logs that it sends out to defined targetsover TCP.

Figure 5: Process flow between ESPSA components

4.3.7.2 Architecture

ESPSA was built in C# around two major principles: modularity and fault tolerance.The reason for that is that ESPSA is dependent upon many systems. It communicateswith both Logstash and Elasticsearch, beyond that it also handles logs generated by

27

Page 40: Monitoring malicious PowerShell usage through log analysis1333165/FULLTEXT01.pdf · Security has become a hot topic around the world but focuses more on the perime-ter than inside

Solution

PowerShell and Windows that are enhanced by Beats. All these dependencies existin different versions and may even exist in multiple versions in the same environment(mainly Windows and PowerShell). In such a case it is preferable to be able to en-able/disable and tweak modules to fit the requirements of the environment in which it isoperating. It also improves the dynamic of the system as it makes it easier to enhance byonly needing to make new modules and ensure the security of that new module insteadof the entire program.

Fault tolerance is critical for this kind of software. Its purpose is to analyze logs at ahigh pace from a high number of systems in an environment. Any exceptions occurringduring execution must be properly handled, otherwise the program will crash. Eventhough Logstash buffers logs in its outgoing queue, the potential high flow of logs canquickly result in this buffer overflowing even in the case of direct detection of failureby IT-personnel. Detecting a crash of the program is not that easy either, unless theenvironment produces a steady flow of logs continually, one cannot differentiate a crashfrom a ”calm” period since the only consequence of a crash is the lack of input intoElasticsearch.

The modularity of the program is constructed in three different ways, the main pro-gram modules - as seen in figure 5 - are connected by blocking First In First Out(FIFO) queues, meaning that modules with the same ”connectors” can be easily insert-ed/removed from the process flow. These queues also work to improve the performanceof the program. Every main module is run in parallel and when a queue is empty, themodule requesting data from it will be blocked until data becomes available. Thus, con-suming no resources when unable to perform any work. The second way that modularitywas introduces was to separate internal services that any module used by dependencyinjection. As seen in appendix B, self-contained services such as network operations orerror logging is conceptualized through interfaces. This means that behavior can bealtered by simply changing a parameter to a module. For instance, error logging canbe changed from writing to a local text file to populating a database without needingto change any behavior of the module itself. One need only construct the different im-plementations of the interface and control what object is injected into the module viasettings. The last implementation of modularity involves log handling. Different partsof the program need to acquire information contained within the log object, and since itis a JSON object, this access must be done dynamically. The problem with this is thatthe structure of the log may evolve over time, requiring a more dynamic approach toenable this access. Therefore, access to log information is done via dependency injectionof anonymous functions that handles this access.

Fault tolerance was constructed in two different ways. One was to make sure that nounhandled exceptions occurred and by taking the fastest way out of an exception. Forinstance, when an incoming log is unable to be parsed into a JSON object, the log issimply dropped instead of undergoing any salvage operation. This approach is to keepthe program as fast and simple as possible - less complexity means less probability forunhandled failures. The second way to increase fault tolerance is also a complement tothe first tactic. Any major exception is error logged, including the log content if theoperation that failed was tied to it. These logs are supposed to serve as a basis for future

28

Page 41: Monitoring malicious PowerShell usage through log analysis1333165/FULLTEXT01.pdf · Security has become a hot topic around the world but focuses more on the perime-ter than inside

Solution

improvement of the program or the entire system.

4.3.7.3 TCP Reader/TCP Sender

The responsibilities for the reader and sender are quite straightforward. They act asthe bridge between incoming data and the program as well as between the program andoutgoing data. They are prefixed by ”TCP” simply because of the use of TCP in thetested solution, but since the actual reading of data is abstracted by an interface, anysource and means can be used, including parsing of local files.

The reader and sender both have the limitation that JSON objects that are read andwritten are separated by a new-line character. This comes from the fact that any meansof communication composed of a continually opened channel needs a delimiter of somesort. This is also true for any other thinkable interface that returns batches of objects.It is however also acceptable to have batches composed of one single object.

The reader and sender differ on one account. The reader accepts incoming data, try toparse it into a JSON object and then passing it along to the Aggregator if successfullyparsed, throwing it away otherwise. The sender however has a different approach, akind of extra fault tolerance for connectivity issues. It accepts JSON objects from theProcessor and deserializes it into a byte array and then tries to push it through theinterface of the connectivity service. If unsuccessful, the sender will try to reconnectthrough the service and try again. If unsuccessful the second try, the sender will log theerror and return the log to the back of the sending queue populated by the processor.This way there will be no loss of data in the case of temporary outage of for examplenetwork connectivity.

4.3.7.4 Aggregator

The Aggregator exist only for enabling compatibility with Logstash. ESPSA requireslogs to be processed in a chronological order to ensure correct analytic results. Logstashhowever cannot guarantee this when delivering the logs. Thus, it becomes the responsi-bility of the Aggregator to perform this task.

The Aggregator makes use of a central class called RetentionCollection which doesmost of the work. It is a collection that holds logs and can be told to extract andreturn logs that has an execution time-stamp above a certain age. The Aggregatorthus both accepts logs from the TCP Reader and inserts them into this collection, butalso periodically extracts logs of a certain age and forwards them to the processor ina chronological order. This enables unordered incoming logs to ”catch up” and bereordered into their correct position before being processed.

4.3.7.5 Processor

The Processor is the heart of the program and is responsible for the actual analysis andenhancement of logs. It has as well as the Aggregator one major class that does the mostof its work, the RiskCalculator. The Processor’s analysis of logs includes originating fromthe result of the previous log of the current source, meaning that it must be able to fetch

29

Page 42: Monitoring malicious PowerShell usage through log analysis1333165/FULLTEXT01.pdf · Security has become a hot topic around the world but focuses more on the perime-ter than inside

Solution

the last processed log for sources it encounters. Thus, the Processor has two levels ofcaches, which implementation is free of choice by means of abstraction via interface.In this case however the first level cache was local memory and the second level was aclient connection to Elasticsearch. There is a distinction between the first and secondlevel cache. Beyond checking the first level cache for specific entries before checking thesecond level, the Processor only maintains the first, meaning that the Processor insertsanalyzed logs into the first level cache for future needs but never into the second levelcache. If both caches would come up empty, the Processor would assume that the currentlog is the absolute first for this source and skip the attribution of the past log to theanalysis.

Risk Calculator The Risk Calculator is responsible for the actual analysis of the logand coming up with a quantitative number of the security risk the current log imposes.It calculates the new risk value as a ”base risk value” gained from the class RiskLookupmultiplied by a factor given by the time of day of the execution. It then sums this valuewith a degradation of the risk value from the previous log. The equation used is:

yc =yp

2tpch

+ a(tc) ∗ r(bc) (1)

Where:

yc: is the risk value to be assigned the log

yp: is the risk value assigned to the previous log

tpc: is the hours between the current and previous log

h: is the configured half-life of risk values in hours

a(tc): is the Akima interpolation of the time-stamp of the log

r(bc): is the base risk of the PowerShell content of the log

The time-of-day factor a(tc) used in equation 1 was calculated through an Akima CubicSpline interpolation. The reason for choosing this solution is that it enables a dynamicsetting of working hours and still maintain the same ”appearance” of the graph. In thiscase the wanted ”appearance” was a factor of 1 during work hours with quite a rapidincrease to 2 after hours followed by an increase to 3 just before the starting hour anda rapid decrease to 1 again. Figure 6 shows a graph of an example interpolation withworking hours between 8 and 17.

30

Page 43: Monitoring malicious PowerShell usage through log analysis1333165/FULLTEXT01.pdf · Security has become a hot topic around the world but focuses more on the perime-ter than inside

Solution

Figure 6: Example graph of Akima Cubic Spline Interpolation for time riskfactoring with working hours between 8 and 17

RiskLookup This class is responsible for calculating the risk values that the Power-Shell content in logs pose entirely on their own. It uses a local JSON configuration fileto make a dictionary of configurations capable of calculating risks in a custom manner.Each command can be configured with a base risk value and an arbitrary set of extra riskvalues that are added to the base risk based on criterions. The only supported criteriais regex queries performed on the command parameters. One can define an array ofqueries or a single query per criteria, regardless they must all be evaluated true for theextra risk value to be applied. Each query is tested against all parameters for a match.The complete set of criterions are all expressed in the file CommandRiskMappings.json.

The risk values gained from custom evaluation is later also magnified based on certainstatic criterions. Three factors are taken in consideration and they all revolve aroundthe presence of certain parameters to the PowerShell application. -EncodedCommandobfuscates scripts into base64 encoding and can be used to bypass detection, -NoProfileexcludes PowerShell profiles from loading during execution and can be used to ensurethat no unknown setting interferes with the execution, -WindowStyle Hidden hides theapplication window and can be used to run scripts unnoticed.

4.3.7.6 Command risks

To assign risk values to incoming execution logs there must be definitions of what mali-cious commands looks like. Two parameters that would affect the potential maliciousnessof an execution is the probability of benign execution and the security risk the commandcould pose. Following this idea, commands along with possible arguments where assigneda risk value according to the function

31

Page 44: Monitoring malicious PowerShell usage through log analysis1333165/FULLTEXT01.pdf · Security has become a hot topic around the world but focuses more on the perime-ter than inside

Solution

rc = 10 ∗ ropl

(2)

Where:

rc: is the risk value to be assigned the command and potential argument on a scaleof 0 to 100

pl: is the possibility for execution by legitimate users on a scale of 1 to 10

ro: is the security risk of the outcome/information that the command gives on ascale of 0 to 10

Table 4.3.7.6 displays the assignment of risks of all commands identified from appendixC. Each command has one or several regex parameter queries that adds its defined riskvalue to the total risk value every time evaluated true on a parameter. Every query is alsochecked against all parameters for matches. The first parameter regex of every commandin the table containing a single asterisk defines the base risk value that command hasregardless of parameters.

Table 3: PowerShell command risk assignments

Command Parameter regex pl ro rc

Get−LocalGroup * 7 2 2.85

Get−LocalGroupMember

* 7 2 2.85

−Group[ \”]∗(A|a)dmin 7 4 5.70

Get−ChildItem

* 10 2 2

−Path.∗\\Startup 5 4 12.50

−Path.∗C:\\Users 7 2 2.85

−Path.∗Program Files 7 3 4.29

−Force.∗True 7 3 4.29

−Include.∗web.config 2 7 25.00

−Path.∗Registry::.∗Software 5 4 8.00

Get−WmiObject

* 6 3 5.00

Win32 Product 5 3 6.00

Win32 Process 4 3 7.50

Win32 Service 4 6 15.00

32

Page 45: Monitoring malicious PowerShell usage through log analysis1333165/FULLTEXT01.pdf · Security has become a hot topic around the world but focuses more on the perime-ter than inside

Solution

Command Parameter regex pl ro rc

Get−Service * 4 6 15.00

Get−ScheduledTask * 5 5 10.00

Get−PSDrive * 7 7 10.00

Get−Process * 4 3 7.50

Select−String

* 9 2 2.22

−Path.∗Firefox\\Profiles 1 10 100

−Path.∗Chrome\\User Data 1 10 100

Invoke−WebRequest* 3 8 26.67

−UseDefaultCredentials 2 9 45.00

ConvertTo−SecureString

* 5 3 6

−AsPlainText True 4 4 10.00

Invoke−Expression * 3 8 26.67

Start−Sleep * 2 1 5.00

New−Object

* 8 0 0

−ArgumentList.∗Chrome\\User Data 1 10 100

−TypeName.∗Windows\.Security\.Credentials\.PasswordVault

1 10 100

−TypeName.∗Net\.Networkinformation\.Ping

2 4 20.00

−TypeName.∗Net\.Sockets\.TcpClient 2 5 25.00

−TypeName.∗DirectoryServices\.DirectoryEntry

2 8 40.00

−TypeName.∗Security\.Cryptography 2 8 40.00

−TypeName.∗Automation\.PSCredential

7 5 7.14

Where−Object

* 8 0 0

−FilterScript.∗−notlike.∗svchost 2 4 20.00

−FilterScript.∗−notlike.∗Microsoft 2 4 20.00

−FilterScript.∗−notlike.∗Windows 2 4 20.00

−FilterScript.∗−eq.∗Auto 6 4 6.67

Enter−PSSession * 2 10 50.00

33

Page 46: Monitoring malicious PowerShell usage through log analysis1333165/FULLTEXT01.pdf · Security has become a hot topic around the world but focuses more on the perime-ter than inside

Solution

Command Parameter regex pl ro rc

Set−MpPreference* 1 9 90

−DisableRealtimeMonitoring True 1 10 100

Get−ItemProperty* 10 2 2

−Path.∗Windows\\CurrentVersion\\Uninstall

5 4 8

systeminfo * 6 4 6.67

ipconfig* 10 2 2.00

/all 8 3 3.75

reg

* 9 2 2.22

ˆ/s$ 8 6 7.50

query 9 2 2.22

password 3 8 26.67

Currentversion\\Winlogon 6 4 6.67

Services\\SNMP 4 6 15.00

PuTTY 2 8 40.00

RealVNC\\WinVNC4 3 6 20.00

PowerShellEngine 3 3 10.00

Windows.∗Run 5 4 12.50

AlwaysInstallElevated 3 7 23.33

Terminal Server Client 3 3 10.00

net

* 10 1 1.00

user 7 3 4.29

accounts 7 3 4.29

Administrator 5 5 10.00

start 4 3 7.50

whoami* 8 2 2.50

/all 6 3 5.00

34

Page 47: Monitoring malicious PowerShell usage through log analysis1333165/FULLTEXT01.pdf · Security has become a hot topic around the world but focuses more on the perime-ter than inside

Solution

Command Parameter regex pl ro rc

findstr

* 10 1 1.00

ˆ/.∗s 9 1 1.11

ˆ/.∗ i 9 1 1.11

\.xml$ 7 3 4.29

\. ini$ 5 5 10.00

\.config$ 7 5 7.14

password 3 8 26.67

system32 3 6 12.00

binary path name 2 8 40.00

service name 2 5 25.00

SSID Cipher Content 1 10 100

dir

* 10 2 2.00

pass 3 8 26.67

cred 3 8 26.67

\.xml 7 3 4.29

\. ini 5 5 10.00

\. config 7 5 7.14

vnc 3 8 26.67

Startup 5 4 12.50

tasklist* 4 3 7.50

eq system 3 6 12.00

netsh* 6 3 5.00

wlan 4 3 7.50

sc

* 4 6 15.00

query 4 6 15.00

ˆqc 2 8 40.00

msiexec

* 6 3 5.00

/quiet 6 6 10.00

/qn 3 6 20.00

35

Page 48: Monitoring malicious PowerShell usage through log analysis1333165/FULLTEXT01.pdf · Security has become a hot topic around the world but focuses more on the perime-ter than inside

5. EVALUATION

Command Parameter regex pl ro rc

wmic

* 8 2 4.37

service 4 6 15.00

startup 5 4 12.50

schtasks* 8 3 3.75

ˆ/query 5 5 10.00

icacls * 3 7 23.33

nslookup* 10 1 1.00

ˆ172\\.(1[6−9]|2[0−9]|3[01])|ˆ10\\.|ˆ192\\.168\\. 6 3 5.00

ping* 10 1 1.00

ˆ172\\.(1[6−9]|2[0−9]|3[01])|ˆ10\\.|ˆ192\\.168\\. 10 3 3.00

5 Evaluation

To evaluate the solution, the scenarios described in section 4.2.1, 4.2.2 and 4.2.3 wasrun in a test-bed setup as pictured in figure 3. The risk configurations of ESPSA wasassigned as described in table 4.3.7.6. The commands of each scenario were run manuallyand sequentially in the order they are described in each respective section. All execu-tion was done during daytime (configured working hours in ESPSA) directly inputtedinto a PowerShell session window. The upper limit threshold for categorizing maliciousbehavior was 100 as was the basis for the risk assignment equation 2 used.

5.1 Local files

This evaluation was done on the scenario described in section 4.2.1 where clear textcredentials are found in local files. In this evaluation the username admin and passwordpass123 was found in a local XML file. The infected computer lied in the AD domainExternal.TestBed.se with a login controller named DCEXT. Table 5.1 displays the datarelating to the simulation and PowerShell that where inserted into Elasticsearch duringthe simulation in a chronological fashion.

36

Page 49: Monitoring malicious PowerShell usage through log analysis1333165/FULLTEXT01.pdf · Security has become a hot topic around the world but focuses more on the perime-ter than inside

MSI packages

Table 4: Outcome of simulation - Local files

Command Parameter(s)Riskvalue

findstr

/si

51.32

password

∗.xml

∗. ini

∗.txt

∗. config

New−Object

−TypeName System.DirectoryServices.DirectoryEntry 91.30

−ArgumentList LDAP://DC=External,DC=TestBed,DC=se, admin, pass123

systeminfo 97.90

ConvertTo−SecureString

−AsPlainText True

113.86−Force True

−String pass123

New−Object

−TypeName System.Management.Automation.PSCredential 121.00

−ArgumentList admin, System.Security.SecureString

Enter−PSSession−ComputerName DCEXT

171.00−Credential System.Management.Automation.PSCredential

5.2 MSI packages

This evaluation was done on the scenario described in section 4.2.2 where a settingenabling installation of MSI packages to run with elevated privileges automatically isexploited. The script wrapper run to enable PowerShell execution that disables Win-dows Defender was C:\evil.msi. The later found credentials of the keylogger was theusername admin and password pass123. The infected computer lied in the AD domainExternal.TestBed.se with a login controller named DCEXT. Table 5.2 displays the datarelating to the simulation and PowerShell that where inserted into Elasticsearch during

37

Page 50: Monitoring malicious PowerShell usage through log analysis1333165/FULLTEXT01.pdf · Security has become a hot topic around the world but focuses more on the perime-ter than inside

MSI packages

the simulation in a chronological fashion.

Table 5: Outcome of simulation - MSI packages

Command Parameter(s)Riskvalue

reg

query

27.77HKLM\\SOFTWARE\\Policies\\Microsoft\\Windows\\Installer

/v

AlwaysInstallElevated

reg

query

55.53HKCU\\SOFTWARE\\Policies\\Microsoft\\Windows\\Installer

/v

AlwaysInstallElevated

msiexec

∗ /quiet

90.51/qn

/i

C:\\evil .msi

Set−MpPreference

−DisableRealtimeMonitoring True

280.48−QuarantinePurgeItemsAfterDelay 0

−ReportingAdditionalActionTimeOut 0

...

New−Object

−TypeName System.DirectoryServices.DirectoryEntry 320.36

−ArgumentList LDAP://DC=External,DC=TestBed,DC=se, admin, pass123

systeminfo 326.79

ConvertTo−SecureString

−AsPlainText True

342.66−Force True

−String pass123

38

Page 51: Monitoring malicious PowerShell usage through log analysis1333165/FULLTEXT01.pdf · Security has become a hot topic around the world but focuses more on the perime-ter than inside

Saved browser credentials

Command Parameter(s)Riskvalue

New−Object

−TypeName System.Management.Automation.PSCredential 349.80

−ArgumentList admin, System.Security.SecureString

Enter−PSSession−ComputerName DCEXT

399.80−Credential System.Management.Automation.PSCredential

5.3 Saved browser credentials

This evaluation was done on the scenario described in section 4.2.3 where stored creden-tials of browsers are extracted. The found AD domain credentials stored by the browsersfor the logged in user Test was the username admin and password pass123. The infectedcomputer lied in the AD domain External.TestBed.se with a login controller namedDCEXT. Table 5.3 displays the data relating to the simulation and PowerShell thatwhere inserted into Elasticsearch during the simulation in a chronological fashion.

Table 6: Outcome of simulation - Saved browser credentials

Command Parameter(s)Riskvalue

Get−ItemProperty−Path HKLM:\\Software\\Wow6432Node\\Microsoft\\Windows\\CurrentVersion\\Uninstall\\∗

10.00

New−Object

−ArgumentList C:\\Users\\Test\\AppData\\Local\\Google\\Chrome\\User Data\\Default\\Login Data, Open,Read, ReadWrite

115.00

−TypeName IO.FileStream

New−Object

−ArgumentList System.IO.FileStream,System.Text.Latin1Encoding 125.00

−TypeName IO.StreamReader

New−Object−TypeName Windows.Security.Credentials.PasswordVault

224.94

39

Page 52: Monitoring malicious PowerShell usage through log analysis1333165/FULLTEXT01.pdf · Security has become a hot topic around the world but focuses more on the perime-ter than inside

6. DISCUSSION

Command Parameter(s)Riskvalue

New−Object

−TypeName System.DirectoryServices.DirectoryEntry 264.84

−ArgumentList LDAP://DC=External,DC=TestBed,DC=se, admin, pass123

systeminfo 271.29

ConvertTo−SecureString

−AsPlainText True

287.17−Force True

−String pass123

New−Object

−TypeName System.Management.Automation.PSCredential 294.31

−ArgumentList admin, System.Security.SecureString

Enter−PSSession−ComputerName DCEXT

344.30−Credential System.Management.Automation.PSCredential

6 Discussion

6.1 Evaluation results

As seen in table 5.1, 5.2 and 5.3, each of the run scenarios would result in a warningindication for observing parties since they exceed the value of 100. This is however onlycertain for the exact executions simulated. Alternative executions could very well leavea vulnerability exploitable without exceeding the threshold. The fact that all scenariosend with the same approach to reach the AD DC is what makes all the scenarios exceedthe threshold.

Looking at table 5.1 describing the simulation of clear text passwords in local files, ifthe attackers would choose an alternative way to reach the AD DC - a way not involvingPowerShell execution - the final risk value after the attackers ensured the findings ofAD domain administrator credentials would be 97.90. The same is true for the risk ofelevated installation of MSI packages described in table 5.2. If the attackers installed amalicious MSI package that does not involve running PowerShell (or maybe circumventsthe logging), the final risk value would stop at 90.51.

This shows that for this approach to be successful, one cannot solely rely on the fact ofautomatically logging the usage of PowerShell. An active effort must be made to ensure

40

Page 53: Monitoring malicious PowerShell usage through log analysis1333165/FULLTEXT01.pdf · Security has become a hot topic around the world but focuses more on the perime-ter than inside

Assigned risk values

minimal existence of vulnerabilities in systems exploitable via PowerShell. That wayattackers that use PowerShell will probe for vulnerabilities and in the meantime runningup the total risk value for the infected system. Beside heightening the probability forcatching infections, it would also heighten the probability for mitigating infections beforeany damage or spreading has been done.

6.2 Assigned risk values

The definition of risk assignment displayed in table4.3.7.6 can be questioned for theircorrectness or questioned for the actual existence of correct values for that matter.Equation 2 used in the assignment of risk values (rc) has the parameters of probabilityfor benign execution (pl) and security risks of execution (ro) for the reason of minimizingfalse positives. The used values of these parameters when calculating risk values ishowever not derived from research or polls. The security risks of commands are morecertain as they are derived from the output or actions that commands result in. Theprobabilities for benign execution however are uncertain as trustworthy estimates wouldrequire insight in real world usage of PowerShell. These parameters surely also fluctuategoing from environment to environment, making assignments that are globally accuratevery difficult if not impossible.

There is a possibility that more accurate numbers could be found by enhancing theequation used. There is a possibility of additional parameters having impact on the riskvalue that could be introduced. One improvement quite clearly present is the parametersimpact on the risk value. As can be seen in figure 7, the higher risk values are quitecentralized at the extremes (high values of ro and low values of pl). The equation shouldbe remade so the spike in its graph have a ”straighter” descent towards the center ofthe graph, giving higher risk values for parameters pl < 5 and ro > 5. How the optimalequation graph should look like is debatable and left outside the scope of this thesis.

41

Page 54: Monitoring malicious PowerShell usage through log analysis1333165/FULLTEXT01.pdf · Security has become a hot topic around the world but focuses more on the perime-ter than inside

Browser security

Figure 7: 3D plot of equation 2

6.3 Browser security

The existence and simplicity of the commands used to extract credentials from browsersin the scenario described in section 4.2.3 raises some questions around the security ofbrowsers. It is however not that they lack security, but how security is implemented. Allpasswords that are stored by the browsers are indeed encrypted, making them secure ifsomeone would steal your hard-drive. It is the fact that they are encrypted by Windowsfunctionality that uses user context that is problematic. This implies that the onlyrequisite to decrypt the credentials is to be logged in as the correct user, which isfulfilled when having RATs operating in user context. This vulnerability is not reducedby the fact that these password managers synchronize credentials over systems, makingall credentials ever saved accessible regardless of what system they were saved on.

6.4 PowerShell

6.4.1 Logging capabilities

Module Logging The strength of Module logging is that it logs every call to a cmdletwith all parameters in clear text. This means that it is very easy to see exactly whatcommands has been executed. It also proves useful in the cases of loops, pipelines,conditionals and variable usage since a mere view of the script content would not tellyou what commands was run, how many times they were run or what parameters theywere run with. It is also very resilient to obfuscation methods. For example, it is possibleto run scripts by downloading text from the internet into a variable and then pass thisvariable to a function that would interpret the text as a script and run it. This scenariowould leave a script file view alternative totally blind as nothing can be seen about

42

Page 55: Monitoring malicious PowerShell usage through log analysis1333165/FULLTEXT01.pdf · Security has become a hot topic around the world but focuses more on the perime-ter than inside

PowerShell

the content of the script executed. Module logging however would still log every singlecmdlet execution inside this obfuscation method. Module logging also ignores aliasesthat exists for cmdlets. Meaning that aliases and case-sensitivity can be ignored whichgreatly simplifies the effort needed to analyze.

The downside of Module logging is that it only logs cmdlets. Many malicious scriptsmake quite extensive use of .NET Framework functions and classes, which Module log-ging logs nothing about. This means that an enlightened attacker who knows about thepresence of Module logging could potentially make scripts that run without logging asingle bit of information during its execution since the .NET Framework is so widelyapplicable to all sorts of dilemmas.

Script Block Logging This logging is also very resilient to obfuscation methods as itlogs scripts as they are passed to the PowerShell engine, as all scripts must be if anythingis to be executed. It also has the benefit of having the entire script written out in cleartext, meaning that all types of operations are visible no matter what type. One couldalso argue that the visibility of conditional branches not executed is beneficial.

The downside of Script Block Logging is where Module logging is strong, there isno way of getting the details of executions of conditional branches or inside loops orpipelines. The usage of variables also leaves uncertainty of what exactly has been ex-ecuted. Unlike Module logging you also must deal with case-sensitivity and aliases forcommands.

Transcription logging Can be useful since it logs everything exactly as it appearsin the console window, both input and output. The downside of it is that it thus logsnothing about the content of script files executed, or output that is written to the filesystem.

6.4.2 Choice of enabled GPOs

The choice of enabled GPOs can be seen in table 4.3.1. The result of enabling thesewas to gain visibility into both PowerShell cmdlet invocations as well as invocations ofsystem executables such as ipconfig.exe. In the case of the executables, some filtering wasnecessary since the GPOs enables logging of every process creation. The only processcreations of interest were the ones that had been created by PowerShell. Those createdby cmd.exe was also included to increase the scope of visibility and to cope with the factthat Command Line executions could be fired by PowerShell as well. The positive aspectof these GPOs is that everything is written out in a straight forward fashion, meaningthat the load on the solution is lowered since little resources is needed to extract theinformation needed from the logs.

Unfortunately, the findings of the negative aspects of Module logging described insection 6.4.1 was found to late. The choice for Module logging was made on the premisethat it logged executions of all functions, including those in .NET Framework. The factthat it does not leaves a very big security hole in the solution. One consideration is if it isnot more beneficial to change direction towards Script Block logging and analysis of script

43

Page 56: Monitoring malicious PowerShell usage through log analysis1333165/FULLTEXT01.pdf · Security has become a hot topic around the world but focuses more on the perime-ter than inside

PowerShell

content. One loses the preciseness of executions, but the inclusion of .NET Frameworkexecutions may be more valuable. One could counter that loss with generalizations andrisk assessments of reused results of commands whether it is via variables or pipelinesas well as finding malicious execution paths in the regard of conditional branching. Oneconcern for that approach is the efficiency diminishing of ESPSA since it absolutely willaffect it negatively. Another concern is the management of aliases for commands thatexists.

One other aspect is that PowerShell is under constant development. There is a possi-bility that the logging capabilities will change in the future, for the better or the worse.Would the Module logging be enhanced to include all types of executions including staticfunctions and class methods, then Module logging would be far more superior than ScriptBlock logging in the aspect of automated PowerShell execution analysis.

6.4.3 Other defences

6.4.3.1 ExecutionPolicy

One of the built-in defenses in PowerShell is ExecutionPolicy. It can be set via GPO andoffers settable restrictions on the execution of script files and loading of configurationfiles. The possible values are:[17]

AllSigned: Requires that all scripts and configuration files are signed by a trustedpublisher, including scripts written on the local computer.

Bypass: Nothing is blocked and there are no warnings or prompts.

Default: Sets the default execution policy. Restricted for Windows clients orRemoteSigned for Windows servers.

RemoteSigned: Requires that all scripts and configuration files downloaded fromthe Internet are signed by a trusted publisher. The default execution policy forWindows server computers.

Restricted: Does not load configuration files or run scripts. The default executionpolicy Windows client computers.

Undefined: No execution policy is set for the scope. Removes an assigned execu-tion policy from a scope that is not set by a Group Policy. If the execution policyin all scopes is Undefined, the effective execution policy is Restricted.

Unrestricted: Loads all configuration files and runs all scripts. If you run anunsigned script that was downloaded from the Internet, you are prompted for per-mission before it runs. The default execution policy for non-Windows computersand cannot be changed.

It is however very easy to bypass this kind of restriction. As Sutherland describes,there are at least 15 ways to do it.[18] The one tested and confirmed was to downloadthe script from the internet and running it with the command Invoke-Expression.

44

Page 57: Monitoring malicious PowerShell usage through log analysis1333165/FULLTEXT01.pdf · Security has become a hot topic around the world but focuses more on the perime-ter than inside

PowerShell

6.4.3.2 Disabling PowerShell

There is also the option of completely blocking the execution of PowerShell on machinesvia GPO.[19] The question is if it is such a good idea. If one looks on the premise thatwas made for this solution, the attackers had already exploited a vulnerability to achieveremote system access via a RAT. It is then very likely that attackers have different toolsat their disposal than PowerShell but are much keener on using PowerShell to keep alow profile. To disable PowerShell might thus not yield the desired outcome, it mightjust force the attacker to other means instead of blocking them out. The best approachwould then be to keep PowerShell enabled if an adequate level of monitoring can beachieved.

6.4.4 Monitoring obstacles

PowerShell houses some difficulties and obstacles when dealing with monitoring. First,there exists multiple commands that yield the same result. One example is appendixC.14, where every command returns installed software on a system. There is also aprobability that there exist more commands to do that as well. Every command howeverdoes not completely mimic the others, there are differences between what they return.The overlap between them however is large enough for all of them to be suitable in manyscenarios. This complicates the assurance of visibility in behaviors since covering onecommand is not enough, meaning that all commands must be examined in detail (allpossible parameters) for complete assurance of visibility to be established.

PowerShell also has aliases for commands. One example is that the execution ofthe command gwmi fires an execution of the command Get-WmiObject. This makes itproblematic to configure commands since one does not know if the command configuredis the one which will be run upon execution. The upside is that this problem disappearswhen complete visibility is achieved as described above.

The interoperability of PowerShell is also an issue when trying to monitor its usage.The fact that PowerShell can fire executables and launch Command Prompt (CMD)scripts makes it harder to monitor. Executables and CMD scripts differ quite in structurecompared to PowerShell cmdlets and scripts. Cmdlets have all its parameters namedwhereas executables have flags and distinct orders of its parameters. This means thatthought most be given to parameter appearance and order when judging executions ofexecutables, which differ between most executables. It becomes more problematic withthe fact that some executables completely change their behavior depending on how theyare executed. One example is reg.exe, where the first parameter of query or add changesthe behavior from searching the registry to adding values to it. Another example isfindstr.exe that searches for text within files normally but if placed inside a pipeline cansearch for text within results of other commands.

Another issue occurs with the introduction of Windows Subsystem for Linux (WSL).According to Chris Hoffman it is possible to call Linux bash scripts from within Power-Shell just as CMD scripts are.[20] This adds yet another source of commands and possibleexploits to the pool that needs to be examined. Chris also writes about the mutual ac-

45

Page 58: Monitoring malicious PowerShell usage through log analysis1333165/FULLTEXT01.pdf · Security has become a hot topic around the world but focuses more on the perime-ter than inside

Elastic Stack

cess between the file-systems of Windows and the Linux subsystem, yielding implicationsregarding monitoring as both file-systems must be considered for both shells.

Additionally, the logging options described in section 6.4.1 have the risk of not beingconsistent. This became clear with Module logging regarding calling executables. If anexecutable was called as a single command, there would be no information logged aboutthe execution. However, if the executable was called as part of a pipeline, the calling ofthe executable would be logged. This behavior is unwanted as it results in a duplicatelog since the calling of executables are fetched from another source. These peculiar casesare hard to find and can cause issues when making themselves known during productiondeployment.

6.5 Elastic Stack

The usage of components from the Elastic Stack in the solution is not vital. Thesecomponents can be replaced by any type of SIEM solution while still maintaining thefunctionality.

The core application in this solution is ESPSA. The Elastic Stack components are onlythere to handle the flow of information to and from it. As such the only needed com-ponent for a minimal functional solution is Beats or a similar product. The extractionof log data from endpoints is not a capability of ESPSA, all the other responsibilitieshowever can be integrated into ESPSA. The log transformations done by Logstash andthe log filtering done by Beats can easily be made an extended responsibility of ESPSA.If historical data and visualizations are unwanted, maybe by wanting ESPSA to onlyissue real-time warnings itself, Elasticsearch and Kibana would also be unnecessary.

6.6 ESPSA

6.6.1 Execution time risk interpolation

The first approach used to be able to calculate the risk factor to be applied consideringtime-of-day aspects of executions was a static equation of the fourth degree. The reasonfor that approach was mere efficiency optimization. A curve was interpolated thatfollowed the one in figure 6 quite well, there was some oscillation around the turningpoints which could affect the result in a negative way.

In the end Akima Cubic Spline was chosen to enable the dynamic choice of workinghours and still maintain the same characteristics of the graph. Other cubic splinesresulted in such oscillations around turning points that made it impossible to even get a”near enough” good value. No efficiency measurements was made on the selected solutionsince no alternative was considered. There is a possibility that it can be improved byconstruction of a simple range check of the value, the chosen curve layout certainly issimple enough for it to be viable. The only negative aspect for such a solution is the lossof ”smoothness” in the curve, which would give a less accurate result right around theturning points. For example, the possibility for executions beyond work hours decreasesincreasingly as time progresses since the odds of people working overtime decreases in

46

Page 59: Monitoring malicious PowerShell usage through log analysis1333165/FULLTEXT01.pdf · Security has become a hot topic around the world but focuses more on the perime-ter than inside

ESPSA

the same manner. Thus, the curve should mirror that and increase in a logarithmicmanner.

6.6.2 Risk half-life

The solution uses the approach of having a logarithmic decrease in risk level as timepasses. This must of course happen one way or another otherwise every system willeventually reach alerting levels. This approach however has some flaws, it does not copevery well with legitimate users running the same commands repeatedly because theyforgot the result. This is extra troublesome since it is very likely that only legitimateusers will behave this way. Malicious users will run commands and then extracts theresults and save them, thus have no need for running the same command again. Thisonly increases the risks for false positives and not the chances of detecting malicioususage.

Another approach would be to have a retention policy for executed commands. Mean-ing that executed commands are saved for a period of time and accounts for the totalrisk level during that period. Another execution of the same command would not countagain and thus eliminating the issue. In other words, one would sum the risks of allunique commands during a running window period as the total risk level. The problemwith this approach however is that it can be quite cumbersome to implement and theimpact on performance is unclear.

6.6.3 Aggregator

The Aggregator in ESPSA is responsible for keeping incoming logs in chronologicalorder. It can however not guarantee this. The aggregation is performed by periodicallyextracting logs of a certain age based on the time-stamp for execution. The probabilityfor correct ordering increases as the chosen age is increased, but one does not want tohave a too high delay between execution and input to Elasticsearch. The risk of havingto low threshold value is that the delay that Beats and Logstash introduces is unknown.Any disruption in communications between Beats and Logstash or between Logstashand ESPSA would also result in logs being buffered. At the time that communicationis resumed, a batch of logs would be transmitted that could directly lie beyond thethreshold value and thus risk incorrect ordering. This could also be true in the case thatsystems experience high loads and therefore lag in the transmission.

An implementation that completely solves this issue may be non-existent. At somepoint the application must take the logs buffered so far and filter them. One possiblesolution would be to check event record ids. Windows enumerates all created logs in anincremental fashion with an integer number that can be used to determine if all logs ina certain range has been delivered. The issue with this id is that it counts per log sourceand not per event type, meaning that in the case of multiple events being written tothe same log source, the ids will have gaps if only one event type is considered. This isthe case for the logs used by this solution, since the logs for launched executables arefiltered.

47

Page 60: Monitoring malicious PowerShell usage through log analysis1333165/FULLTEXT01.pdf · Security has become a hot topic around the world but focuses more on the perime-ter than inside

7. CONCLUSIONS AND FUTURE WORK

6.6.4 Output waste

In the current implementation of the solution there exists a filter inside the ruby scriptpowershell.rb used by Logstash that filters out unwanted commands from logging. Thisshould be moved to ESPSA to centralize the processing and simplify the overall design.In addition, ESPSA should be improved to drop all logs that does not increase thetotal risk level as they are unnecessary, currently ESPSA sends all processed logs toElasticsearch regardless. It should however store all commands that are dropped as itcould be executions that are not configured but should be included. Additionally, itcould be beneficial to store executions that have configured queries but where none wereapplied to gain insight in missing queries for configured commands as well.

7 Conclusions and future work

It is quite possible to ensure security around PowerShell usage with the aid of automaticlog analysis. However, work must be performed around it to be successful. As manyvulnerabilities as possible must be patched on every monitored machine as to maximizethe attackers command invocation rate in case of a breach. Any present vulnerabilitiesmay only require a couple of commands to exploit, which complicates mitigation as itbecomes harder to detect malicious usage and increases damage done or infection spreadup until mitigation.

Much work is needed to gain enough visibility around PowerShell usage because of itsnature. PowerShell has high usability on its own, but the possibility for it to utilize CMD,WSL, .Net Framework and executables makes its scope extremely wide and difficult tocover. Things like multiple suitable commands for the same purpose and commandaliases also aggravates the aim for complete monitoring coverage.

Unfortunately, the logging capabilities of PowerShell are currently flawed. NeitherModule logging or Script Block logging grants a complete insight in the usage of Pow-erShell and even built in security measures of PowerShell are easily sidestepped. Thelogging options also have the tendency to contain inconsistencies in what they log, whichcould lead to unwanted side-effects such as duplicate logging of executions. How the log-ging capabilities will evolve looking forward is also unclear. Newer versions of PowerShellmight improve the overall capabilities, impair it or make one option favorable over theother. Currently the most favorable option is deemed to be Script Block logging in thesense of information given, even if the extraction of this information is more complicatedas it needs an intelligent parser.

7.1 Future work

The solution presented can be improved in many ways. The issues brought up in section6.6 are all points of improvements that can be made to improve the quality and reliabilityof ESPSA. Some of them are improvements of current implementations and some can bemade as alternative features that can be chosen via settings. Section 6.4.2 also brings up

48

Page 61: Monitoring malicious PowerShell usage through log analysis1333165/FULLTEXT01.pdf · Security has become a hot topic around the world but focuses more on the perime-ter than inside

Future work

a possibility for an additional feature, namely a parser and analyzing tool for PowerShellscript blocks.

If looking at the solution, there are some improvements that can be made there aswell to heighten the quality of the solution. In case of a breach the malicious usageof PowerShell may be conducted at night, which gives the attacker much more time toreach their goal than when conducted during working hours. In the worst-case scenario,they begin attacking right after work end and are not mitigated until work begins again.To counter this, some kind of automated response must be introduced. One candidatesolution is some kind of measure - a locally installed client or access control measuresvia example a firewall - that can isolate machines that are conducting malicious usagefrom the rest of the network. The temporary disconnection of systems is surely to preferover risk giving attackers enough time to reach their goal.

One issue that can occur - and that surely becomes enlarged by an implementation ofthe improvement of automation described above - is the risk of false positives. Normalusage can and will at some point result in threshold breaches. As described in the be-ginning of this section, there is also the need for finding and patching vulnerabilities onmachines for this solution to be efficient. This would most likely be done via automatedrunning of scripts that searches and reports its findings. What way can be better tofind vulnerabilities usable through PowerShell than to actually ”ask” PowerShell. Theseautomated scripts would also be counted towards the threshold value and without adoubt pass it by a large margin. This is where Artificial Intelligence (AI) would comein handy. By using it to perform behavior analysis on the risk value, one can makethe system react to the outliers of this analysis instead of on the risk value itself. Thatway both regular running scripts and normal usage can be accounted for and still re-spond to cases where the behavior deviates, thus lessen the risk for false positives. Forthis purpose, the Elastic Stack can prove beneficial since it provides machine learningfunctionality for these types of analyzes in exchange of a license fee.

As described in section 6.2, the risk assessment function must also be improved to givemore accurate values in relation to its parameters. Some method must also be applied toreassure the right values of the parameters of executions if looking at a global appliance.

49

Page 62: Monitoring malicious PowerShell usage through log analysis1333165/FULLTEXT01.pdf · Security has become a hot topic around the world but focuses more on the perime-ter than inside

REFERENCES References

References

[1] Steve Mansfield-Devine, Network Security. Apr2017 2017, 2017, 7–11, DOI 10.

1016/S1353-4858(17)30037-5.

[2] Danny Hendler, Shay Kels, Amir Rubin in Proceedings of the 2018 ACM Asia Con-ference on Computer and Communications Security, May 29, 2018, Association forComputing Machinery, Inc, 2018, pp. 187–197, DOI 10.1145/3196494.3196511.

[3] G. Foss, PowerShell Command Line Logging, 2015, https://logrhythm.com/blog/powershell-command-line-logging/, (accessed: 15.05.2019).

[4] R. Rodriguez, Enabling Enhanced PowerShell logging Shipping Logs to an ELKStack for Threat Hunting, 2017, https://cyberwardog.blogspot.com/2017/06/enabling-enhanced-ps-logging-shipping.html, (accessed: 15.05.2019).

[5] Cybelius, THE 6 BIGGEST CYBERATTACKS AGAINST THE ENERGY IN-DUSTRY, 2017, http://www.cybelius.fr/en/2017/12/19/industrie-

energetique-top-6-des-plus-grandes-cyberattaques/, (accessed: 01.02.2019).

[6] R. Falcone, Shamoon 2: Return of the Disttrack Wiper, 2016, https://unit42.paloaltonetworks.com/unit42-shamoon-2-return-disttrack-wiper/, (ac-cessed: 06.02.2019).

[7] R. Falcone, Shamoon 3 Targets Oil and Gas Organization, 2018, https://unit42.paloaltonetworks.com/shamoon-3-targets-oil-gas-organization/, (ac-cessed: 06.02.2019).

[8] K. Albano, The Full Shamoon: How the Devastating Malware Was Inserted IntoNetworks, 2017, https://securityintelligence.com/the-full-shamoon-how-the-devastating-malware-was-inserted-into-networks/, (accessed:06.02.2019).

[9] K. Lab, Energetic Bear — Crouching Yeti, 2018, https://media.kasperskycontenthub.com/wp-content/uploads/sites/43/2018/03/08080817/EB-YetiJuly2014-

Public.pdf, (accessed: 05.02.2019).

[10] K. Lab, Energetic Bear / Crouching Yeti: attacks on servers, 2018, https://ics-cert.kaspersky.com/reports/2018/04/23/energetic- bear- crouching-

yeti-attacks-on-servers/, (accessed: 05.02.2019).

[11] E-ISAC, Analysis of the Cyber Attack on the Ukrainian Power Grid, 2016, https:/ / ics . sans . org / media / E - ISAC _ SANS _ Ukraine _ DUC _ 5 . pdf, (accessed:04.02.2019).

[12] A. Cherepanov, WIN32/INDUSTROYER, A new threat for industrial control sys-tems, 2017, https://www.welivesecurity.com/wp-content/uploads/2017/06/Win32_Industroyer.pdf, (accessed: 01.02.2019).

[13] E. V. Velzen, Crash Override: What Does The Threat Mean For Utilities?, 2017,https://encs.eu/2017/06/13/crash-override-threat-mean-utilities/,(accessed: 01.02.2019).

50

Page 63: Monitoring malicious PowerShell usage through log analysis1333165/FULLTEXT01.pdf · Security has become a hot topic around the world but focuses more on the perime-ter than inside

References References

[14] W. Williamson, Lateral Movement: When Cyber Attacks Go Sideways, 2016,https://www.securityweek.com/lateral-movement-when-cyber-attacks-

go-sideways, (accessed: 11.02.2019).

[15] M. Kamal, StupidKeylogger, 2017, https://github.com/MinhasKamal/StupidKeylogger,(accessed: 19.03.2019).

[16] E. B.V., The Elastic Stack 7.0, 2019, https://www.elastic.co/products/,(accessed: 24.04.2019).

[17] Microsoft, Set-ExecutionPolicy, 2019, https://docs.microsoft.com/en-us/powershell/module/microsoft.powershell.security/set-executionpolicy?

view=powershell-5.0, (accessed: 14.05.2019).

[18] S. Sutherland, 15 Ways to Bypass the PowerShell Execution Policy, 2014, https://blog.netspi.com/15- ways- to- bypass- the- powershell- execution-

policy/, (accessed: 15.05.2019).

[19] top-password, How to Disable PowerShell with Software Restriction Policies GPO,2018, https://www.top-password.com/blog/disable-powershell-with-software-restriction-policies-gpo/, (accessed: 15.05.2019).

[20] C. Hoffman, Everything You Can Do With Windows 10’s New Bash Shell, 2018,https : / / www . howtogeek . com / 265900 / everything - you - can - do - with -

windows-10s-new-bash-shell/, (accessed: 22.05.2019).

[21] K. Milan, Get-ChromeCreds2.ps1, 2017, https://raw.githubusercontent.com/kerrymilan/Get- ChromeCreds2/master/Get- ChromeCreds2.ps1, (accessed:05.03.2019).

51

Page 64: Monitoring malicious PowerShell usage through log analysis1333165/FULLTEXT01.pdf · Security has become a hot topic around the world but focuses more on the perime-ter than inside

Appendices

A Attack tree

52

Page 65: Monitoring malicious PowerShell usage through log analysis1333165/FULLTEXT01.pdf · Security has become a hot topic around the world but focuses more on the perime-ter than inside

B. ESPSA CLASS DIAGRAM

B ESPSA Class Diagram

53

Page 66: Monitoring malicious PowerShell usage through log analysis1333165/FULLTEXT01.pdf · Security has become a hot topic around the world but focuses more on the perime-ter than inside

C. POWERSHELL COMMANDS

C PowerShell Commands

C.1

sys temin fo

C.2

net user

C.3

whoami / a l l

C.4

Get−ChildItem C:\ Users −Force | s e l e c t Name

C.5

net user <<admin username based on language>>

C.6

net accounts

C.7

Get−LocalGroup | ForEach−Object { $ ; Get−LocalGroupMember −Group ” $ ”}

C.8

i p c o n f i g / a l l

C.9

f i n d s t r / s i password ∗ . xml ∗ . i n i ∗ . tx t ∗ . c o n f i g

C.10

cmd /c ” d i r /S /B ∗pass ∗ . tx t == ∗pass ∗ . xml == ∗pass ∗ . i n i == ∗cred ∗ == ∗vnc∗ == ∗ . c o n f i g ∗”

C.11

54

Page 67: Monitoring malicious PowerShell usage through log analysis1333165/FULLTEXT01.pdf · Security has become a hot topic around the world but focuses more on the perime-ter than inside

REG QUERY HKLM /F ”password” / t REG SZ /S /KREG QUERY HKCU /F ”password” / t REG SZ /S /K

reg query ”HKLM\SOFTWARE\Microso f t \Windows NT\Currentver s ion \Winlogon”

reg query ”HKLM\SYSTEM\Current\Contro lSet \ S e r v i c e s \SNMP”reg query ”HKCU\Software \SimonTatham\PuTTY\ S e s s i o n s ”reg query HKEY LOCAL MACHINE\SOFTWARE\RealVNC\WinVNC4 /v

password

reg query HKLM / f password / t REG SZ / sreg query HKCU / f password / t REG SZ / s

C.12

Get−Childitem −Path C:\ inetpub \ −Inc lude web . c o n f i g −F i l e −Recurse −ErrorAct ion S i l en t l yCont inue

C.13

cmd /c WLAN extract . bat [D.1]

C.14

Get−WmiObject −Class Win32 ProductGet−ChildItem ’C:\Program Fi l e s ’ , ’C:\Program F i l e s ( x86 ) ’ | f t

Parent , Name, LastWriteTimeGet−ChildItem −path Reg i s t ry : : HKEY LOCAL MACHINE\SOFTWARE | f t

NameGet−ItemProperty HKLM:\ Software \Wow6432Node\Microso f t \Windows\

CurrentVers ion \U n i n s t a l l \∗ | Se l e c t−Object DisplayName ,DisplayVers ion , Publ i sher , I n s t a l l D a t e | Format−Table −AutoSize

C.15

t a s k l i s t /vnet s t a r tsc . exe querywmic s e r v i c e l i s t b r i e fGet−S e r v i c eGet−WmiObject −Query ” S e l e c t ∗ from Win32 Process ” | where { $ .

Name −n o t l i k e ” svchost ∗”} | S e l e c t Name, Handle , @{Label=”Owner ” ; Express ion={$ . GetOwner ( ) . User }} | f t −AutoSize

C.16

55

Page 68: Monitoring malicious PowerShell usage through log analysis1333165/FULLTEXT01.pdf · Security has become a hot topic around the world but focuses more on the perime-ter than inside

t a s k l i s t /v / f i ”username eq system”

C.17

REG QUERY ”HKLM\SOFTWARE\Microso f t \PowerShel l \1\PowerShel lEngine ” /v PowerShel lVers ion

C.18

cmd /c ” schta sk s / query / fo LIST 2>nul | f i n d s t r TaskName”Get−ScheduledTask | where { $ . TaskPath −n o t l i k e ”\Microso f t ∗”}| f t TaskName , TaskPath , State

C.19

reg query HKLM\Software \Microso f t \Windows\CurrentVers ion \Rreg query HKCU\Software \Microso f t \Windows\CurrentVers ion \Runreg query HKCU\Software \Microso f t \Windows\CurrentVers ion \

RunOnced i r ”$env :APPDATA\Microso f t \Windows\ Star t Menu\Programs\Startup

”d i r ”C:\ProgramData\Microso f t \Windows\ Star t Menu\Programs\

StartUp”

C.20

$hash = @{}$one = wmic s e r v i c e l i s t f u l l | f i n d s t r / i ”pathname” | f i n d s t r

/ i /v ” system32 ” | % { $t = $ − s p l i t ’= ’ ; $t [ 1 ] }$two = sc . exe query s t a t e=a l l | f i n d s t r ”SERVICE NAME: ” | % { $t

= $ − s p l i t ’ ’ ; $t [ 1 ] } | % { sc . exe qc ” $ ”} | f i n d s t r ”BINARY PATH NAME” | % { $t = $ − s p l i t ” : ” ; $t [ 1 ] }

$one + $two | % { i f ( $ . StartsWith ( ’ ” ’ ) ) { $r = $ − s p l i t ’ ” ’ ;$s = $r [ 1 ] } e l s e { $r = $ − s p l i t ’ ’ ; $s = $r [ 0 ] } $s } | %{ i f (

$hash . $ −eq $ n u l l ) { $ } ; $hash . $ = 1} | % { i c a c l s $ }

C.21

gwmi −c l a s s Win32 Service −Property Name, DisplayName , PathName, StartMode | Where { $ . StartMode −eq ”Auto” −and $ .PathName −n o t l i k e ”C:\Windows∗” −and $ . PathName −n o t l i k e’”∗ ’} | s e l e c t PathName , DisplayName ,Name

C.22

reg query HKLM\SOFTWARE\ P o l i c i e s \Microso f t \Windows\ I n s t a l l e r /vAlways Ins ta l lE l evated

56

Page 69: Monitoring malicious PowerShell usage through log analysis1333165/FULLTEXT01.pdf · Security has become a hot topic around the world but focuses more on the perime-ter than inside

reg query HKCU\SOFTWARE\ P o l i c i e s \Microso f t \Windows\ I n s t a l l e r /vAlways Ins ta l lE l evated

C.23

msiexec / qu i e t /qn / i C:\ e v i l . msi

C.24

Set−MpPreference −DisableRealt imeMonitor ing $true

C.25

REG QUERY ”HKCU\Software \Microso f t \Terminal Server C l i en t \Serve r s ” / s

C.26

Get−PSDrive

C.27

$hash = @{}$ input paths = ”$env : l oca lappdata \Packages\Microso f t .

MicrosoftEdge 8wekyb3d8bbwe\AC\#!001\MicrosoftEdge \Cookies\∗” , ”$env : l oca lappdata \Mozi l l a \Fi r e f ox \ P r o f i l e s \ s3xrny7d .d e f a u l t \ cache2 \ e n t r i e s \∗” , ”$env : l oca lappdata \Google\Chrome\User Data\Defau l t \Cache\data ∗”

$regex = ”\b172 \ .\d{1 , 3}\ . [ 1 6 , 17 , 18 , 19 , 20 , 21 , 22 , 23 , 24 , 25 , 26 , 27 , 28 , 29 , 30 , 31 ]\ .\d{1 ,3}\b | \ b10 \ .\d{1 ,3}\ .\d{1 ,3}\ .\d{1 ,3}\b | \ b192 \ . 1 68\ .\d{1 ,3}\ .\d{1 ,3}\ bhttps ? :\/\/(www\ . ) ?[−a−zA−Z0−9@:%.\+˜#=]{2 ,256}\b”

$ input paths | % { s e l e c t−s t r i n g −Path $ −Pattern $regex −AllMatches | % { $ . Matches } | % { $ . Value } | %{ i f ( $hash .$ −eq $ n u l l ) { $ } ;

$hash . $ = 1}}

C.28

Get-ChromeCreds2.ps1[21]

C.29

[ void ] [ Windows . Secu r i ty . Cr eden t i a l s . PasswordVault , Windows .Secu r i ty . Credent ia l s , ContentType=WindowsRuntime ]

$vau l t = New−Object Windows . Secu r i ty . Cr eden t i a l s . PasswordVault$vau l t . Re t r i ev eA l l ( ) | % { $ . Retr ievePassword ( ) ; $ }

57

Page 70: Monitoring malicious PowerShell usage through log analysis1333165/FULLTEXT01.pdf · Security has become a hot topic around the world but focuses more on the perime-ter than inside

C.30

( [ a d s i s e a r c h e r ] ” objectCategory=User ”) . F inda l l ( ) | ForEach { $ .p r o p e r t i e s . samaccountname}

C.31

1 . . 2 5 4 | % { nslookup ”<<network subnet , eg 192.168.0.>> $ ” } |s e l e c t−s t r i n g ”Name” −Context 0 ,1

C.32

$ping = New−Object System . Net . Networkinformation . Ping1 . . 2 5 4 | % { $ping . send(”<<network subnet , eg 192.168.0.>> $ ”)| s e l e c t address , s t a t u s }

C.33

f unc t i on t e s t p o r t ( $hostname=’yahoo . com ’ , $port =80, $timeout =100){

$reques tCa l lback = $ s t a t e = $ n u l l$ c l i e n t = New−Object System . Net . Sockets . TcpClient$beginConnect = $ c l i e n t . BeginConnect ( $hostname , $port ,$requestCal lback , $ s t a t e )Start−Sleep −m i l l i $timeOuti f ( $ c l i e n t . Connected ) { $open = $true } e l s e { $open =

$ f a l s e }$ c l i e n t . Close ( )[ pscustomobject ]@{hostname=$hostname ; port=$port ; open=$open}

}

<<s t a r t port>>..<<end port>> | % { t e s t p o r t −hostname <<host>> −port $ } | Format−Table −AutoSize

C.34

f unc t i on t e s t p o r t ( $hostname=’yahoo . com ’ , $port =80, $timeout =100){

$reques tCa l lback = $ s t a t e = $ n u l l$ c l i e n t = New−Object System . Net . Sockets . TcpClient$beginConnect = $ c l i e n t . BeginConnect ( $hostname , $port ,$requestCal lback , $ s t a t e )Start−Sleep −m i l l i $timeOuti f ( $ c l i e n t . Connected ) { $open = $true } e l s e { $open =

$ f a l s e }$ c l i e n t . Close ( )

58

Page 71: Monitoring malicious PowerShell usage through log analysis1333165/FULLTEXT01.pdf · Security has become a hot topic around the world but focuses more on the perime-ter than inside

[ pscustomobject ]@{hostname=$hostname ; port=$port ; open=$open}}

1 . . 2 5 4 | % { t e s t p o r t −hostname ”<<network subnet , eg192.168.0.>> $ ” −port <<port>>} | Format−Table −AutoSize

C.35

$hash = @{}$ b a s e u r l = <<host name/ ip>>$ o u t p u t f o l d e r = <<output f o l d e r>>

f unc t i on Scrape ( $ur l ) {Write−Host $ur l$hash . $u r l = 1 ;$ r e s = Invoke−WebRequest −Uri $ur l −

UseDe fau l tCredent ia l s$ r e s | Se l e c t−Object −Expand Content > ( $ o u t p u t f o l d e r

+$ur l . r e p l a c e (”/” ,” ”) + ” . txt ”)$ r e s | Se l e c t−Object −Expand Links | S e l e c t h r e f | %{ i f

( $hash . ( $ b a s e u r l + $ . h r e f ) −eq $ n u l l −And $ . h r e f .StartsWith (”/”) ) { Scrape ( $ b a s e u r l + $ . h r e f ) }}

}

Scrape $ b a s e u r l

C.36

f unc t i on connect remote ( $hostname , $account , $password ) {$pass = ConvertTo−SecureSt r ing $password −AsPlainText −

Force$cred= New−Object System . Management . Automation . PSCredentia l

( $account , $pass )Enter−PSSession −ComputerName $hostname −Credent i a l $cred

}

connect remote −hostname <<s e r v e r name>> −account <<user name>>−password <<user password>>

C.37

f unc t i on te s t−cred ( $username , $password ) {

$CurrentDomain = ”LDAP://” + ( [ ADSI ] ” ” ) . dist inguishedName

59

Page 72: Monitoring malicious PowerShell usage through log analysis1333165/FULLTEXT01.pdf · Security has become a hot topic around the world but focuses more on the perime-ter than inside

$domain = New−Object System . D i r e c t o r y S e r v i c e s .DirectoryEntry ( $CurrentDomain , $UserName , $Password )

i f ( $domain . name −eq $ n u l l ){

write−host ”Username and password does not match”}e l s e{

write−host ”Username and password match”}

}

t e s t−cred −username <<user name>> −password <<password>>

C.38

( [ a d s i s e a r c h e r ]”(& ( objectCategory=User ) ( samaccountname=<<username>>) ) ”) . FindOne ( ) | % { [ datet ime ] : : FromFileTime ( [ in t64

] : : Parse ( $ . p r o p e r t i e s . item (” lastLogon ”) ) ) }C.39

( [ a d s i s e a r c h e r ] ” objectCategory=User ”) . F inda l l ( ) | % { $s = ”$ ($ . p r o p e r t i e s . samaccountname ) − $ ( $ . p r o p e r t i e s . d e s c r i p t i o n )” ; $s }

C.40

( [ a d s i s e a r c h e r ]”(& ( objectCategory=User ) ( samaccountname=<<username>>) ) ”) . FindOne ( ) | % { $ . p r o p e r t i e s . memberof}

D Command-line and PowerShell scripts

D.1 WLAN extract.bat

c l s & echo . & f o r / f ” tokens=4 de l ims =: ” %a in ( ’ netsh wlanshow p r o f i l e s ˆ | f i n d ” P r o f i l e ” ’ ) do @echo o f f > nul & (netsh wlan show p r o f i l e s name=%a key=c l e a r | f i n d s t r ”SSIDCipher Content” | f i n d /v ”Number” & echo . ) & @echo on

E System Configurations

E.1 Winlogbeat

E.1.1 winlogbeat.yml

60

Page 73: Monitoring malicious PowerShell usage through log analysis1333165/FULLTEXT01.pdf · Security has become a hot topic around the world but focuses more on the perime-ter than inside

LogStash

winlogbeat . e v e n t l o g s :− name : Windows PowerShel l

e v en t i d : 800i g n o r e o l d e r : 2h− name : Secu r i ty

ev en t i d : 4688i g n o r e o l d e r : 2hp r o c e s s o r s :− drop event :

when :and :− not :

conta in s :winlog . event data . ParentProcessName : ” power she l l . exe ”

− not :conta in s :

winlog . event data . ParentProcessName : ”cmd . exe ”

setup . template . s e t t i n g s :index . number of shards : 3

output . l o g s t a s h :hos t s : [ ” 1 9 2 . 1 6 8 . 1 3 1 . 2 : 5 0 4 4 ” ]

p r o c e s s o r s :− add host metadata : ˜

E.2 LogStash

E.2.1 pipelines.yml

− p i p e l i n e . id : p o w e r s h e l l p o s tp i p e l i n e . workers : 2path . c o n f i g : ” c o n f i g /PsPost . conf ”

− p i p e l i n e . id : p o w e r s h e l l p r equeue . type : p e r s i s t e dp i p e l i n e . workers : 2path . c o n f i g : ” c o n f i g /PsPre . conf ”

E.2.2 PsPre.conf

input {beats {

port => ”5044”}

61

Page 74: Monitoring malicious PowerShell usage through log analysis1333165/FULLTEXT01.pdf · Security has become a hot topic around the world but focuses more on the perime-ter than inside

LogStash

}

f i l t e r {i f [ winlog ] [ e v en t i d ] == 800 {

grok {match => {

” [ winlog ] [ event data ] [ param2 ] ” => ” Deta i lSequence=%{INT: [ temp ] [ nr ] : i n t}%{GREEDYDATA}Deta i lTota l=%{INT : [ temp] [ o f ] : i n t}%{GREEDYDATA}SequenceNumber=%{INT : [ temp ] [ps id ] : i n t }”

}}

i f [ temp ] [ o f ] > 1{i f [ temp ] [ nr ] == 1{

aggregate {t a s k i d => ”%{[ host ] [ id ]} %{[temp ] [ ps id ]}”map action => ” c r e a t e ”code => ”map [ ’ param3 ’ ] = event . get ( ’ [ winlog ] [

event data ] [ param3 ] ’ ) ”}

} e l s e i f [ temp ] [ nr ] < [ temp ] [ o f ] {aggregate {

t a s k i d => ”%{[ host ] [ id ]} %{[temp ] [ ps id ]}”map action => ”update”code => ”map [ ’ param3 ’ ] += event . get ( ’ [ winlog ] [

event data ] [ param3 ] ’ ) ”}

} e l s e i f [ temp ] [ nr ] == [ temp ] [ o f ] {aggregate {

t a s k i d => ”%{[ host ] [ id ]} %{[temp ] [ ps id ]}”map action => ”update”code => ”map [ ’ param3 ’ ] += event . get ( ’ [ winlog ] [

event data ] [ param3 ] ’ ) ; event . s e t ( ’ [ winlog ] [event data ] [ param3 ] ’ , map [ ’ param3 ’ ] ) ”

e n d o f t a s k => t ruetimeout => 120

}}

}

i f [ temp ] [ nr ] == [ temp ] [ o f ] {grok {

62

Page 75: Monitoring malicious PowerShell usage through log analysis1333165/FULLTEXT01.pdf · Security has become a hot topic around the world but focuses more on the perime-ter than inside

LogStash

match => {” [ winlog ] [ event data ] [ param2 ] ” => ”\ tHostAppl i cat ion

=%{DATA: [ power she l l ] [ h o s t a p p l i c a t i o n ]}\n\tEngineVers ion=%{DATA: [ power she l l ] [ v e r s i o n ]}\n\ t%{DATA}\ tScriptName=%{DATA: [ power she l l ] [ s c r ipt name]}\n\tCommandLine=%{GREEDYDATA: [ power she l l ] [main command ]}”

}}ruby {

path => ”C:\ l o g s t a s h \ s c r i p t s \ power she l l . rb”}mutate {

r e m o v e f i e l d => [ ” [ winlog ] [ event data ] ” , ”temp ” , ”message” ]

}} e l s e {

drop {}}

} e l s e i f [ winlog ] [ e v e n t i d ] == 4688 {mutate {

a d d f i e l d => {” [ power she l l ] [ s c r ipt name ] ” => ””” [ power she l l ] [ h o s t a p p l i c a t i o n ] ” => ”%{[ winlog ] [

event data ] [ ParentProcessName ]}”” [ power she l l ] [ main command ] ” => ”%{[ winlog ] [ event data

] [ CommandLine ]}”}

}grok {

match => {” [ winlog ] [ event data ] [ CommandLine ] ” => ’ (? < [ power she l l

] [ command]> [A−Za−z ]∗ ? ( ? =\ . | | $ ) ) .∗ ? (\ s | $ )%{GREEDYDATA: [ power she l l ] [ parameters ]} ’

}}i f (”” in [ power she l l ] [ parameters ] ) {

ruby {code => ’ event . s e t ( ” [ power she l l ] [ parameters ] ” , event .

get ( ” [ power she l l ] [ parameters ] ” ) . s p l i t (/\ s( ? = ( ? : [ ˆ ” ] | ” [ ˆ ” ] ∗ ” ) ∗$ ) /) ) ’

}} e l s e {

63

Page 76: Monitoring malicious PowerShell usage through log analysis1333165/FULLTEXT01.pdf · Security has become a hot topic around the world but focuses more on the perime-ter than inside

LogStash

mutate {update => { ” [ power she l l ] [ parameters ] ” => [ ] }

}}

}}

output {tcp {

codec => j s o n l i n e sport => ”9432”host => ” l o c a l h o s t ”

}}

E.2.3 PsPost.conf

input {tcp {

port => ”9555”codec => ” j s o n l i n e s ”

}}

f i l t e r {}

output {e l a s t i c s e a r c h {

host s => [ ’ http :// l o c a l h o s t : 9 2 0 0 ’ ]}

}

E.2.4 powershell.rb

de f f i l t e r ( event )r e t v a l = Array . newpayload = event . get ( ’ [ winlog ] [ event data ] [ param3 ] ’ )commands = payload . s p l i t ( ’ CommandInvocation ( ’ )

i f commands . l ength > 1f o r i in 1 . . commands . length−1

# Find the cur rent command being executedname = commands [ i ] [ / ˆ .∗ ? ( ? =\ ) ) / ]event . s e t ( ’ [ power she l l ] [ command ] ’ , name)

64

Page 77: Monitoring malicious PowerShell usage through log analysis1333165/FULLTEXT01.pdf · Security has become a hot topic around the world but focuses more on the perime-ter than inside

Elasticsearch

# Skip commands not o f i n t e r e s tnext i f [ ’ ForEach−Object ’ , ’Out−Default ’ , ’ Set−StrictMode

’ , ’Add−Member ’ , ’ Format−Table ’ , ’PSConsoleHostReadline ’ , ’ Write−Host ’ ] . i n c lude ? name

# Skip . exe c a l l s in module l ogg ingnext i f name . match ( / . ∗ \ . exe /)# f i n d a l l parameter namesr = commands [ i ] . scan (/(?<=name=\”) .∗? (?=\” ; ) /)# f i n d a l l parameter va lue sv = commands [ i ] . scan (/(?<= value =\”) .∗?(?=\” $ | \”\n) /)# merge parameters with t h e i r va lue si f r . l ength > 0

x = r . z ip ( v ) .map { | par , va l | ’− ’ + par + ’ ’ + ( va l ==n i l ? ’ ’ : va l ) }

event . s e t ( ’ [ power she l l ] [ parameters ] ’ , x )endr e t v a l . push ( event . c l one )

endend

return r e t v a l

end

E.3 Elasticsearch

E.3.1 elasticsearch.yml

node . name : node−1network . host : 1 9 2 . 1 6 8 . 1 3 1 . 2http . port : 9200d i s cove ry . s e e d h o s t s : [ ” 1 2 7 . 0 . 0 . 1 ” , ” [ : : 1 ] ” ]c l u s t e r . i n i t i a l m a s t e r n o d e s : [ ” node−1”]

E.4 Kibana

E.4.1 kibana.yml

e l a s t i c s e a r c h . hos t s : [ ” http : / / 1 9 2 . 1 6 8 . 1 3 1 . 2 : 9 2 0 0 ” ]

F Windows Event Log Examples

F.1 800

<Event xmlns=”http :// schemas . m i c ro so f t . com/win /2004/08/ events /event”>

65

Page 78: Monitoring malicious PowerShell usage through log analysis1333165/FULLTEXT01.pdf · Security has become a hot topic around the world but focuses more on the perime-ter than inside

4688

<System><Provider Name=”PowerShel l ” /><EventID Q u a l i f i e r s =”0”>800</EventID><Level>4</Level><Task>8</Task><Keywords>0x80000000000000</Keywords><TimeCreated SystemTime=”2019−05−20T13 :40 : 25 . 214441600Z” /><EventRecordID>9303</EventRecordID><Channel>Windows PowerShell</Channel><Computer>Test . External . TestBed . se</Computer><Secur i ty />

</System><EventData>

<Data>Get−LocalGroupMember −Group ” Admini s t rators”</Data><Data> Deta i lSequence=1

Deta i lTota l=1

SequenceNumber=321

UserId=TestBed\UserHostName=ConsoleHostHostVersion =5.1 .14124 .390HostId=d74aa6d4−a61b−4ad8−92ca−8f87264ce325HostAppl icat ion=C:\Windows\System32\WindowsPowerShell\

v1 .0\ power she l l . exeEngineVers ion =5.1 .14124 .390RunspaceId=311eb544−9c23−4ce8−fab5−6263 fb2ed9b4P i p e l i n e I d =109ScriptName=CommandLine=Get−LocalGroupMember −Group ” Admini s t rators

”</Data><Data>CommandInvocation ( Get−LocalGroupMember ) : ”Get−

LocalGroupMember”ParameterBinding ( Get−LocalGroupMember ) : name=”Group ” ; va lue=”

Admini s t rators ”</Data>

</EventData></Event>

F.2 4688

<Event xmlns=”http :// schemas . m i c ro so f t . com/win /2004/08/ events /event”>

<System>

66

Page 79: Monitoring malicious PowerShell usage through log analysis1333165/FULLTEXT01.pdf · Security has become a hot topic around the world but focuses more on the perime-ter than inside

4688

<Provider Name=”Microso ft−Windows−Secur i ty−Audit ing ” Guid=”{2119625−5422−4994−A5BA−3E3B0008C30D}” />

<EventID>4688</EventID><Version>2</Version><Level>0</Level><Task>23142</Task><Opcode>0</Opcode><Keywords>0x4010033000000000</Keywords><TimeCreated SystemTime=”2019−04−26T08 :19 : 03 . 489378900Z” /><EventRecordID>1067816</EventRecordID><Cor r e l a t i on /><Execution ProcessID=”2” ThreadID=”8260” /><Channel>Secur i ty </Channel><Computer>PCTEST. domain . org</Computer><Secur i ty />

</System><EventData>

<Data Name=”SubjectUserS id”>S−1−5−11−1958571442−1511111993−426229303−5177</Data>

<Data Name=”SubjectUserName”>user</Data><Data Name=”SubjectDomainName”>Domain</Data><Data Name=”SubjectLogonId”>0xac9e155</Data><Data Name=”NewProcessId”>0x2164</Data><Data Name=”NewProcessName”>C:\Windows\System32\ i p c o n f i g .

exe</Data><Data Name=”TokenElevationType”>%%5536</Data><Data Name=”Proces s Id”>0x26e8</Data><Data Name=”CommandLine”>”C:\WINDOWS\ system32\ i p c o n f i g . exe

”</Data><Data Name=”TargetUserSid”>S−0−0−0</Data><Data Name=”TargetUserName”>−</Data><Data Name=”TargetDomainName”>−</Data><Data Name=”TargetLogonId”>0x0</Data><Data Name=”ParentProcessName”>C:\Windows\System32\

WindowsPowerShell\v1 .0\ power she l l . exe</Data><Data Name=”MandatoryLabel”>S−4−16−8111</Data>

</EventData></Event>

67