Checkmarx Application Security Platform The world runs on code. We secure it. Thu, 15 Aug 2024 14:09:40 +0000 en-US hourly 1 https://wordpress.org/?v=6.6.1 https://checkmarx.com/wp-content/uploads/2024/06/cropped-cx_favicon-32x32.webp Checkmarx Application Security Platform 32 32 LofyGang – Software Supply Chain Attackers; Organized, Persistent, and Operating for Over a Year https://checkmarx.com/blog/lofygang-software-supply-chain-attackers-organized-persistent-and-operating-for-over-a-year/ Fri, 07 Oct 2022 13:00:00 +0000 https://checkmarx.com/?p=79723

Checkmarx discovered ~200 malicious NPM packages with thousands of installations linked to an attack group called “LofyGang”.

This attack group has been operating for over a year with multiple hacking objectives:

  • Credit card information
  • Discord “Nitro” (premium) upgrades
  • Streaming services accounts (e.g. Disney+), Minecraft accounts, and more.

Our findings were disclosed to the security teams of GitHub, NPM, Repl.it, Discord, and more.

We’ve launched a tracker website https://lofygang.info/ to share the findings about these attackers and share the full list of LofyGang’s related packages here.

Connecting the Dots

In August 2022, we bumped into a couple of LofyGang’s malicious packages. It started with a report from one of our internal engines. Our researchers immediately began investigating and crossing the IOC using our internal retro-hunting tools. This helped reveal more and more connections to other packages, and some of the packages linked to reports from Sonatype, SecureList, and JFrog, but each report was a small piece of the big puzzle, as you can see below. The detective board was so overloaded at some point that we had to zoom out. See the image below. We are also sharing the detective board PDF file here.

Historical Hunting

When defenders disclose malicious packages to package managers (NPM, PyPi, etc..), the package managers simply delete the related release artifacts and metadata.

While this does prevent users from downloading the malware, it makes things hard for defenders to (a) know what happened, as this is not documented, and (b) learn and improve from the attacker’s activities as it’s almost impossible to get the removed evidence.

Checkmarx research team created internal tools to continuously collect open source-related evidence. This is powering our research process; as you can see in this report, it helps us reveal and correlate deleted historical evidence and re-investigate samples which assist us in telling you the story of LofyGang over time. To read more about the fruits of retro-hunting, check out this story.

About LofyGang

By observing LofyGang’s activities across the internet, it appears they are an organized crime group focused on stealing and sharing stolen credit cards, gaming and streaming accounts, and more.

They create sock-puppets accounts using a closed dictionary of names with slight permutations of keywords such as lofy, life, polar, panda, kakau, evil, devil, and vilão (villain in Portuguese).

As we explored this case, we guessed their origin is Brazil as much of the evidence contained Brazilian Portuguese sentences and even a file called “brazil.js”, which contained malware found in a couple of their malicious packages.

Discord Server

LofyGang’s Discord server was created a year ago, on October 31, 2021, and seems to be the main channel of communication between the group’s administrators and their members.

In this Discord server, you can find technical support for the group’s hacking tools, a dark meme group, and a dedicated bot responsible for a giveaway of Discord Nitro upgrades.

Discord Bot – “Lofy Boost”

LofyGang created a Discord bot “Lofy Boost” to deploy stolen credit cards on the operator’s account. When calling the bot command “ph!boost”, the operator must provide it with his personal credentials. Also, LofyGang stated that whoever uses this bot will also automatically boost LofyGang’s Discord server.

Cracked.io Contributions

The group is contributing to an underground hacking community under the alias DyPolarLofy, where  they leak thousands of Disney+ and  Minecraft accounts, promote their hacking tools under their GitHub page, promote their bots, and more.

Fake Instagram Followers As-A-Service

It seems that LofyGang’s main offering in that underground hacking community is to sell fake Instagram followers. This links to some of the malicious package profiles; for example, the package “fetch-string” is linked to the “victorjxl” Instagram account, which appeared to be an account with fake followers.

GitHub Profile

The group is hosting hack tools under the GitHub account PolarLofy. Their open source repositories offer tools and bots for Discord, such as:

  • Discord spammer
  • Password stealer
  • Nitro Generator
  • Chat Wiper
  • And more

YouTube Tutorials

LofyGang has a YouTube channel with self-promotion content, such as video tutorials demonstrating how to use their hacking tools. Their channel has almost 4k subscribers.

Using Legitimate Services as C2

Discord, Repl.it, glitch, GitHub, and Heroku are just a few services LofyGang is using as C2 servers for their operation.

Malicious Packages

We were able to trace ~200 malicious open-source packages published in the past year. We saw several classes of malicious payloads, general password stealers, and Discord-specific persistent malware; some were embedded inside the package, and some downloaded the malicious payload during runtime from c2 servers.

We’ve launched a tracker website https://lofygang.info/ to share the findings about these attackers and share the full list of LofyGang’s related packages here.

Typosquatting and StarJacking

Typosquatting is a technique commonly used by attackers targeting the open source supply chain that relies on typing mistakes. Attackers register permutations of typing mistakes of popular packages, like “falsk” instead of “flask.” This leads to the accidentally installation of a malicious package.

Starjacking, usually combined with Typosquatting, occurs whenever a package references a git repository; websites such as PyPi, NPM, etc., display the statistics such as GitHub issues, stars, forks, etc., accordingly. The package managers do not validate the accuracy of this reference, and we see attackers take advantage of that by stating their package’s git repository is legitimate and popular, which may trick the victim into thinking this is a legitimate package due to its so-called popularity. We saw Starjacking  in another previously reported attack last month.

LofyGang, like many other attackers, used Typosquatting and Starjacking techniques to appear popular and legitimate to developers. For instance, they often use the words “color” and “discord” in package names in addition to referencing a legitimate GitHub repository and copying another popular package’s description as-is.

Hiding in a Sub-Dependency

One of the techniques used by the attackers to avoid detection is to keep the first-level package clean from malicious code, but having it depend on another package that introduces the malicious code. We saw that whenever the malicious dependent package was caught and removed, the attackers would replace it with a new one, and publish a new version of the main package which was never removed.

The packages are purposely published by different NPM user accounts to decouple them as much as possible if one of them is caught.

Modifying the Installed Discord Application

Some of the group’s malicious packages were spotted modifying the installed Discord instance with hooks to steal credit cards, sent via Discord webhook straight to the attackers whenever a payment was made.

Anti-Deobfuscation

Some of the malicious payloads are obfuscated. When we tried de-obfuscating the payloads, we noticed that the writers of this code added anti-deobfuscation statements to be executed whenever de-obfuscation tools such as https://github.com/relative/synchrony were used. The anti-deobfuscation statements would unpack a naïve regular expression that jams the event loop, making debugging the malicious code confusing.

NPM Activity Over Time

Since the beginning of their malicious activities on NPM, we’ve seen a steady flow of dozens of malicious packages published per month.

Don’t Trust Code From Strangers, Especially Attackers ????

LofyGang’s hack tools also depend on malicious packages, which infect their operators with persistent hidden malware using the same capabilities as described above. For instance, we saw the tool “Discord-Mass-Dm” on GitHub, which depends on “small-sm” – one of LofyGang’s malicious packages.

Screenshot from the group’s hack tool “Discord-Mass-Dm” having a malicious dependency.

In addition, some reports from the underground community cautioned about LofyGang’s code examples, discord bots, and other contributions which were also infected.

Conclusion

The surge of recent open-source supply chain attacks teaches us that cyber attackers have realized that abusing the open-source ecosystem represents an easy way to increase the effectiveness of their attacks.

Communities are being formed around utilizing open-source software for malicious purposes. We believe this is the start of a trend that will increase in the coming months.

