Edward Jackson

Edward Jackson

1559182487

Top 10 npm Security Best Practices

10 npm Security Best Practices. Avoid publishing secrets to the npm registry. Enforce the lockfile. Assess npm project health. Audit for vulnerabilities in open source dependencies. Use a local npm proxy. Responsibly disclose security vulnerabilities. Enable 2FA. Use npm author tokens.

Concerned about npm vulnerabilities? It is important to take npm security into account for both frontend, and backend developers. Open source security auditing is a crucial part of shifting security to the left, and npm package security should be a top concern, as we see that even the official npm command line tool has been found to be vulnerable.

In this cheat sheet edition, we’re going to focus on npm security and productivity tips for both open source maintainers and developers. So let’s get started with our list of 10 npm security best practices, starting with a classic mistake: people adding their passwords to the npm packages they publish!

DOWNLOAD THE CHEAT SHEET!


1. Avoid publishing secrets to the npm registry

Whether you’re making use of API keys, passwords or other secrets, they can very easily end up leaking into source control or even a published package on the public npm registry. You may have secrets in your working directory in designated files such as a .env which should be added to a .gitignore to avoid committing it to a SCM, but what happen when you publish an npm package from the project’s directory?

The npm CLI packs up a project into a tar archive (tarball) in order to push it to the registry. The following criteria determine which files and directories are added to the tarball:

  • If there is either a .gitignore or a .npmignore file, the contents of the file are used as an ignore pattern when preparing the package for publication.
  • If both ignore files exist, everything not located in .npmignore is published to the registry. This condition is a common source of confusion and is a problem that can lead to leaking secrets. Developers may end up updating the .gitignore file, but forget to update .npmignore as well, which can lead to a potentially sensitive file not being pushed to source control, but still being included in the npm package.

Another good practice to adopt is making use of the files property in package.json, which works as a whitelist and specifies the array of files to be included in the package that is to be created and installed (while the ignore file functions as a blacklist). The files property and an ignore file can both be used together to determine which files should explicitly be included, as well as excluded, from the package. When using both, the former the files property in package.json takes precedence over the ignore file.

When a package is published, the npm CLI will verbosely display the archive being created. To be extra careful, add a --dry-run argument to your publish command in order to first review how the tarball is created without actually publishing it to the registry.

In January 2019, npm shared on their blog that they added a mechanism that automatically revokes a token if they detect that one has been published with a package.


2. Enforce the lockfile

We embraced the birth of package lockfiles with open arms, which introduced: deterministic installations across different environments, and enforced dependency expectations across team collaboration. Life is good! Or so I thought… what would have happened had I slipped a change into the project’s package.json file but had forgotten to commit the lockfile along side of it?

Both Yarn, and npm act the same during dependency installation . When they detect an inconsistency between the project’s package.json and the lockfile, they compensate for such change based on the package.json manifest by installing different versions than those that were recorded in the lockfile.

This kind of situation can be hazardous for build and production environments as they could pull in unintended package versions and render the entire benefit of a lockfile futile.

Luckily, there is a way to tell both Yarn and npm to adhere to a specified set of dependencies and their versions by referencing them from the lockfile. Any inconsistency will abort the installation. The command line should read as follows:

  • If you’re using Yarn, run yarn install --frozen-lockfile.
  • If you’re using npm run npm ci.

3.Minimize attack surfaces by ignoring run-scripts

The npm CLI works with package run-scripts. If you’ve ever run npm start or npm test then you’ve used package run-scripts too. The npm CLI builds on scripts that a package can declare, and allows packages to define scripts to run at specific entry points during the package’s installation in a project. For example, some of these script hook entries may be postinstall scripts that a package that is being installed will execute in order to perform housekeeping chores.

With this capability, bad actors may create or alter packages to perform malicious acts by running any arbitrary command when their package is installed. A couple of cases where we’ve seen this already happening is the popular eslint-scope incident that harvested npm tokens, and the crossenv incident, along with 36 other packages that abused a typosquatting attack on the npm registry.

Apply these best practices in order to minimize the malicious module attack surface:

Always vet and perform due-diligence on third-party modules that you install in order to confirm their health and credibility.

  • Hold-off on upgrading blindly to new versions; allow new package versions some time to circulate before trying them out.
  • Before upgrading, make sure to review changelog and release notes for the upgraded version.
  • When installing packages make sure to add the --ignore-scripts suffix to disable the execution of any scripts by third-party packages.
  • Consider adding ignore-scripts to your .npmrc project file, or to your global npm configuration.

4. Assess npm project health

Outdated dependencies

Rushing to constantly upgrade dependencies to their latest releases is not necessarily a good practice if it is done without reviewing release notes, the code changes, and generally testing new upgrades in a comprehensive manner. With that said, staying out of date and not upgrading at all, or after a long time, is a source for trouble as well.

The npm CLI can provide information about the freshness of dependencies you use with regards to their semantic versioning offset. By running npm outdated, you can see which packages are out of date:

Dependencies in yellow correspond to the semantic versioning as specified in the package.json manifest, and dependencies colored in red mean that there’s an update available. Furthermore, the output also shows the latest version for each dependency.


Call the doctor

Between the variety of Node.js package managers, and different versions of Node.js you may have installed in your path, how do you verify a healthy npm installation and working environment? Whether you’re working with the npm CLI in a development environment or within a CI, it is important to assess that everything is working as expected.

Call the doctor! The npm CLI incorporates a health assessment tool to diagnose your environment for a well-working npm interaction. Run npm doctor to review your npm setup:

  • Check the official npm registry is reachable, and display the currently configured registry.
  • Check that Git is available.
  • Review installed npm and Node.js versions.
  • Run permission checks on the various folders such as the local and global node_modules, and on the folder used for package cache.
  • Check the local npm module cache for checksum correctness.

5. Audit for vulnerabilities in open source dependencies

The npm ecosystem is the single largest repository of application libraries amongst all the other language ecosystems. The registry and the libraries in it are at the core for JavaScript developers as they are able to leverage work that others have already built and incorporate it into their code-base. With that said, the increasing adoption of open source libraries in applications brings with it an increased risk of introducing security vulnerabilities.

Many popular npm packages have been found to be vulnerable and may carry a significant risk without proper security auditing of your project’s dependencies. Some examples are npm request, superagent, mongoose, and even security-related packages like jsonwebtoken, and npm validator.

Security doesn’t end by just scanning for security vulnerabilities when installing a package but should also be streamlined with developer workflows to be effectively adopted throughout the entire lifecycle of software development, and monitored continuously when code is deployed.


Scan for vulnerabilities

Scanning for security vulnerabilities with Snyk, use:

$ npm install -g snyk
$ snyk test

When you run a Snyk test, Snyk reports the vulnerabilities it found and displays the vulnerable paths so you can track the dependency tree to understand which module introduced a vulnerability. Most importantly, Snyk provides you with actionable remediation advise so you can upgrade to a fixed version through an automated pull request that Snyk opens in your repository, or apply a patch that Snyk provides to mitigate the vulnerability if no fix is available. Snyk provides a smart upgrade by recommending the minimal semver-upgrade possible for the vulnerable package.


Monitor for vulnerabilities discovered in open source libraries

The security work doesn’t end there.

What about security vulnerabilities found in an application’s dependency after the application has been deployed? That’s where the importance of security monitoring and tight integration with the project’s development lifecycle comes in.

We recommend integrating Snyk with your source code management (SCM) system such as GitHub or GitLab so that Snyk actively monitors your projects and:

  • Automatically open PRs to upgrade or patch vulnerable dependencies for you
  • Scan and detect vulnerabilities in open source libraries that a pull request may have introduced

If you can’t integrate Snyk with an SCM, it is possible to monitor snapshots of your projects as sent from the Snyk CLI tool as well, by simply running:

$ snyk monitor

How is Snyk different from npm audit?

  1. We invite you to review a blog post published by Nearform which  compares the differences between npm’s audit and Snyk
  2. Snyk’s vulnerability database offers comprehensive data about vulnerabilities through its threat intelligence system. Providing better coverage and being able to surface and report vulnerabilities that have not yet received a CVE. For example, 72% of the vulnerabilities in npm’s advisories were added first to the Snyk database. See more on this here: https://snyk.io/features/vulnerabilitiy-database/

6. Use a local npm proxy

The npm registry is the biggest collection of packages that is available for all JavaScript developers and is also the home of the most of the Open Source projects for web developers. But sometimes you might have different needs in terms of security, deployments or performance. When this is true, npm allows you to switch to a different registry:

When you run npm install, it automatically starts a communication with the main registry to resolve all your dependencies; if you wish to use a different registry, that too is pretty straightforward:

  1. Set npm set registry to set up a default registry.
  2. Use the argument –registry for one single registry.

Verdaccio is a simple lightweight zero-config-required private registry and installing it is as simple as follows:

$ npm install --global verdaccio

Hosting your own registry was never so easy! Let’s check the most important features of this tool:

  • It supports the npm registry format including private package features, scope support, package access control and authenticated users in the web interface.
  • It provides capabilities to hook remote registries and the power to route each dependency to different registries and caching tarballs. To reduce duplicate downloads and save bandwidth in your local development and CI servers, you should proxy all dependencies.
  • As an authentication provider by default, it uses an htpasswd security, but also supports Gitlab, Bitbucket, LDAP. You can also use your own.
  • It’s easy to scale using a different storage provider.
  • If your project is based in Docker, using the official image is the best choice.
  • It enables really fast bootstrap for testing environments, and is handy for testing big mono-repos projects.

It is fairly simple to run:

$ verdaccio --config /path/config --listen 5000

If you use verdaccio for a local private registry, consider having a configuration for your packages to enforce publishing to the local registry and avoid accidental publishing by developers to a public registry. To achieve this add the following to package.json:

“publishConfig”: {
 “registry”: “https://localhost:5000
}

Your registry is running—ya !! Now, to publish a package just use the npm command npm publish and it is ready for you to share it with the world.


7. Responsibly disclose security vulnerabilities

When security vulnerabilities are found, they pose a potentially serious threat if publicly disclosed without prior warning or appropriate mitigation available for users to protect themselves.

It is recommended that security researchers follow a responsible disclosure program, which is a set of processes and guidelines that aims to connect the researchers with the vendor or maintainer of the vulnerable asset, in order to convey the vulnerability, it’s impact and applicability. Once the vulnerability is correctly triaged, the vendor and researcher coordinate a fix and a publication date for the vulnerability in an effort to provide an upgrade-path or remediation for affected users before the security issue is made public.

Security is too important to be an afterthought or handled unethically. At Snyk, we deeply value the security community and believe that a responsible disclosure of security vulnerabilities in open source packages helps us ensure the security and privacy of the users.

Snyk’s security research team regularly collaborates with the community for bug bounties, such as the case with f2e-server that resulted in hundreds of community disclosures, as well as Snyk’s very close partnership with academic researchers such as Virginia Tech to provide security expertise and the ability to coordinate with vendors and community maintainers.

We invite you to collaborate with us and offer our help with the disclosure process:

8. Enable 2FA

In October 2017, npm officially announced support for two-factor authentication (2FA) for developers using the npm registry to host their closed and open source packages.

Even though 2FA has been supported on the npm registry for a while now, it seems to be slowly adopted with one example being the eslint-scope incident in mid-2018 when a stolen developer account on the ESLint team lead to a malicious version of eslint-scope being published by bad actors.

** URGENT SECURITY WARNING ** Please share.