We’d like to thank our friends from Sonatype, SecureList, and JFrog for publishing their reports. By crossing those findings, we were able to connect the dots faster and create this investigation board which links the source of those activities to LofyGang.

We believe in sharing and working together to keep the ecosystem safe. Shoot us an email at supplychainsecurity@checkmarx.com if you’re interested in this incident’s samples or other data.

Tracker Website

We’ve launched a tracker website https://lofygang.info/ to share new findings about these attackers. This is an open source static website available on our GitHub. If you bump into more of these packages, feel free to contribute!

List of Malicious Packages

See the following list of malicious packages in this gist: https://gist.github.com/jossef/aaa9e45c062d973f18bd87c43b9c4fc7

IOC

  • hxxps://canary[.]discord[.]com/api/webhooks/1010307578896584765/Kfko3kvm_uwgTjZlGgmTnHirUnfqDagEyMjXrPBKn-9oSJXR2-s1SOMxe4zsq_JpbbA6
  • hxxps://canary[.]discord[.]com/api/webhooks/1011399721878814850/LfNuEU1BFNNmF_laiFT7_7OFSlHKecYXB7NdaAi1NTtOnTkDI2Dm_KALPKUJm6qqyRFU
  • hxxps://canary[.]discord[.]com/api/webhooks/903018156283551775/lJOJ9526e_rzw0Js2DQPdV0eYQd5RQybtUcJqolp84JTwlxJxaWnuam9FyUplYN2TJfT
  • hxxps://canary[.]discord[.]com/api/webhooks/914037745771499571/AB0bgB81VjZhloJ789Rlctn0IBCvi1Ldq6VDupf7bjI4T7TTJ57vMByABDTd8uCgaTdC
  • hxxps://canary[.]discord[.]com/api/webhooks/918981986096381962/cSgWzzDxr-wKWtEt_6Kql2DPTF9GNgcvtjfUGzPR4hy7EuTy0q9w2_ptp0YTBauTd8xn
  • hxxps://canary[.]discord[.]com/api/webhooks/949718758296002631/SpfpIZp0psg_QWas7fhPjcaVrXqWsAHwO3w5CsyD7CXtMW860MeI-NhX59f2nYtmeKmS
  • hxxps://canary[.]discord[.]com/api/webhooks/984673863805837352/FzN-2AdPtz1RZBO5j3VcNmdC9x3gQ7pPZKt9Lt6J6ys_8vLtThI5SmVXosifztix66IB
  • hxxps://canary[.]discord[.]com/api/webhooks/984688862397870080/c3qSIuHwNXCWS3KlAu3pqBD4xp_vS0WuhAClfNfcZLvtZwJn5jGcu0NtsvY9ccdMuY0W
  • hxxps://canary[.]discord[.]com/api/webhooks/984688878139109396/Yq1v7Tdd-xgba_GSVaHBGIUO9YM57xCj5wojF4CFhylLyHIc_Dl-_3vEQ35IStxwOraV
  • hxxps://canary[.]discord[.]com/api/webhooks/984720782930358303/oYisKKXVvyFMLxeRTcri41fV0v31q7AA6BrAsJvWrGjGA2aLOqri_bZuzzCM5CGjbVw9
  • hxxps://discord[.]com/api/webhooks/1007006820629483640/PcVef3zPDULoGoHQBQu1WK_pLYOMtOdk6ynz0wqSFJf6yv0Ro5iZpMLiZ3Pe4aVKxk-j
  • hxxps://discord[.]com/api/webhooks/904528194634403941/L0VOc4iDPfIqrxAT7zdu6outRd_H1Msg6KWlp5puRsHomqBx403GQOiR33KEJgAUaMup
  • hxxps://discord[.]com/api/webhooks/905040941210009600/ePUsX_HQO2urHu8dGxIRe4Xc7f2oBYBOefzSqZOofWBOWf329EWAZ6Ou_YfHpRm4yscb
  • hxxps://discord[.]com/api/webhooks/914037745771499571/AB0bgB81VjZhloJ789Rlctn0IBCvi1Ldq6VDupf7bjI4T7TTJ57vMByABDTd8uCgaTdC
  • hxxps://discord[.]com/api/webhooks/915623697610592337/Vzzg2pVt8RbaDB9FDsmcDZ7lP1NA_bAb4tIMOdZLGAJ1SW-QVtJOvCzCMjCyv56hiK0z
  • hxxps://discord[.]com/api/webhooks/930679264238526516/RZuAyoB_lyUN8oHP4qhPcHTj4mqxUVtTjl0ns_SApm2uqt4b8fF-SaPbS98Yaw0TnzUk
  • hxxps://discord[.]com/api/webhooks/932004105180827728/ujjSxTrm495ED2aZyy4KcGij46T04SHCW_v1R5Y9O5Fio3CWhLf7Vx_-8_1AkWnBtPt5
  • hxxps://discord[.]com/api/webhooks/937305693143310356/1qn3-WmKtRciNHFemaqpKLVauBgPI00_Vu8J_UbA5ySwio_6k_8XFs3vx17MHenWhy9C
  • hxxps://discord[.]com/api/webhooks/947531680938336296/WKswtEcag_JOyyIBpn5Gtkm5euDRHd9KYskA0PjI8APu2f5MHeLEtyY28H2MatkCtIKN
  • hxxps://discord[.]com/api/webhooks/953241659813011556/XtxjMHOnwEG-El3bYE92xidIIE1ppEvghZ697CvqbFxZF0Zug_FKyr1pyrX_eucxvIKk
  • hxxps://discord[.]com/api/webhooks/953241815820173352/N31HYut5ZLnXg6VzYWLhaKQPs9jwi5tUinCDw5tZkP857K80F8e-ToXoJkb27KDurvid
  • hxxps://discord[.]com/api/webhooks/955210570364223559/YjuF9W338gvOWjmvov_L-Gd76ufB1Askk52uPlCFuZIj5elVPyfV6f2BOYPCdIRBlQvB
  • hxxps://discord[.]com/api/webhooks/957683084151623700/Pg1hrdWZQumi4YGvStMnx9om3LsiJ45keS8MHakWhZZQgvAqfraYlM2AovyvwstNYJWd
  • hxxps://discord[.]com/api/webhooks/958195333589004329/xKR83dNat_Sl90lAjgY6KLGnfEUgBvDTR8ZDV7-GtxMpJ-s2V227bN9QrlbuKZ9lIvR7
  • hxxps://discord[.]com/api/webhooks/976901668786548787/tUVW6mqnwG3gPmouXzThYAPGEyf2qmA6T8pNGU1edSxYx881HNS4rLo88UcuQ9D4aa4p
  • hxxps://discord[.]com/api/webhooks/979128884324884521/AXZVtB7Iw-F4VwhNfhgsy7hDYJLvA-ECklpyOjl9mFTO8cIyIMb5w8f1ekaZCXZa3tLr
  • hxxps://discord[.]com/api/webhooks/987289154821951528/FcCt-I0mfAglretxRcyeI_wb5RPiSMqzMcw4V14Ns8mqz14JQiz3-9MbZhmoSdwdTpzy
  • hxxps://discord[.]com/api/webhooks/990106451324338237/mSg2aHrG-nhssCvVI5HJRH-Fg8nrLKD-S64nort9IORlH4QretOi-aAvBaeZQFwfNcjS
  • hxxps://discord[.]com/api/webhooks/995137146530836512/mJtGOehWgbBkcHZYKVdHIxIsurkRQrg-gIHT6c0LDsO3y9_veDv38urWJrTQhHZ1HPYe
  • hxxps://frequent-level-cornflower[.]glitch[.]me
  • hxxps://github[.]com/NotFubukIl/DiscordTokenGrabber
  • hxxps://github[.]com/mafintosh/end-of-stream/tree/daba5d692f7f016bad7831b4f61caad3ba2d2544
  • hxxps://historical-mangrove-turnover[.]glitch[.]me/discord
  • hxxps://ibb[.]co/nmDLGCT
  • hxxps://idk[.]polarlabs[.]repl[.]co
  • hxxps://kakau–kozune[.]herokuapp[.]com
  • hxxps://kauedaocu[.]space/api/webhooks/evilKaue
  • hxxps://kauelindo[.]xyz/manhattan
  • hxxps://lofy[.]polarlofy7[.]repl[.]co
  • hxxps://low-abaft-wax[.]glitch[.]me
  • hxxps://nikezada[.]tk/raw/injectionviIaomoduIe
  • hxxps://pastebin[.]com/raw/HMgsiG4k
  • hxxps://pastebin[.]com/raw/LcqZiszq
  • hxxps://pastebin[.]com/raw/Su4ip2LB
  • hxxps://pastebin[.]com/raw/aTgt2yTk
  • hxxps://pastebin[.]com/raw/gUKcsvAX
  • hxxps://pastebin[.]com/raw/zaNHxzJL
  • hxxps://pegapiranha[.]com/kauanaperigosa
  • hxxps://ptb[.]discord[.]com/api/webhooks/953241518024572938/LD2_8dHNulaQrhtQioIo5_E8iaO866o7twVgJgPo9b8acLRZs8zwOpRnuS-11fgXced3
  • hxxps://ptb[.]discord[.]com/api/webhooks/953241856244846593/6iDkaIFk_6Rui_SgQ-u3uNAplUSuvhPfh3o39dbezTIaKpyNkXmHl2QVbDiKO1aHQPH2
  • hxxps://qualquer1[.]tartrweatr[.]repl[.]co
  • hxxps://raw[.]githubusercontent[.]com/Balenciaga7/client/main/client[.]js
  • hxxps://raw[.]githubusercontent[.]com/NotFubukIl/DiscordTokenGrabber/main/data/index[.]js
  • hxxps://raw[.]githubusercontent[.]com/Rubyx-S/tqt/main/index[.]js
  • hxxps://raw[.]githubusercontent[.]com/Stanley-GF/PirateStealer/main/src/Injection/injection
  • hxxps://raw[.]githubusercontent[.]com/Stanley-GF/PirateStealer/main/src/injection/injection[.]js
  • hxxps://raw[.]githubusercontent[.]com/VaporMax7/client/main/injection[.]csp
  • hxxps://raw[.]githubusercontent[.]com/disclord/-js/main/index[.]js
  • hxxps://raw[.]githubusercontent[.]com/drooutokenchecker/god/main/injection[.]js
  • hxxps://raw[.]githubusercontent[.]com/haxdeveloper/Aryzs-Injection/main/aryzsminified[.]js
  • hxxps://raw[.]githubusercontent[.]com/haxdeveloper/Aryzs-Injection/main/aryzsminified[.]js?token=GHSAT0AAAAAABTTSWAISYVCRFCXON6NGVPCYVWTAKA
  • hxxps://raw[.]githubusercontent[.]com/haxdeveloper/Aryzs-Injection/main/aryzsminified[.]js?token=GHSAT0AAAAAABTTSWAJWYEPF32M7SU7VGGGYVWRLCQ
  • hxxps://raw[.]githubusercontent[.]com/iowfqjfiowjq/AAAAAAAAAAAA/main/aliente[.]js
  • hxxps://raw[.]githubusercontent[.]com/k4pis/Painel/main/index[.]js
  • hxxps://raw[.]githubusercontent[.]com/shawty71/evoluiram/main/webhook
  • hxxps://rawbutteryevents[.]kakaunfdifjjgfg[.]repl[.]co
  • hxxps://stealer-api[.]herokuapp[.]com
  • hxxps://vilao[.]cf/injectionmoduIeviIao
  • hxxps://vilao[.]xyz/api/dc/core/inject
  • hxxps://vilao[.]xyz/api/dc/core/raw
  • hxxps://vilao[.]xyz/api/dc/inject=raw
  • hxxps://vilao[.]xyz/raw/injectionviIaomoduIe
  • hxxps://vilaozada[.]tk/raw/injectionviIaomoduIe
  • hxxps://vilaozada[.]tk/raw/webhookmoduIeviIao
  • hxxps://www[.]klgrth[.]io/paste/62fo9/raw
  • hxxps://www[.]klgrth[.]io/paste/baez7/raw
  • hxxps://www[.]klgrth[.]io/paste/jce5w/raw
  • hxxps://www[.]klgrth[.]io/paste/m8fh6/raw
  • hxxps://www[.]klgrth[.]io/paste/nfnk5/raw
  • hxxps://www[.]klgrth[.]io/paste/vrkur/raw


To learn more about Checkmarx approach to Supply Chain Security, request a demo of our Checkmarx One™ Application Security Platform today. Or sign up for a 14-day free trial here.

]]>
image_1-1024×659-1 image_2-1024×878-1 image_3-1024×651-1 image_4-1024×704-1 image_5-1024×794-1 image_6-1024×688-1 image_7-1024×828-1 image_8-1024×707-1 image_9-1024×546-1 image_10-1024×775-1 Malicious package Attack diagram image_12-1024×866-1 image_13-1024×322-1 ???? image_15-1024×775-1 image_16-1024×775-1
API Security: Exposed API Endpoint Leaks Over 11 Million Telco Customers’ Data https://checkmarx.com/blog/api-security-exposed-api-endpoint-leaks-over-11-million-telco-customers-data/ Wed, 05 Oct 2022 13:08:22 +0000 https://checkmarx.com/?p=79688

Last week, one of the largest telcos in the Asia Pacific regions was compromised. The attackers scraped customer data, including personally identifiable information (PII), via an unsecured API endpoint publicly available on the internet. The attackers released sample data of a few users, including names, email addresses, physical addresses, passport numbers, driver’s license numbers, birth dates, whether a person owns their home or not, and more. The leaked data includes both current and former customers.

Not only was the data stolen but also it was used. There were reports that driver’s licenses, passports, and national IDs were applied for on the victims’ behalf, constituting a serious risk of identity theft. A few users reported they received a direct email asking for a $2,000 ransom to delete their data.1

The intruders were able to fetch the data using an API that is believed to have had no authentication in place and provided direct access to the attackers for stealing the data. After leaking the data of 10,200 users, the attackers ostensibly had a change of heart and issued a public apology stating they deleted the data, however, we can only take their word as there’s no evidence to suggest they did not successfully sell the leaked data.

After a week (28-Sep-2022), the Medical Record ID for thousands were reported to be compromised via the same exposed API endpoint.2 Though this has already ignited the fire for lawmakers to impose stricter norms, proactive actions are necessary.

How can “shift-left” for API testing help?

Shift-left is an approach to software and system testing in which testing is performed earlier in the development life cycle. Developers are empowered to scan their source code and remediate identified vulnerabilities rather than relying on a separate team or process.

Traditional API protections are run-time focused, where API Gateways or Web Application Firewalls (WAFs) can only secure the API endpoints of which they are aware. In the case of the telco data breach, it appears that they were either unaware that the API endpoint existed or that it was exposed publicly, meaning an API Gateway or WAF may not have stopped the breach.

By analysing the underlying source code of the application’s APIs using static application security testing (SAST), vulnerabilities can be identified and thus remediated earlier, saving organizations time, effort, and monetary resources. And by scanning APIs at the source, organizations can identify otherwise undocumented endpoints (known as shadow APIs), such as what appears to be the case that led to the data breach of the APAC telco. Of course, you need a good platform to do the analysis.

How can Checkmarx API Security help?

The Checkmarx One™ Application Security Platform includes our API Security scan engine, which uses static code analysis to identify and inventory API endpoints, the request and response data associated with those endpoints, and any related vulnerabilities. By scanning applications and APIs at the source, we identify vulnerabilities earlier and provide pointed guidance to developers and AppSec teams on where best to address the vulnerabilities before releasing code to production.