Today, version 3.7.2 of eslint-scope (https://t.co/Gkc9XhDRN6) was found to contain malicious code that steals your NPM credentials. Take action now if you are using version 3.7.2.

Snyk DB entry: https://t.co/dAhhA3cZQP
— Snyk (@snyksec) July 12, 2018

The registry supports two modes for enabling 2FA in a user’s account:

  • Authorization-only—when a user logs in to npm via the website or the CLI, or performs other sets of actions such as changing profile information.
  • Authorization and write-mode—profile and log-in actions, as well as write actions such as managing tokens and packages, and minor support for team and package visibility information.

Equip yourself with an authentication application, such as Google Authentication, which you can install on a mobile device, and you’re ready to get started. One easy way to get started with the 2FA extended protection for your account is through npm’s user interface, which allows enabling it very easily. If you’re a command line person, it’s also easy to enable 2FA when using a supported npm client version (>=5.5.1):

$ npm profile enable-2fa auth-and-writes

Follow the command line instructions to enable 2FA, and to save emergency authentication codes. If you wish to enable 2FA mode for login and profile changes only, you may replace the auth-and-writes with auth-only in the code as it appears above.


9. Use npm author tokens

Every time you log in with the npm CLI, a token is generated for your user and authenticates you to the npm registry. Tokens make it easy to perform npm registry-related actions during CI and automated procedures, such as accessing private modules on the registry or publishing new versions from a build step.

Tokens can be managed through the npm registry website, as well as using the npm command line client. An example of using the CLI to create a read-only token that is restricted to a specific IPv4 address range is as follows:

$ npm token create --read-only --cidr=192.0.2.0/24

To verify which tokens are created for your user or to revoke tokens in cases of emergency, you can use npm token list or npm token revoke respectively.


10. Understand module naming conventions and typosquatting attacks

Naming a module is the first thing you might do when creating a package, but before defining a final name, npm defines some rules that a package name must follow:

  • It is limited to 214 characters
  • It cannot start with dot or underscore
  • No uppercase letters in the name
  • No trailing spaces
  • Only lowercase
  • Some special characters are not allowed: “~\’!()*”)’
  • Can’t start with . or _
  • Can’t use node_modules or favicon.ico due are banned

Even if you follow these rules, be aware that npm uses a spam detection mechanism when publishing new packages, based on score and whether a package name violates the terms of the service. If conditions are violated, the registry might deny the request.

Typosquatting is an attack that relies on mistakes made by users, such as typos. With typosquatting, bad actors could publish malicious modules to the npm registry with names that look much like existing popular modules.

We have been tracking tens of malicious packages in the npm ecosystem; they have been seen on the PyPi Python registry as well. Perhaps some of the most popular incidents have been for cross-env, event-stream, and eslint-scope.

One of the main targets for typosquatting attacks are the user credentials, since any package has access to environment variables via the global variable process.env. Other examples we’ve seen in the past include the case with event-stream, where the attack targeted developers in the hopes of injecting malicious code into an application’s source code.

To reduce the risk of such attacks you might do the following:

  • Be extra-careful when copy-pasting package installation instructions into the terminal. Make sure to verify in the source code repository as well as on the npm registry that this is indeed the package you are intending to install. You might verify the metadata of the package with npm info to fetch more information about contributors and latest versions.
  • Default to having an npm logged-out user in your daily work routines so your credentials won’t be the weak spot that would lead to easily compromising your account.
  • When installing packages, append the –ignore-scripts to reduce the risk of arbitrary command execution. For example: npm install my-malicious-package --ignore-scripts

DOWNLOAD THE CHEAT SHEET!

Be sure to print out the cheat sheet and pin it up somewhere to remind you of some of the npm security best practices you should follow if you’re a javascript developer, or just enjoy using npm for fun.


Learn More

10 Node Frameworks to Use in 2019

Machine Learning In Node.js With TensorFlow.js

Full Stack Developers: Everything You Need to Know

MEAN Stack Tutorial MongoDB, ExpressJS, AngularJS and NodeJS

Build a web scraper with Node

Originally published by Liran Tal, Juan Picado at https://snyk.io

#npm #node-js #security

What is GEEK

Buddha Community

Top 10 npm Security Best Practices
Wilford  Pagac

Wilford Pagac

1596796680

OWASP Top 10 API Security - DZone Security

I am sure that almost all of you would be aware about OWASP. But, just for the context let me just brief about the same.

OWASP is an international non-profit organization that is dedicated to web application security. It is a completely opensource and community driven effort to share articles, methodologies, documentation, tools, and technologies in the field of web application security.

When we talk about API, we are almost every time talking about REST and OWASP has a dedicated project to API security. As this series of articles are focused towards the API security, we shall not be going in details of web application security. You can use the provided links to find more about these. Let us spend some time on the background, before we dive deep in to API security project.

Background

OWASP’s most widely acknowledged project is OWASP top 10. This is the list of security risks compiled by the security experts from across the world. This report is continuously updated, outlining the concerns of web application security, and specially focuses on the Top 10 of the most critical risks. According to OWASP, this report is an “The OWASP Top 10 is a standard awareness document for developers and web application security. It represents a broad consensus about the most critical security risks to web applications.” They recommend that all companies incorporate the report into their processes in order to minimize and/or mitigate security risks. The latest version was published in 2017 and below is the list.

  1. Injection
  2. Broken Authentication
  3. Sensitive Data Exposure
  4. XML Eternal Entities (or XXE)
  5. Broken Access Control
  6. Security Misconfiguration
  7. Cross-Site Scripting (or XSS)
  8. Insecure Deserialization
  9. Using Components With known vulenerabilities
  10. Insufficient Logging And Monitoring

How API Security Is Different from Web Application Security

Although API’s have many similarities with web applications, but both are fundamentally different in nature.

In web applications, all the processing is done on the servers and the resulting web page is sent back to web-browser for rendering. Because of this nature, they have limited entry point and attack surface which are resulting web pages. This can easily be protected by putting up and web-application firewall (WAF) in front of the application server.WAF

In most of the modern application UI itself uses API’s to send and receive data from backend servers and provide the functionality of the application. It is the responsibility of the clients to do the rendering and convert the responses to a web page.

API GET and raw data

Also, with the rise of microservices architecture individual components become APIs, and it becomes a different world altogether, where UI clients could interact with hundreds of services via API calls. This significantly increases the attack surface. Now all those API’s become the entry point and attack surface.

These entry points can’t be guarded using the WAF solutions as they cannot differentiate between the legitimate and malicious API calls.

Why A Separate Project on API security?

Since its first release in 2003 OWASP top 10 projects has been the most useful resource in terms of web application security risks and to suggest the ways to mitigate these issues.