Checkmarx API Security scans source code, indexing the data flow through the code and capturing potential vulnerabilities using a set of queries.  We index, enumerate, and correlate our scan findings, providing developers and AppSec teams the specific file path and line number where the vulnerability was found. Furthermore, we provide pointed remediation guidance—as necessary—on the identified vulnerability.  In the image below, we see a SQL Injection vulnerability associated with a specific API endpoint.

Because we have visibility of the underlying source code for the API endpoint, we can capture and provide details of the APIs associated parameters and whether it exposes any sensitive data, such as usernames or passwords.

What are the benefits of using source code API security?

  • Complete API visibility: Provides AppSec teams with the most accurate and up-to-date view of their entire API attack surface, eliminating the problem of shadow and zombie APIs.
  • True shift-left approach: Discovers APIs in application source code to identify and fix problems earlier in the SDLC–faster with lower cost and risk.
  • DevOps readiness: It can be easily integrated with DevOps platforms.
  • Prioritization remediation: Focuses developers and AppSec teams on solving the most critical issues by prioritizing API vulnerabilities based on their real impact and risk.
  • Holistic view into application risk: Scans the entire application with a single solution (SAST and API testing), eliminating the need for additional API-specific tools to reduce the overhead on over-burdened AppSec teams.
  • Prevent vs. protect methodology: Source code analysis for API Security allows teams to create more secure APIs early in the SDLC and give fast feedback to developers, preventing issues from being pushed into the product.
  • Knowing which application/project the API belongs to: reduces the time it takes to fix the problem.

Conclusion

This recent unfortunate example underscores the importance of analysing APIs at the source. By leveraging Checkmarx API Security, available within the Checkmarx One Platform, organizations can proactively protect against attacks such as these, helping to protect their customer data and reputation.

Reach out to a sales team today for more information or a live demonstration!

1 https://www.crikey.com.au/2022/09/26/optus-hack-cyberattack-reform/
2 https://www.youtube.com/watch?v=x9YIb46kPS0

]]>
Automatic Execution of Code Upon Package Download on Python Package Manager https://checkmarx.com/blog/automatic-execution-of-code-upon-package-download-on-python-package-manager/ Fri, 26 Aug 2022 10:00:00 +0000 https://checkmarx.com/?p=78686

Automatic code execution is triggered upon downloading approximately one third of the packages on PyPi.

A worrying feature in pip/PyPi allows code to automatically run when developers are merely downloading a package. Also, this feature is alarming due to the fact that a great deal of the malicious packages we are finding in the wild use this feature of code execution upon installation to achieve higher infection rates.

It is important that python developers understand that package downloading can expose them to an increased risk of a supply chain attack.

Intro

When executing the well-known “pip install <package_name>” command, users may expect code to be run on their machine as part of the installation process. One source of such code usually resides in the setup.py file of python packages.

When a python package is installed, pip, python’s package manager, tries to collect and process the metadata of this package, such as its version and the dependencies it needs in order to work properly. This process occurs automatically in the background by pip running the main setup.py script that comes as part of the package structure.

setup.py example

The purpose of setup.py is to provide a data structure for the package manager to understand how to handle the package.

However, the setup.py file is still a regular python script that can contain any code the developer of the package would like. An attacker who understands this process can plant malicious code in the setup.py file, which would then execute automatically during the package’s installation. In fact, much of the malicious packages we are detecting contain malicious code in the setup.py file.

What if we just download the package rather than install it?

In addition to the “install” command, pip provides several more options, among them is the “download” command. This command is intended to allow users to download packages’ files without the need to install them.

There could be various reasons someone would need this. For example, a developer may want to look into the package’s code before using it. A user may want or need to perform a security check, or perhaps even observe the setup.py file for any anomalies.

As it turns out, executing the command “Pip download <package_name>” will run the setup.py file, as well as any potentially malicious code contained within it. It may surprise you, but this behavior is not a bug but rather a feature in the pip design. Users who intentionally only download a package do not expect code to run on their system automatically.

As a matter of fact, this concern was expressed in an issue from 2014 on the pypa project https://github.com/pypa/pip/issues/1884, yet it was not addressed, and the issue continues to exist to this day.

The .whl file type

Python wheels are essentially .whl files that are part of the Python ecosystem and bring various performance benefits to the package installation process. But that is not the only thing that wheels bring to the table. In the past, when python code was built into a package, the result would be a tar.gz file that would then be published to the PyPi platform. tar.gz files include the setup.py file which is run upon download and installation.

But suppose you’ve recently tried downloading or installing a Python package using pip. In that case, you may have noticed Python supplying you with a .whl file. The reason for this is when developers build a python package using, for example, the pip -m build” command, in newer pip versions, pip automatically tries to create a secondary .whl file in addition to the tar.gz file, which is then published together to the Python Package manager platform. When a user downloads or installs this package, PIP will by default deliver the .whl file to the user’s machine. The way wheels work cuts the setup.py execution out of the equation.

Why is the setup.py still relevant?

Even though pip defaults to using wheels instead of tar.gz files, malicious actors can still intentionally publish python packages without a .whl file. When a user downloads a python package from PyPi, pip will preferentially use the .whl file, but will fall back to the tar.gz file if the .whl file is lacking.

Is there anything you can do about this?

Currently, there are actions users can take to prevent automatic execution upon package download. One action is checking the package file contents at https://pypi.org/project/<package>/#files and observing if a .whl file is present. If there is a .whl file, the user can feel confident they will receive the .whl file, and no code will be executed on their machine.

If there is only tar.gz present, a user can use a safe method of download such as working directly with PyPi’s “simple” API: https://pypi.org/simple/<package-name>/. For example, when using the package listed above, prp1, a user can download it from the following link https://pypi.org/simple/prp1/.

Conclusion

Code execution upon installation is one of the features attackers use the most in open-source attacks. Developers opting to download, instead of installing packages, are reasonably expecting that no code will run on the machine upon downloading the files. However, PyPi includes a feature allowing just that—code execution on the user’s machine when all that was requested was a file download.

It is possible to protect yourselves from suspicious package by following the steps detailed above.

As always, we are releasing similar blogs to help keep the open source ecosystem safe and raise the awareness of python developers to this issue so they can avoid unwanted consequences.


To learn more about how Checkmarx is helping secure the open source software supply chain, download our white paper: Don’t Take Code from Strangers – An Introduction to Checkmarx Supply Chain Security

]]>
API Security Is the New Endpoint Security https://checkmarx.com/blog/api-security-is-the-new-endpoint-security-2/ Wed, 24 Aug 2022 13:23:14 +0000 https://checkmarx.com/?p=78708 Endpoint security remains a constant challenge for organizations 25 to 30 years later. Even in the 90s when things were much simpler, understanding what was attached to a corporate network was a seemingly insurmountable task—and that was with good port security. Today, not only do organizations manage, maintain, and secure the devices they issue but also, so much business is conducted on personal devices operating within a network that is under constant change. Factor SaaS and cloud services into the mix, and it gets even more daunting. It’s no wonder that endpoint security and data protection remain a constant battle for most organizations today. 

Understanding inventory and what should or should not be part of the corporate ecosystem, control over those endpoints, incident response, policy, compliance, malware … The list of challenges is at best constant, at worst, ever-growing. It’s not a new problem but one that remains difficult to solve. It seems that infrastructure and security teams are relegated to robust reactive measures (e.g., incident response) when proactive measures are undermined by careless or thoughtless users.  

There is a certain level of irony in the fact that APIs (application programming interfaces) are often referred to as endpoints as well. Architecturally, APIs are designed to make software more extensible and offer flexibility to unique and custom use cases. Each API is defined as a contract, which accepts certain input and provides certain output. Most modern software leverages private APIs to proffer out-of-the-box functionality as well as public APIs, which users of the software may interact with to extend functionality or cater to their own specific use case. 

Much like physical (or virtual) machines on a network, APIs represent a significant viable attack surface area for would-be attackers. What’s more, command and control over APIs, how they’re built, what security mechanisms they employ, the data they expose, and how and when they are released or sunset is an increasingly challenging problem that organizations are forced to deal with.  

Security teams often aren’t advanced enough to look into what developers are deploying; documentation of APIs is often lacking; version control is often missing; and as a result, the underbelly of deployed applications is (unintentionally) exposed. Some security reports suggest that 40 to 50 percent of organizations have experienced an API breach in the last year, and research also suggests that an overwhelming volume of API traffic is malicious. Well-known companies like Peloton, LinkedIn, Experian, and John Deere have all dealt with the fallout of API security challenges. 

For the developer audience that may be interested in common weaknesses of APIs and how they’re built insecurely, consider reviewing the OWASP API Security Project. For the security architects and risk managers, there are a couple of obvious first steps to gain ground on the API challenge. 

First, you cannot protect, regulate, or inspect what you don’t know about. Discovery, much like infrastructure endpoint security, is a very critical first step. Second, once you know what’s out there, you need to gain an understanding of what type of data may be exposed by these APIs. APIs that expose sensitive data should be known, documented, and properly secured. Lastly, find out what exploitable weaknesses or vulnerabilities may be lurking in the implementation of that API (see OWASP API Security Project). 

Seems easy, right? 

Most security tooling for API security lives in runtime space. This means these tools can examine, in real-time, API calls and the data that these APIs are delivering. But in many cases, this is too late. These tools support a reactionary model that relies on stopping malicious actors just in time, if at all, and they are less capable of detecting data sensitivity concerns or vulnerabilities in the implementation of an API. 

A better way to do API security is to shift left and look at the code developers are writing. With this approach, discovery, data sensitivity issues, and exploitable vulnerabilities in API code can be identified simply by interrogating code stored in a repository. All this can be done well before any APIs are deployed in a production environment. The opportunity to trap security issues well before they are a legitimate risk, and when they’re cheaper to fix, is significant and a game-changer in the API-security space. 

API security tooling isn’t new, but it’s never been done the Checkmarx way. To learn more, check out Checkmarx API Security

]]>
Most Dangerous CWEs of 2021 https://checkmarx.com/blog/most-dangerous-cwes-of-2021/ Mon, 22 Aug 2022 12:02:32 +0000 https://checkmarx.com/?p=78432

2021 was a year where cyberattacks exploded, and if you did not know about the dangers of the cyber world, you probably do now. The pandemic got everyone into their homes and focused on their IT devices, so there was plenty of time to think about security vulnerabilities. In this blog, we will look at the top 10 software vulnerabilities of 2021 based on CWE, and collect some statistics about them according to data collected from MITRE’s CWE.

The above table ranks the top 10 software vulnerabilities of 2021 based on CWE, from most dangerous to least dangerous. Starting from the left, we have the CWE Id and Name, then we have the Number of Vulnerabilities related to that CWE that occurred in the year, the average CVSS Score of those vulnerabilities, and finally the Programming Language that is related to those vulnerabilities.

We can see that almost all vulnerabilities have an average of High criticality level, except for Cross Site Scripting and Out-of-Bounds Read, that have a Medium severity; however, these occupy the 2nd and 3rd place because they have a high popularity. Thus, the ranking of the CWEs is done not only by severity (CVSS score) but also by its popularity (the number of occurrences). For instance, one interesting factor is that Cross Site Scripting (the 2nd most dangerous CWE of 2021) actually has the most occurrences of vulnerabilities. However, having only Medium severity, it loses its place to Out-of-bounds Write due to the High CVSS score, which makes it much more dangerous.

Moreover, we can see that 30% of the vulnerabilities only happen in C/C++, and another 30% are in Web-based languages, meaning that only websites or web apps are affected. The remaining 40% are Language-Independent—meaning that these are independent of any specific programming language or technology/application type.

C and C++ languages

In C and C++ languages, the vulnerabilities that tend to happen are due to the fact that these programming languages do not perform their memory management and do not provide overflow protection. What this means is that the developer is the one who needs to programmatically implement logic to allocate and manage the application memory, which in other languages is done automatically. This is directly related to the overflow attacks since these languages allow us to directly access memory, and there are no built-in protections against accessing or writing data to any part of the memory.

Web-based languages

In Web-based languages, we see very distinct vulnerabilities. But one similarity in all of them is that the common way for attackers to reach their victims is trying to somehow inject malicious content into the web application, in order to change its behavior and execute unintended actions. For instance, in “Unrestricted Upload of File with Dangerous Type” the intention is to try to upload a file to the application in order for it to be later used and perform unintended/unauthorized actions. Another similarity that we see in XSS and CSRF, is that these attacks are mainly directed at the users of the applications in order to try to exploit them, or use them to indirectly exploit the application.

Language-Independent

In Language-Independent vulnerabilities, these are similar in the sense that they are related to the incorrect or inexistence of input validation checks, and the difference is the component that is exploited. Applications should always check and validate the input that is being submitted to them, in order to prevent maliciously formed data from tampering with the application’s actions, which can lead to either the access to sensitive data, the unauthorized access to a database, or the execution of unwanted commands.

The CWE list

Below, we discuss each one of the vulnerabilities in more detail:

1 – We see Out-of-bounds Write being the number 1 vulnerability in 2021. Typically, attackers exploit this issue by overwriting the memory of an application to try to make the program execute some malicious code.

Let’s look at CVE-2021-24036 as an example. The following is one of its vulnerable functions. The ‘size’ variable enters as input to the function, so this means it can be controlled by the user/attacker. This raises some issues because if its value is too big, when it is added to the heap storage, it can cause an integer overflow leading to an out-of-bounds write.

Despite its danger, this can be easy to mitigate though. In this case, as seen in the following code snippet, the fix is to first validate if the ‘size’ variable is bigger than a certain limit, specified by the ´kMaxIOBufSize´ variable, and in case it is, the function throws an exception about it and simply does not proceed—never reaching out of its memory pointer.

2 – Cross Site Scripting (XSS) was the 2nd most dangerous vulnerability of 2021. This is a popular Web issue that happens when the application does not sanitize user-controlled input before it is placed as output in some place of the web page. With this, attackers can inject malicious code into a web page and compromise the users that access it.

To check what happens at code level, we will look at CVE-2021-23327. In the following code snippet, you can see that a ‘span’ is being created with an inner ‘text’ that comes from user input. The problem here is that this input is not being sanitized, which means an attacker could inject malicious code, and it would be generated in the web page.

To mitigate this vulnerability, you need to sanitize the input to remove any unwanted characters and strings, in order to prevent harmful codes. The following code snippet shows the fix of the vulnerable code, where you can see that the input passes through the function ‘sanitizeDom’, which replaces characters related to HTML tags, disabling the execution of any malicious code.

3 – In 3rd place, we see Out-of-bounds Read. This vulnerability is similar to Out-of-bounds Write, but the difference here is that instead of the attackers trying to change the execution of the application, they try to read data from other memory locations to get sensitive information.

4 – Next is Improper Input Validation, which happens when the application does not properly validate an input, or data that it receives and considers it as safe to process. This has various consequences, for instance, an attacker can either provide a bad input and crash the program, read or modify arbitrary data, execute malicious code, and more.

Let’s look at CVE-2021-28918 as an example. If you check the following function, there is already a loop iterating through the ‘ip’ which validates each of its bytes. This validation, however, is not proper, because parsing is only being done for decimal values, as seen in ‘parseInt(byte, 10)’. This can allow unauthenticated attackers to bypass the validation and perform other types of attacks like SSRF, Remote File Inclusion, or Local File Inclusion.