These days almost all the application development like banking, retail, transportation, smart devices, are done with the APIs.

APIs are critical to modern mobile and SaaS application. By nature, the API’s expose business logic and data, often these data are sensitive in nature, for example Personally Identifiable Information (PII). Because of this API’s are increasingly being targeted by attackers.

As API’s are changing how we design and develop our application, this is also changing the way we think about our security. A new approach in needed in terms of security risks. To cater to this need, OWASP decided to come up with another version of Top 10 dedicated to API security which is named “OWASP API Security Project”. The first report was released on 26 December 2019.

Below is the OWASP Top 10 API security risks and their brief description as provided by the official report.

API1:2019 Broken Object Level Authorization

APIs tend to expose endpoints that handle object identifiers, creating a wide attack surface Level Access Control issue. Object level authorization checks should be considered in every function that accesses a data source using an input from the user.

API2:2019 Broken User Authentication

Authentication mechanisms are often implemented incorrectly, allowing attackers to compromise authentication tokens or to exploit implementation flaws to assume other user’s identities temporarily or permanently. Compromising system’s ability to identify the client/user, compromises API security overall.

#security #api security #owasp top 10 #api penetration testing #api security risks #owasp top 10 web security risk

Wilford  Pagac

Wilford Pagac

1596789120

Best Custom Web & Mobile App Development Company

Everything around us has become smart, like smart infrastructures, smart cities, autonomous vehicles, to name a few. The innovation of smart devices makes it possible to achieve these heights in science and technology. But, data is vulnerable, there is a risk of attack by cybercriminals. To get started, let’s know about IoT devices.

What are IoT devices?

The Internet Of Things(IoT) is a system that interrelates computer devices like sensors, software, and actuators, digital machines, etc. They are linked together with particular objects that work through the internet and transfer data over devices without humans interference.

Famous examples are Amazon Alexa, Apple SIRI, Interconnected baby monitors, video doorbells, and smart thermostats.

How could your IoT devices be vulnerable?

When technologies grow and evolve, risks are also on the high stakes. Ransomware attacks are on the continuous increase; securing data has become the top priority.

When you think your smart home won’t fudge a thing against cybercriminals, you should also know that they are vulnerable. When cybercriminals access our smart voice speakers like Amazon Alexa or Apple Siri, it becomes easy for them to steal your data.

Cybersecurity report 2020 says popular hacking forums expose 770 million email addresses and 21 million unique passwords, 620 million accounts have been compromised from 16 hacked websites.

The attacks are likely to increase every year. To help you secure your data of IoT devices, here are some best tips you can implement.

Tips to secure your IoT devices

1. Change Default Router Name

Your router has the default name of make and model. When we stick with the manufacturer name, attackers can quickly identify our make and model. So give the router name different from your addresses, without giving away personal information.

2. Know your connected network and connected devices

If your devices are connected to the internet, these connections are vulnerable to cyber attacks when your devices don’t have the proper security. Almost every web interface is equipped with multiple devices, so it’s hard to track the device. But, it’s crucial to stay aware of them.

3. Change default usernames and passwords

When we use the default usernames and passwords, it is attackable. Because the cybercriminals possibly know the default passwords come with IoT devices. So use strong passwords to access our IoT devices.

4. Manage strong, Unique passwords for your IoT devices and accounts

Use strong or unique passwords that are easily assumed, such as ‘123456’ or ‘password1234’ to protect your accounts. Give strong and complex passwords formed by combinations of alphabets, numeric, and not easily bypassed symbols.

Also, change passwords for multiple accounts and change them regularly to avoid attacks. We can also set several attempts to wrong passwords to set locking the account to safeguard from the hackers.

5. Do not use Public WI-FI Networks

Are you try to keep an eye on your IoT devices through your mobile devices in different locations. I recommend you not to use the public WI-FI network to access them. Because they are easily accessible through for everyone, you are still in a hurry to access, use VPN that gives them protection against cyber-attacks, giving them privacy and security features, for example, using Express VPN.

6. Establish firewalls to discover the vulnerabilities

There are software and firewalls like intrusion detection system/intrusion prevention system in the market. This will be useful to screen and analyze the wire traffic of a network. You can identify the security weakness by the firewall scanners within the network structure. Use these firewalls to get rid of unwanted security issues and vulnerabilities.

7. Reconfigure your device settings

Every smart device comes with the insecure default settings, and sometimes we are not able to change these default settings configurations. These conditions need to be assessed and need to reconfigure the default settings.

8. Authenticate the IoT applications

Nowadays, every smart app offers authentication to secure the accounts. There are many types of authentication methods like single-factor authentication, two-step authentication, and multi-factor authentication. Use any one of these to send a one time password (OTP) to verify the user who logs in the smart device to keep our accounts from falling into the wrong hands.

9. Update the device software up to date

Every smart device manufacturer releases updates to fix bugs in their software. These security patches help us to improve our protection of the device. Also, update the software on the smartphone, which we are used to monitoring the IoT devices to avoid vulnerabilities.

10. Track the smartphones and keep them safe

When we connect the smart home to the smartphone and control them via smartphone, you need to keep them safe. If you miss the phone almost, every personal information is at risk to the cybercriminals. But sometimes it happens by accident, makes sure that you can clear all the data remotely.

However, securing smart devices is essential in the world of data. There are still cybercriminals bypassing the securities. So make sure to do the safety measures to avoid our accounts falling out into the wrong hands. I hope these steps will help you all to secure your IoT devices.

If you have any, feel free to share them in the comments! I’d love to know them.

Are you looking for more? Subscribe to weekly newsletters that can help your stay updated IoT application developments.

#iot #enterprise iot security #how iot can be used to enhance security #how to improve iot security #how to protect iot devices from hackers #how to secure iot devices #iot security #iot security devices #iot security offerings #iot security technologies iot security plus #iot vulnerable devices #risk based iot security program

Lokesh Kumar

1603438098

Top 10 Trending Technologies Must Learn in 2021 | igmGuru

Technology has taken a place of more productiveness and give the best to the world. In the current situation, everything is done through the technical process, you don’t have to bother about doing task, everything will be done automatically.This is an article which has some important technologies which are new in the market are explained according to the career preferences. So let’s have a look into the top trending technologies followed in 2021 and its impression in the coming future in the world.

  1. Data Science
    First in the list of newest technologies is surprisingly Data Science. Data Science is the automation that helps to be reasonable for complicated data. The data is produces in a very large amount every day by several companies which comprise sales data, customer profile information, server data, business data, and financial structures. Almost all of the data which is in the form of big data is very indeterminate. The character of a data scientist is to convert the indeterminate datasets into determinate datasets. Then these structured data will examine to recognize trends and patterns. These trends and patterns are beneficial to understand the company’s business performance, customer retention, and how they can be enhanced.

  2. DevOps
    Next one is DevOps, This technology is a mixture of two different things and they are development (Dev) and operations (Ops). This process and technology provide value to their customers in a continuous manner. This technology plays an important role in different aspects and they can be- IT operations, development, security, quality, and engineering to synchronize and cooperate to develop the best and more definitive products. By embracing a culture of DevOps with creative tools and techniques, because through that company will gain the capacity to preferable comeback to consumer requirement, expand the confidence in the request they construct, and accomplish business goals faster. This makes DevOps come into the top 10 trending technologies.

  3. Machine learning
    Next one is Machine learning which is constantly established in all the categories of companies or industries, generating a high command for skilled professionals. The machine learning retailing business is looking forward to enlarging to $8.81 billion by 2022. Machine learning practices is basically use for data mining, data analytics, and pattern recognition. In today’s scenario, Machine learning has its own reputed place in the industry. This makes machine learning come into the top 10 trending technologies. Get the best machine learning course and make yourself future-ready.

To want to know more click on Top 10 Trending Technologies in 2021

You may also read more blogs mentioned below

How to Become a Salesforce Developer

Python VS R Programming

The Scope of Hadoop and Big Data in 2021

#top trending technologies #top 10 trending technologies #top 10 trending technologies in 2021 #top trending technologies in 2021 #top 5 trending technologies in 2021 #top 5 trending technologies

Brain  Crist

Brain Crist

1597266000

OWASP TOP 10 API Security Part 2 (Broken Object Level Authorization)

In the previous article, we had them build our ground around OWASP’s top ten projects and covered the brief official definition of OWASP Top 10 for API security.

In this article, we will explore the first of the OWASP Top 10 API security risks for the year 2019. (API1:2019 - Broken object-level authorization).

Context

In most of the API implementations, where we have to get some data which is specific to some object, Reference of the internal object implementation is exposed, for example: “id”, “pid”, “uid” and so on. Although in most cases this reference is visible as part of the HTTP parameter itself, but these could also be part of headers and cookies.

The problem here is that it reveals the real identifier and format/pattern used of the element in the storage backend side. The most common example of it (although is not limited to this one) is a record identifier in a storage system (database or filesystem).

Once the pattern is identified, the malicious user can easily guess/autogenerate the reference ID’s and modify the requests to supply the reference ID’s that do not belong to them.

If the API implementation does not have proper measures in place, then these malicious requests can cause revelations, modifications, or even deletion of records in the backend.

Just because the direct object reference checks were not in place or misconfigured. That is the reason this attack is also known as Insecure Direct Object Reference or IDOR in short.

Use Case

Let us assume that we have an API implementation that gets the financial information of a user. And to get the details the API expects the user id as parameter.

  1. API call parameters use the ID of the resource accessed through the API /API/user1/financial_info.
  2. By proxying and intercepting the URL’s attacker can guess the format of the parameter (user1).
  3. Attackers replace the IDs of their resources with a different one which they guessed through /API/user2/financial_info.
  4. As there is no measure to check the check permissions, the API returns data for user2. Which, it should not have.
  5. This could cause further issues if IDs can be enumerated and calls are automated to scrape though the data available with the UI /api/{AUTOMATED_USER_ID_HERE}/financial_info.

api users

How to Prevent it

If we have to summarize then we can say, IDOR is a combination of two issues

  1. Enumerable identifiers, which could easily be guessed.
  2. Insufficient checking of access rights on the requests.

So, the solution to prevent IDOR completely has to address both the issues, Below are some of the recommendations.

  • API should verify that the current user has permission to access the object, every time access is attempted. For example, if a user has access to record 3 and no others, any attempt to access record 4 should be rejected.
  • The API should validate both read and write requests, it should not be the case that a user can write to a record, even without having the read permission to it, such scenarios may allow the further compromise of the system. For example, if a PUT request made to /data/1 contains a sensitive value, it is important to check that the same PUT request cannot be made to /data/2, even if it is known that GET /data/2 is rejected.
  • Implement authorization checks with user policies and hierarchy.
  • Do not rely on IDs that the client sends. Use IDs stored in the session object instead.
  • Check authorization for each client request to access the database.
  • Use random IDs that cannot be guessed (UUIDs).
  • idor preventionIDOR Prevention

Sample Application

As we saw earlier that our solution has to address both the Access and predictable ID issue. Let us try to build an application to demonstrates the same. Please be advised that this application is meant for demonstration purposes only.

So, our hypothetical application has a requirement that the users shall be able to get his data (e.g. financial details). Now, the API design could take user-id as input and serve returns the financial details belonging to the user. The common implementation approach for the API will be to have the user id as path parameters or as part of headers. Let’s say we choose the path parameter. Then our API will look something like this. And it works as expected.

PowerShell

1

http://localhost:9999/getdata-IDOR-vulnerable/user_2

But by analyzing the request we can see that the input is user_1, what if we supply **user_2? **

PowerShell

1

http://localhost:9999/getdata-IDOR-vulnerable/user_2

Voila! it works again. Thus, it is clear that **user_x ** is a reference to internal ID. Now, what if we somehow automate this parameter using some tool, or even simple programming? We can get the data of all the users available in the system.

PowerShell

1

http://localhost:9999/getdata-IDOR-vulnerable/user_2

2

http://localhost:9999/getdata-IDOR-vulnerable/user_3

3