In order to mitigate these issues, developers need to understand the type of input that is being dealt with, and provide a proper validation to prevent malformed data from entering and tampering with the application. In this case, the fix consists of parsing not only decimal, but also octal bytes. We can see the fix changes in the following code snippet.

5 – OS Command Injection happens when the application does not properly validate an input that it receives to construct an operating system command. This gives an attacker the ability to modify the intended command and execute arbitrary commands on the operating system through the application.

6 – SQL Injection occurs when the application does not properly validate an input that it receives to construct a SQL query. Not validating input can allow an attacker to modify the query logic and read or modify data from the database as well as execute other operations in it.

7 – Use After Free takes place when the application tries to access a memory location that has been freed, which could lead to various consequences such as: crash the program or allow remote code execution.

8 – Path traversal happens when the application does not properly validate or normalize an input that it uses to construct a pathname to a file or directory. Attackers exploit this vulnerability to cause the pathname to resolve to a location outside the application directory, and access or modify arbitrary content on the machine.

9 – Cross-Site Request Forgery (CSRF) is a vulnerability that happens when a web server does not verify that a request from a client is made from the authentic page. As a result, an attacker can craft a malicious website that sends a request to the application on a visitors’ behalf. For example, a victim that visits the crafted website can send a request to the application and perform unintended actions such as changing a password.

10 – Finally, we have Unrestricted Upload of File with Dangerous Type. This vulnerability occurs when an application does not validate the files that are uploaded to it. A typical exploit is an attacker uploading a file containing malicious code (e.g., a php file) which can then be used, for instance, to execute arbitrary commands through the URL.

Do you usually scan your code to check if it has any vulnerabilities that relate to these CWEs? At Checkmarx, we can help! Our application security testing solutions are designed to quickly alert you of these types of risks. Whether you want to perform source code scanning with Checkmarx SAST or software composition analysis with Checkmarx SCA, we have solutions designed to help secure your code.

Learn more about Checkmarx One Application Security Platform, start a free trial, or request a demo today!

]]>
A Practical Example of the Power of Checkmarx Fusion https://checkmarx.com/blog/a-practical-example-of-the-power-of-checkmarx-fusion/ Wed, 03 Aug 2022 13:36:19 +0000 https://checkmarx.com/?p=77895 Application Security (AppSec) personnel have a tough job these days trying to secure their applications.   Many organizations take a fragmented approach to AppSec and scan engines; they may use one vendor for static application security testing (SAST), another for software composition analysis (SCA), and yet another for scanning and securing their Infrastructure-as-Code (IaC) configuration files.  Three different software suites to configure, three different interfaces with which to interact, and at least three different scans to analyze the results. Not to mention that the results are independent of each other with no way to integrate or correlate into one cohesive analysis.

That’s where Checkmarx Fusion comes in. 

Checkmarx Fusion, an element of our Checkmarx One™ Application Security Platform, helps you see all of your scan results on one easy-to-read dashboard. Checkmarx Fusion maps the threats in a visual, intuitive graph containing all software elements, consumed cloud resources, and relationships among them. It extrapolates potential vulnerabilities within two or more scans that might otherwise escape detection. Fusion also adds context to the different scanners by combining and correlating results from static code scans and runtime scans, significantly minimizing false positives.

Let’s take a look underneath the hood at how this process works.

Fusion works with applications and currently supports Java and C# code with Terraform files and AWS, with a roadmap to support additional languages and public cloud providers. As you can see below in Figure 1, there are two applications defined in this instance of the Checkmarx One Platform, one named the “Shopping App,” and another named “Bank.”

Figure 1 Checkmarx One Application and Projects

Clicking on the “Shopping App” Java-based application shows four microservices tied to this application, such as managing users and shipping.

Figure 2 Microservices Tied to the Shopping App

Selecting the “Go to Application” button near the bottom of the page in Figure 2 brings us to the “Shopping App” scan overview page. This page shows information on the most recent scan of this application, such as the number of vulnerabilities found and an aging report on previous findings.

Figure 3 Shopping App Scan Overview

Clicking on the “Advance Insights” link, indicated by the red circle in Figure 3, brings us to the new Fusion correlation engine. There are two views available, the first being a topographical model as seen in Figure 4 below.

Figure 4 Fusion Topographical Map

This view shows a model indicating how services interact with each other. For instance, clicking  “Shipping Microservice” shows which cloud-based infrastructure this microservice is interacting with, such as two Amazon Simple Storage Services (S3_1 and S3_2) and the vulnerabilities found, as seen by Figure 5 below.

Figure 5 Shipping Microservice

In Figure 5, the blue “next page” icon shows more detail of the state of the microservice and any vulnerabilities found with S3_1 and S3_2, as shown in Figure 6. 

Figure 6 Shipping Microservice Vulnerabilities

The ability to show how microservices and their corresponding cloud-based infrastructure interact is critical to minimizing the vulnerabilities in your cloud-based applications. It allows AppSec users to view and correlate vulnerabilities that could have been missed from individual siloed scan results. This “next-generation” of application security testing will allow companies to have confidence that their application is secure and able to withstand the complexities of modern application development (MAD).

As attackers become more sophisticated in their approach and toolsets, so must AppSec professionals and developers.

To learn more about Checkmarx Fusion and how it works in Checkmarx One, our Checkmarx One™ Application Security Platform Demo Video. To see a live demonstration of Checkmarx Fusion, Request a Demo today!

]]>
When It Comes to Cloud, Location Matters https://checkmarx.com/blog/when-it-comes-to-cloud-location-matters/ Tue, 02 Aug 2022 14:26:54 +0000 https://checkmarx.com/?p=77887

Checkmarx One™ Cloud-Based Application Security Platform Is Expanding its Footprint 

The average layperson likely envisions “the cloud” as being some anomalous, effervescent thing that has no boundaries and none of the physical constraints of a typical computing network. Those of us who have helped build “the cloud” know it much differently. To us, it’s just another network made up of routers, switches, cables, fibers, load balancers, servers, security technology, and lots and lots of software. The cloud is nothing more than a network that just so happens to not exist in your buildings. Instead, it’s a network in someone else’s buildings that often spans the world with an almost global reach. Terms like points of presence, edge locations, availability zones, regions, branches, global backbones, peering agreements, etc. are terms often heard by engineers who speak the cloud vernacular.

One of the issues that has often stymied the acceptance of cloud-based offerings like SaaS, PaaS, IaaS, etc. is all about location. The reason for this is simple—jurisdiction. Regulatory compliance requirements like GDPR in the EU, data protection and privacy laws in countries all over the world, and general FUD (fear, uncertainty, and doubt) about the cloud being too risky have slowed its growth. FUD is something that is not easy to overcome; however, data protection and privacy requirements have been addressed due to the cloud footprint. Let’s use DDoS defenses as an example of what we’re talking about.

If an organization in the EU wanted to buy DDoS defenses from a cloud-based provider, the provider would have to have cloud-based DDoS scrubbing centers in the EU. In the event of an organization coming under a DDoS attack, the cloud-based DDoS defense company would swing all inbound traffic destined to a site under attack and route that traffic to a DDoS scrubbing center. The scrubbing center would remove the DDoS component of the traffic, and then return all “good traffic” back to the site under attack.

Most people would believe that this is due to distance requirements, potential latency, etc., but it is not. Since cloud backbones are made up of large numbers of 100 gigabit pipes, latency is not the issue—but jurisdiction and data sovereignty are. In other words, if traffic is coming into an organization in the EU, once that traffic is inside the EU, it must remain in the EU to meet regulatory compliance requirements. If the DDoS scrubbing center was outside of the EU, this would be a compliance issue. And the same thing goes for cloud-based application security testing (AST) platforms like Checkmarx One.

Checkmarx One is an AST platform that exists in our own cloud, running in the cloud. And like any cloud-based DDoS defense provider, the Checkmarx “cloud” must also have a global presence. That is why we already have SaaS instances in North America, the EU, Australia, India, and Singapore. This equates to five (5) SaaS instances to better serve our customers worldwide. Again, this has nothing to do with latency or distance. This has to do with data sovereignty. And with organizations, software developers, and application security teams located all over the world, we must operate in the same regions in which they operate. Checkmarx One is available to all organizations in all regions regardless of their size or number of software developers.

For Checkmarx, it’s always been about a global AppSec presence since software knows no boundaries, but data sovereignty does. Also, there is no difference in the costs of our platform no matter where in the world you operate. Organizations send their lines of code to the location of choice where we operate, the platform scans the code for vulnerabilities and associated risks, and results are returned to the organizations—in the most secure fashion possible. The term we coined for this is called, “Global AppSec,” since we understand code knows no boundaries, and neither does security.

In other words, software security where you need it, when you need it, and however you like it. That is what Checkmarx One is all about.

To learn more about Checkmarx One Application Security Platform, visit us here. Or sign up for a Free Trial of the Platform. We guarantee you won’t regret it.

]]>
What Are the Challenges with Securing APIs? https://checkmarx.com/blog/what-are-the-challenges-with-securing-apis/ Wed, 27 Jul 2022 17:50:45 +0000 https://checkmarx.com/?p=77712 When you expose API services to the public internet, you are responsible not only for their reliable operation, but also for their security. Sufficiently securing and protecting a public API is not just a business necessity – it’s a regulatory requirement. If your APIs are leaking secrets and sensitive PII information, you run the risk of facing lawsuits for failing to protect that information by properly securing them.

This may sound cliché, but the harsh truth is that many public APIs contain numerous vulnerabilities. Therefore, properly securing APIs so that the worst-case scenario doesn’t become a reality is a major challenge for development teams.

This article aims to give the reader a better understanding of what will work and what won’t work in the context of API security. We will walk you through the most essential considerations, taking into account the fact that there is no silver bullet for API security due to the ways in which APIs are built and deployed.

Let’s get started.

Reasons Why APIs Are Hard to Test and Secure

APIs come in all shapes and sizes. The most critical parts of an API are often the most susceptible to attacks on vulnerabilities like those listed in the OWASP API Security Top 10. For example, attackers might attempt to abuse paths for logged in users, exfiltrate sensitive data by fuzzy testing the endpoints, or force the site down using DDoS attacks. As the API surface increases, of course, so does the risk of exposure. Imagine having to protect APIs with hundreds of endpoints, each with its own conventions.

This could happen quite easily when there are multiple teams working on the same project and contributing to the same API. The API might not have a sole owner; instead, it might be exchanged between multiple stakeholders (such as project owners, developers, testers, operations, and network and security teams), with each group submitting their own piece to deliver new features to their customers.

Relying too heavily on some parts of the delivery pipeline to include sufficient security controls is equally problematic. For example, you shouldn’t rely on the development team to constantly provide the most secure software all the time. Developers do not habitually think like attackers. They will incorporate basic pragmatic reasoning and accept logical trade-offs when delivering sprint goals. However, they will miss important security considerations fairly often simply because they are generally unaware of use and abuse scenarios. Likewise, if you expect your WAFs to perpetually block all unwanted traffic and your static code analyzers to always pinpoint all security flaws in the code, then you will be in for a big surprise when attackers exploit unknown vulnerabilities or zero-day bugs.

Therefore, since APIs are hard to test and secure, you must be innovative in finding conventional tools, agile methodologies, and various approaches that work well together. Let’s explore some of them.

Tools and Approaches That Work Well Together – and Some That Don’t

Once you have established that you need to use flexible approaches to keep your APIs secure, you want to make sure that you are following the right guidance. There are lots of great guides and best practices for API security, but it’s important to differentiate the ones that make the most sense for your APIs from the ones that don’t.

Some of the approaches that work with API security are mainly focused on establishing in-depth defenses:

  • Authenticate and authorize by default: When you are developing APIs, you should explicitly mark unauthenticated endpoints (and not the other way around). For example, you should protect all endpoints with strong authentication (2-factor) and assign a default role that cannot read or modify any data. That way, there is less risk of exposing new endpoints that do not have any sort of protections.
  • Use API security scanners: Tools and services in this category include runtime protection, DAST (vulnerability scanning tools), static code analyzers, and security bots. These tools provide a nice layer of defense against baseline security issues.
  • Use penetration testing: You can hire professionals who think like attackers and are able to perform sophisticated tampering. These professionals have access to unconventional tools and leverage techniques that help expose issues that security scanners won’t pick up by default.

On the other hand, some approaches might not work in the long run because they possess inherent risks. For example:

  • Security through obscurity: This means that we try to secure part of the API by making it harder to use or to discover its endpoints or behavior. This is like an Easter egg hunt where you expose certain parts of the API only to clients that know where to look for them. Or you might make it harder for attackers to guess some of the API schemes by using special query parameters or headers. Although this approach might work for certain cases, it is not considered 100% secure. Cunning attackers might figure out a way to uncover those hidden parts of the API or infer how the API response works, which would give them the ability to retrieve sensitive information.
  • Using JSON Web Tokens (JWTs) for storing sensitive data: JWTs offer a good balance between security and convenience when working with APIs – as long as you abide by the rules. If you store sensitive data in the JWT payload, for example, you are already compromising security since JWTs can be decoded easily. Always use industry-standard JWT libraries, strong JWT secrets, and short expiration tokens. In addition, always use HTTPS.

We mentioned before that APIs can be secured by automating the scanning of application code. Let’s explore that in more detail.

How to Effectively Scan APIs

Start with the source of truth, the source code. By scanning the source code, you get a complete view of what APIs are inside of a project. This also allows developers to easily and quickly fix any security issue that has been identified by this static analysis. Since APIs need to be human-readable, scanning the API Documentation as Swagger can also be key to identifying risk—checking key risks like access control, configurations, and best practices. This is an example of shift-left security, wherein DevOps teams ensure that security is built into application development rather than added on later.

Next, once those APIs are moved to an environment, it is easy to perform real E2E tests based on predefined rules against your real API. If the scanner finds any defects or suspicious red flags, it will report them to a dashboard for triaging. These scanners include many checks (like the OWASP API Security Top 10 and open CVEs) and can automatically create policies without intervention.

Even if you have a perfectly valid specification file, though, it doesn’t mean that the scanners will find all of the issues. It’s equally important that you are able to feed the scanner raw HTTP recorded sessions using either Fiddler or Burp so that it can verify unknown parts of the API.

Ways to Address the Continuous Development of APIs and Ever-Changing Contracts

At the end of the day, how can you address the continuous development of APIs and ever-changing contracts when you have to contend with multiple attack vectors in real time?

There are several options to consider:

  • Scan early and often: Software is developed at the speed of light nowadays.The only way to keep up with the ever-changing contracts is scanning the API Documents and Source Code when they are changed by the development team.This can alert them immediately to critical vulnerabilities and risk. Allow the developer to learn better practices and secure the APIs well before they are live.
  • Create clean environments for security testing: Sometimes you can’t slow down the release of new features in the name of security. It’s important that security teams create special environments where they can introduce novel security testing tools and scanners for advanced security testing. The primary idea is to conduct intelligent analytics, pinpoint hidden attack vectors, and expose vulnerabilities without affecting the production environment. Once a security issue has been found and mitigated in this special environment, the security team can patch the production systems using the current change request system.
  • Adopt DevSecOps workflows: DevSecOps is about integrating your IT security team into the full lifecycle of your app. Put simply, this means that security teams follow short and frequent development cycles, integrate security tools and vulnerability scanners with minimal intervention, ensure that all operational technologies run with the optimal security configurations, and promote a security-first mindset across isolated teams. This can be accomplished by including automated security checks throughout the CI/CD process and creating service templates that are secure by default for the development teams to adopt.