http://localhost:9999/getdata-IDOR-vulnerable/user_4

4

.

5

.

6

.

7

http://localhost:9999/getdata-IDOR-vulnerable/user_N

We leaked all the data just because someone was able to guess the reference ID.

So, what if we use something difficult or random to guess? We solve one part of our problem.

One of the possible ways could be that we use these complex ID’s (something like UUID) in our backend system, or we can wrap our data fetch logic around some utility class or filter which does this job for each request. In a very basic example, we could write something like below.

Java

1

package org.sk.owasp.api.security.idor.util;

2

3

import java.util.Base64;

4

import org.springframework.stereotype.Service;

5

/**

6

 * <strong>FOR DEMONSTRATION ONLY, NOT TO BE USED IN PRODUCTION.</strong><br>

7

 * As this code is for demonstration purpose only. {@link Base64} is used to encypt-decrypt the ID's. This algorithm is not considered safe and can be

8

 * decoded easily. 

9

 * In real world scenario you shall be using more sophisticated algorithms or something like UUID

10

 *  Access check in intentionaly left from the code.

11

 * @author Satish Sharma

12

 *

13

 */

14

@Service

15

public class IdorUtility {

16

17

    // this could be externalized to configuration.

18

    private String saltString="S3cUr#d1Ds1L$";

19

20

    public String computeObfuscatedId(String actualIdentifier) {

21

        String saltedString = actualIdentifier + saltString;

22

        return new String(Base64.getEncoder().encode(saltedString.getBytes()));

23

    }

24

25

    public String resolveObfuscatedId(String obfuscatedIdentifier) {

26

        var decodedBit = Base64.getDecoder().decode(obfuscatedIdentifier);

27

        String decodedSaltedString = new String(decodedBit);

28

        return decodedSaltedString.replace(saltString, "");

29

    }

30

}

Once we wrap our service call around the encode-decode utility class. As we have encoded all the identifiers with Base64, The API request will change something like below. Notice the change in the path parameter in the URL.

PowerShell

1

http://localhost:9999/getdata-IDOR-secured/dXNlcl8zUzNjVXIjZDFEczFMJA%3D%3D

As we can see now the IDs cannot be guessed easily. Combined the above code with authorization mechanism (left intentionally from this code). We address both the issues, and hence prevent the IDOR.

You can find the sample spring-boot application at this GitHub location. In the next article, we shall be addressing **API2:2019 Broken User Authentication. **

Thank you for reading. If any questions or comments please share them, I would be happy to hear.

#security #spring boot 2 #owasp top 10 #api penetration testing #owasp top 10 web security risk #broken api

Edward Jackson

Edward Jackson

1559182487

Top 10 npm Security Best Practices

10 npm Security Best Practices. Avoid publishing secrets to the npm registry. Enforce the lockfile. Assess npm project health. Audit for vulnerabilities in open source dependencies. Use a local npm proxy. Responsibly disclose security vulnerabilities. Enable 2FA. Use npm author tokens.

Concerned about npm vulnerabilities? It is important to take npm security into account for both frontend, and backend developers. Open source security auditing is a crucial part of shifting security to the left, and npm package security should be a top concern, as we see that even the official npm command line tool has been found to be vulnerable.

In this cheat sheet edition, we’re going to focus on npm security and productivity tips for both open source maintainers and developers. So let’s get started with our list of 10 npm security best practices, starting with a classic mistake: people adding their passwords to the npm packages they publish!

DOWNLOAD THE CHEAT SHEET!


1. Avoid publishing secrets to the npm registry

Whether you’re making use of API keys, passwords or other secrets, they can very easily end up leaking into source control or even a published package on the public npm registry. You may have secrets in your working directory in designated files such as a .env which should be added to a .gitignore to avoid committing it to a SCM, but what happen when you publish an npm package from the project’s directory?

The npm CLI packs up a project into a tar archive (tarball) in order to push it to the registry. The following criteria determine which files and directories are added to the tarball:

  • If there is either a .gitignore or a .npmignore file, the contents of the file are used as an ignore pattern when preparing the package for publication.
  • If both ignore files exist, everything not located in .npmignore is published to the registry. This condition is a common source of confusion and is a problem that can lead to leaking secrets. Developers may end up updating the .gitignore file, but forget to update .npmignore as well, which can lead to a potentially sensitive file not being pushed to source control, but still being included in the npm package.

Another good practice to adopt is making use of the files property in package.json, which works as a whitelist and specifies the array of files to be included in the package that is to be created and installed (while the ignore file functions as a blacklist). The files property and an ignore file can both be used together to determine which files should explicitly be included, as well as excluded, from the package. When using both, the former the files property in package.json takes precedence over the ignore file.

When a package is published, the npm CLI will verbosely display the archive being created. To be extra careful, add a --dry-run argument to your publish command in order to first review how the tarball is created without actually publishing it to the registry.

In January 2019, npm shared on their blog that they added a mechanism that automatically revokes a token if they detect that one has been published with a package.


2. Enforce the lockfile

We embraced the birth of package lockfiles with open arms, which introduced: deterministic installations across different environments, and enforced dependency expectations across team collaboration. Life is good! Or so I thought… what would have happened had I slipped a change into the project’s package.json file but had forgotten to commit the lockfile along side of it?

Both Yarn, and npm act the same during dependency installation . When they detect an inconsistency between the project’s package.json and the lockfile, they compensate for such change based on the package.json manifest by installing different versions than those that were recorded in the lockfile.

This kind of situation can be hazardous for build and production environments as they could pull in unintended package versions and render the entire benefit of a lockfile futile.

Luckily, there is a way to tell both Yarn and npm to adhere to a specified set of dependencies and their versions by referencing them from the lockfile. Any inconsistency will abort the installation. The command line should read as follows:

  • If you’re using Yarn, run yarn install --frozen-lockfile.
  • If you’re using npm run npm ci.

3.Minimize attack surfaces by ignoring run-scripts

The npm CLI works with package run-scripts. If you’ve ever run npm start or npm test then you’ve used package run-scripts too. The npm CLI builds on scripts that a package can declare, and allows packages to define scripts to run at specific entry points during the package’s installation in a project. For example, some of these script hook entries may be postinstall scripts that a package that is being installed will execute in order to perform housekeeping chores.