Next Steps with API Security

We want to conclude this article by emphasizing the fact that there is no way your APIs can be 100% secure at all times. Instead, organizations should be constantly vigilant to scan their APIs for risks and vulnerabilities. As a security professional, it’s crucial that you stay informed about the status of the API security ecosystem. Reading security advisories like the ones from Checkmarx is a great way to acquire this knowledge. Their advisories discuss real public exposures while providing deep root cause analysis and explaining mitigation tactics. Feel free to sign up for more tutorials about API security and DevSecOps.

About the Author

Theo Despoudis is a Senior Software Engineer, a consultant and an experienced mentor. He has a keen interest in Open Source software Architectures, Cloud Computing, best practices and functional programming. He occasionally blogs on several publishing platforms and enjoys creating projects from inspiration. Follow him on Twitter @nerdokto.

..

..


To learn more about the many risks (including APIs) in modern application development, download this e-book today.

Or if you would like to learn more about Checkmarx approach to API security within the Checkmarx One™ Application Security Platform, this white paper explains it all.

]]>
What Is Your API Attack Surface? https://checkmarx.com/blog/what-is-your-api-attack-surface/ Wed, 20 Jul 2022 11:36:20 +0000 https://checkmarx.com/?p=77455 The proliferation of APIs today is astonishing. According to a recent report, the number of active APIs will approach 1.7 billion by 2030. You might expect that the majority of those APIs would be resistant to attacks or vulnerabilities; however, that is not necessarily the case. In fact, a major study from RapidAPI on the state of enterprise APIs revealed a rather distressing lack of consistent policy enforcement and visibility across all APIs. Many of those APIs might expose parts that are undocumented, which is a great concern among security teams.

This article explores the fundamental reasons why an API can become insecure and discusses ways to reduce the attack surface.

How Do Documentation Tools Like Swagger Fall Short?

Documenting APIs comes with inherent difficulties. The main problem areas include ambiguity of exposed functionality, incomplete or undocumented content, and incorrect responses. Development teams rely on tools like Swagger to help them document their APIs and use automation to mitigate some of those issues.

Swagger is not a panacea, however, and using Swagger/OpenAPI for API development does not protect you against all vulnerabilities. Recent research conducted by Soufian El Yadmani of Cybersprint found many flaws in this technology, including many vulnerabilities listed in the OWASP API Top 10.

For example, issues can happen when a web framework is integrated with Swagger. Developers using the FastAPI framework can receive automatically generated Swagger UI fields from the code without declaring the API specification. This works fine on paper, but it might not work with your particular business requirements. The CRUD model might return a different result based on certain circumstances, for instance, or use a different way of calculating the end result that deviates from a typical case. The framework might be unable to introspect the correct result and rely instead on manual intervention. In this case, developers will have to completely own the dependencies and generated documentation to ensure that they match the expected outcome.

In addition, Swagger generates complex code that has little opportunity for customization, which makes it inconvenient to use. For example, if hypermedia links are missing from the response, developers might try to intervene by writing custom queries that deviate from the spec, thereby increasing the risk of producing undocumented responses.

Overall, the hardest part is establishing proper workflows for working with Swagger in the optimal way – writing specs in YAML, implementing the specs, and writing unit tests that conform with those specs. The API maintainer’s job is to make sure that they don’t deviate from the supported features and that they keep the spec as an authoritative source of truth.

Why It’s Hard to Keep Track Of APIs

There are many reasons why APIs are hard to keep track of, and therefore hard to support at scale, but they all relate to technical debt. Working on many products as part of a broader ecosystem is a very typical scenario. Some parts of the system might be unknown due to a change in business priorities and focus, when some API services were neglected and forgotten – until they failed to work. This is an example of code ownership debt.

Another type of technical debt is people debt. This happens when you allow developers to work on critical API systems for a long time and then they decide to resign from the company. The domain experience that these people acquired when building those systems may be lost to future maintainers unless there is a good handover process. Having many API services and no one who understands how they work significantly contributes to the initial problem.

The issue becomes even bigger when you introduce architectural debt by implementing APIs using microservices. Let’s explain.

How Microservices Architectures Lead to API Communication Flows

APIs and microservices are directly related. As you develop applications using microservices, you create highly decoupled services that enclose their own domain and communicate with each other using APIs. For example, a user microservice needs to communicate with the auth microservice to authenticate the user before responding to a request to view that user’s profile. This communication dictates the use of an API contract between each microservice. In addition, API gateways can be used to aggregate multiple APIs under a single namespace, which helps maintain observability and centralized monitoring at a fundamental level.

More real-world domains may need many microservices. In practice, that means having a separate API layer behind each microservice – and each one has its own attack surface. It’s not unusual to have hundreds of microservices that each expose OpenAPI interfaces. This leads to what is known as API sprawl. In this case, the sheer number of services makes things harder to maintain. It’s very common for businesses to use APIs without tracking when or where they are used, which makes it harder to keep track of their security risks.

Not Knowing All Your APIs Leads to Catastrophe

It is a well-known fact that you cannot secure something when you don’t know it exists. But achieving continuous runtime visibility into all APIs is not trivial. It requires that you understand the exposed parts of the API in depth and that you document the obscure sections, run static code analyzers, and subject the application to security testing. This is mandatory, since the failure to record and secure these parts is very dangerous.

APIs are already extremely susceptible to many kinds of attacks. Undoubtedly, there is no limit to what attackers can use when it comes to stealing sensitive data for malicious purposes. Here are some examples of attacks that you may encounter:

  • DDoS: Attackers can target unknown parts of your APIs to do the maximum damage. They can overload the system with terabytes of bandwidth if they’re successful, and you won’t know what hit you. It’s therefore important to safeguard against DDoS attacks on each exposed part of your APIs.
  • Innocuous access: Hidden or undocumented parts of your API can be easier to exploit. By using unknown endpoints, for example, attackers can dig in quickly and gain unauthorized access without someone detecting anything suspicious. Unless the traffic from those endpoints is more consistent, it will be harder for the security teams to recognise the danger.
  • Injection: API endpoints that are vulnerable to injection attacks (SQL, XSS, and so on) can help attackers expose sensitive data, leak credentials, and gain insights into how to attack the infrastructure. If the API under attack is unknown or undocumented, you will lose valuable time trying to figure out how to safeguard it.

Take extra care when you develop and expose APIs – especially the ones that are used for public access. These can be used as target practice for all sorts of attacks. Conducting a solid security assessment of your APIs will position you one step ahead of any future attacks.

Conclusion

Just because you use Swagger, follow the best practices for documentation, and lead by example does not mean that your APIs are secure by default. It literally takes a village to achieve a superior level of security – mainly because of the inherent difficulty of covering the attack surface of your APIs. This is why you need to establish an end-to-end API security strategy, complete with security testing, extensive discovery of available APIs, and the use of modern tooling and monitoring services. With some effort, you will improve the security posture of your APIs without hurting their overall performance.

About the Author

Theo Despoudis is a Senior Software Engineer, a consultant and an experienced mentor. He has a keen interest in Open Source software Architectures, Cloud Computing, best practices and functional programming. He occasionally blogs on several publishing platforms and enjoys creating projects from inspiration. Follow him on Twitter @nerdokto.

..

..


To learn more about the many risks (including APIs) in modern application development, download this e-book today.

Or if you would like to learn more about Checkmarx approach to API security within the Checkmarx One™ Application Security Platform, this white paper explains it all.

]]>