With this capability, bad actors may create or alter packages to perform malicious acts by running any arbitrary command when their package is installed. A couple of cases where we’ve seen this already happening is the popular eslint-scope incident that harvested npm tokens, and the crossenv incident, along with 36 other packages that abused a typosquatting attack on the npm registry.

Apply these best practices in order to minimize the malicious module attack surface:

Always vet and perform due-diligence on third-party modules that you install in order to confirm their health and credibility.

  • Hold-off on upgrading blindly to new versions; allow new package versions some time to circulate before trying them out.
  • Before upgrading, make sure to review changelog and release notes for the upgraded version.
  • When installing packages make sure to add the --ignore-scripts suffix to disable the execution of any scripts by third-party packages.
  • Consider adding ignore-scripts to your .npmrc project file, or to your global npm configuration.

4. Assess npm project health

Outdated dependencies

Rushing to constantly upgrade dependencies to their latest releases is not necessarily a good practice if it is done without reviewing release notes, the code changes, and generally testing new upgrades in a comprehensive manner. With that said, staying out of date and not upgrading at all, or after a long time, is a source for trouble as well.

The npm CLI can provide information about the freshness of dependencies you use with regards to their semantic versioning offset. By running npm outdated, you can see which packages are out of date:

Dependencies in yellow correspond to the semantic versioning as specified in the package.json manifest, and dependencies colored in red mean that there’s an update available. Furthermore, the output also shows the latest version for each dependency.


Call the doctor

Between the variety of Node.js package managers, and different versions of Node.js you may have installed in your path, how do you verify a healthy npm installation and working environment? Whether you’re working with the npm CLI in a development environment or within a CI, it is important to assess that everything is working as expected.

Call the doctor! The npm CLI incorporates a health assessment tool to diagnose your environment for a well-working npm interaction. Run npm doctor to review your npm setup:

  • Check the official npm registry is reachable, and display the currently configured registry.
  • Check that Git is available.
  • Review installed npm and Node.js versions.
  • Run permission checks on the various folders such as the local and global node_modules, and on the folder used for package cache.
  • Check the local npm module cache for checksum correctness.

5. Audit for vulnerabilities in open source dependencies

The npm ecosystem is the single largest repository of application libraries amongst all the other language ecosystems. The registry and the libraries in it are at the core for JavaScript developers as they are able to leverage work that others have already built and incorporate it into their code-base. With that said, the increasing adoption of open source libraries in applications brings with it an increased risk of introducing security vulnerabilities.

Many popular npm packages have been found to be vulnerable and may carry a significant risk without proper security auditing of your project’s dependencies. Some examples are npm request, superagent, mongoose, and even security-related packages like jsonwebtoken, and npm validator.

Security doesn’t end by just scanning for security vulnerabilities when installing a package but should also be streamlined with developer workflows to be effectively adopted throughout the entire lifecycle of software development, and monitored continuously when code is deployed.


Scan for vulnerabilities

Scanning for security vulnerabilities with Snyk, use:

$ npm install -g snyk
$ snyk test

When you run a Snyk test, Snyk reports the vulnerabilities it found and displays the vulnerable paths so you can track the dependency tree to understand which module introduced a vulnerability. Most importantly, Snyk provides you with actionable remediation advise so you can upgrade to a fixed version through an automated pull request that Snyk opens in your repository, or apply a patch that Snyk provides to mitigate the vulnerability if no fix is available. Snyk provides a smart upgrade by recommending the minimal semver-upgrade possible for the vulnerable package.


Monitor for vulnerabilities discovered in open source libraries

The security work doesn’t end there.

What about security vulnerabilities found in an application’s dependency after the application has been deployed? That’s where the importance of security monitoring and tight integration with the project’s development lifecycle comes in.

We recommend integrating Snyk with your source code management (SCM) system such as GitHub or GitLab so that Snyk actively monitors your projects and:

  • Automatically open PRs to upgrade or patch vulnerable dependencies for you
  • Scan and detect vulnerabilities in open source libraries that a pull request may have introduced

If you can’t integrate Snyk with an SCM, it is possible to monitor snapshots of your projects as sent from the Snyk CLI tool as well, by simply running:

$ snyk monitor

How is Snyk different from npm audit?

  1. We invite you to review a blog post published by Nearform which  compares the differences between npm’s audit and Snyk
  2. Snyk’s vulnerability database offers comprehensive data about vulnerabilities through its threat intelligence system. Providing better coverage and being able to surface and report vulnerabilities that have not yet received a CVE. For example, 72% of the vulnerabilities in npm’s advisories were added first to the Snyk database. See more on this here: https://snyk.io/features/vulnerabilitiy-database/

6. Use a local npm proxy

The npm registry is the biggest collection of packages that is available for all JavaScript developers and is also the home of the most of the Open Source projects for web developers. But sometimes you might have different needs in terms of security, deployments or performance. When this is true, npm allows you to switch to a different registry:

When you run npm install, it automatically starts a communication with the main registry to resolve all your dependencies; if you wish to use a different registry, that too is pretty straightforward:

  1. Set npm set registry to set up a default registry.
  2. Use the argument –registry for one single registry.

Verdaccio is a simple lightweight zero-config-required private registry and installing it is as simple as follows:

$ npm install --global verdaccio

Hosting your own registry was never so easy! Let’s check the most important features of this tool:

  • It supports the npm registry format including private package features, scope support, package access control and authenticated users in the web interface.
  • It provides capabilities to hook remote registries and the power to route each dependency to different registries and caching tarballs. To reduce duplicate downloads and save bandwidth in your local development and CI servers, you should proxy all dependencies.
  • As an authentication provider by default, it uses an htpasswd security, but also supports Gitlab, Bitbucket, LDAP. You can also use your own.
  • It’s easy to scale using a different storage provider.
  • If your project is based in Docker, using the official image is the best choice.
  • It enables really fast bootstrap for testing environments, and is handy for testing big mono-repos projects.

It is fairly simple to run:

$ verdaccio --config /path/config --listen 5000

If you use verdaccio for a local private registry, consider having a configuration for your packages to enforce publishing to the local registry and avoid accidental publishing by developers to a public registry. To achieve this add the following to package.json:

“publishConfig”: {
 “registry”: “https://localhost:5000
}

Your registry is running—ya !! Now, to publish a package just use the npm command npm publish and it is ready for you to share it with the world.


7. Responsibly disclose security vulnerabilities

When security vulnerabilities are found, they pose a potentially serious threat if publicly disclosed without prior warning or appropriate mitigation available for users to protect themselves.

It is recommended that security researchers follow a responsible disclosure program, which is a set of processes and guidelines that aims to connect the researchers with the vendor or maintainer of the vulnerable asset, in order to convey the vulnerability, it’s impact and applicability. Once the vulnerability is correctly triaged, the vendor and researcher coordinate a fix and a publication date for the vulnerability in an effort to provide an upgrade-path or remediation for affected users before the security issue is made public.

Security is too important to be an afterthought or handled unethically. At Snyk, we deeply value the security community and believe that a responsible disclosure of security vulnerabilities in open source packages helps us ensure the security and privacy of the users.

Snyk’s security research team regularly collaborates with the community for bug bounties, such as the case with f2e-server that resulted in hundreds of community disclosures, as well as Snyk’s very close partnership with academic researchers such as Virginia Tech to provide security expertise and the ability to coordinate with vendors and community maintainers.

We invite you to collaborate with us and offer our help with the disclosure process:

8. Enable 2FA

In October 2017, npm officially announced support for two-factor authentication (2FA) for developers using the npm registry to host their closed and open source packages.

Even though 2FA has been supported on the npm registry for a while now, it seems to be slowly adopted with one example being the eslint-scope incident in mid-2018 when a stolen developer account on the ESLint team lead to a malicious version of eslint-scope being published by bad actors.

** URGENT SECURITY WARNING ** Please share.

Today, version 3.7.2 of eslint-scope (https://t.co/Gkc9XhDRN6) was found to contain malicious code that steals your NPM credentials. Take action now if you are using version 3.7.2.

Snyk DB entry: https://t.co/dAhhA3cZQP
— Snyk (@snyksec) July 12, 2018

The registry supports two modes for enabling 2FA in a user’s account:

  • Authorization-only—when a user logs in to npm via the website or the CLI, or performs other sets of actions such as changing profile information.
  • Authorization and write-mode—profile and log-in actions, as well as write actions such as managing tokens and packages, and minor support for team and package visibility information.

Equip yourself with an authentication application, such as Google Authentication, which you can install on a mobile device, and you’re ready to get started. One easy way to get started with the 2FA extended protection for your account is through npm’s user interface, which allows enabling it very easily. If you’re a command line person, it’s also easy to enable 2FA when using a supported npm client version (>=5.5.1):

$ npm profile enable-2fa auth-and-writes

Follow the command line instructions to enable 2FA, and to save emergency authentication codes. If you wish to enable 2FA mode for login and profile changes only, you may replace the auth-and-writes with auth-only in the code as it appears above.


9. Use npm author tokens

Every time you log in with the npm CLI, a token is generated for your user and authenticates you to the npm registry. Tokens make it easy to perform npm registry-related actions during CI and automated procedures, such as accessing private modules on the registry or publishing new versions from a build step.

Tokens can be managed through the npm registry website, as well as using the npm command line client. An example of using the CLI to create a read-only token that is restricted to a specific IPv4 address range is as follows:

$ npm token create --read-only --cidr=192.0.2.0/24

To verify which tokens are created for your user or to revoke tokens in cases of emergency, you can use npm token list or npm token revoke respectively.


10. Understand module naming conventions and typosquatting attacks

Naming a module is the first thing you might do when creating a package, but before defining a final name, npm defines some rules that a package name must follow:

  • It is limited to 214 characters
  • It cannot start with dot or underscore
  • No uppercase letters in the name
  • No trailing spaces
  • Only lowercase
  • Some special characters are not allowed: “~\’!()*”)’
  • Can’t start with . or _
  • Can’t use node_modules or favicon.ico due are banned

Even if you follow these rules, be aware that npm uses a spam detection mechanism when publishing new packages, based on score and whether a package name violates the terms of the service. If conditions are violated, the registry might deny the request.

Typosquatting is an attack that relies on mistakes made by users, such as typos. With typosquatting, bad actors could publish malicious modules to the npm registry with names that look much like existing popular modules.

We have been tracking tens of malicious packages in the npm ecosystem; they have been seen on the PyPi Python registry as well. Perhaps some of the most popular incidents have been for cross-env, event-stream, and eslint-scope.

One of the main targets for typosquatting attacks are the user credentials, since any package has access to environment variables via the global variable process.env. Other examples we’ve seen in the past include the case with event-stream, where the attack targeted developers in the hopes of injecting malicious code into an application’s source code.

To reduce the risk of such attacks you might do the following:

  • Be extra-careful when copy-pasting package installation instructions into the terminal. Make sure to verify in the source code repository as well as on the npm registry that this is indeed the package you are intending to install. You might verify the metadata of the package with npm info to fetch more information about contributors and latest versions.
  • Default to having an npm logged-out user in your daily work routines so your credentials won’t be the weak spot that would lead to easily compromising your account.
  • When installing packages, append the –ignore-scripts to reduce the risk of arbitrary command execution. For example: npm install my-malicious-package --ignore-scripts

DOWNLOAD THE CHEAT SHEET!

Be sure to print out the cheat sheet and pin it up somewhere to remind you of some of the npm security best practices you should follow if you’re a javascript developer, or just enjoy using npm for fun.


Learn More

10 Node Frameworks to Use in 2019

Machine Learning In Node.js With TensorFlow.js

Full Stack Developers: Everything You Need to Know

MEAN Stack Tutorial MongoDB, ExpressJS, AngularJS and NodeJS

Build a web scraper with Node

Originally published by Liran Tal, Juan Picado at https://snyk.io

#npm #node-js #security