Ошибка decryption failed or bad record mac

Introduction

When working remotely and using NPM to install packages, I occasionally come across connectivity issues. These issues can be of SSL errors.

Recently when I was creating new React app, I came across the error:

ERR_SSL_DECRYPTION_FAILED_OR_BAD_RECORD_MAC

This happened when I ran the command:

npx create-react-app first-app

A more verbose error log looks like the following:

npx create-react-app first-app

Installing packages. This might take a couple of minutes.
Installing react, react-dom, and react-scripts with cra-template...

npm ERR! code ERR_SSL_DECRYPTION_FAILED_OR_BAD_RECORD_MAC
npm ERR! 10104:error:1408F119:SSL routines:ssl3_get_record:decryption failed or bad record mac:c:\ws\deps\openssl\openssl\ssl\record\ssl3_record.c:677:
npm ERR!

npm ERR! A complete log of this run can be found in:

Similar issue on Windows Server 2016

If you are using Windows Server (specifically in my case, I was using 2016), a similar error might look something like this after you run a npm install

npm install
npm ERR! code ERR_SSL_WRONG_VERSION_NUMBER
npm ERR! 8160:error:1408F10B:SSL routines:ssl3_get_record:wrong version number:c:\ws\deps\openssl\openssl\ssl\record\ssl3_record.c:308:
npm ERR!

What does ERR_SSL_DECRYPTION_FAILED_OR_BAD_RECORD_MAC mean?

So what does this error ERR_SSL_DECRYPTION_FAILED_OR_BAD_RECORD_MAC mean anyway?

If you haven’t dealt with NPM before, this doesn’t really mean much and doesn’t tell you anyway to fix it!

“ERR_SSL_DECRYPTION_FAILED_OR_BAD_RECORD_MAC” is an SSL-related error that indicates an issue with the decryption of data or a mismatch in the message authentication code (MAC) during an SSL/TLS handshake.

This error may occur when you are trying to use npm install to download packages.

Steps to fix this error

  1. Check your network connection
  2. Make sure that there are no antivirus or firewall blocking NPM
  3. If you are behind a corporate proxy, make sure to check proxy settings
  4. Use the strict-ssl=false flag
  5. Remove cache, node_modules folder and package-lock.json and install again

1. Check your network connection

The first thing to test is to make sure that we have a stable connection.

There are two options we can go forward with. One is the Ping test — to test our connection stability, and the other is the internet speed test.

To do the Ping Test:

  1. Open the command prompt (Windows) or terminal (macOS/Linux) and run the following command:

The -t flag is mainly for Windows and tells the command to run continuously until cancelled by the user (using Ctrl + C).

If you are on macOS and Linux, the ping command runs continuously by default, so you don’t need a -t flag.
To stop the ping process on macOS and Linux, press CTRL + C.

If you have a stable internet connection, you will see a consistent reply from google and with no packet loss errors:

Pinging google.com [142.250.66.238] with 32 bytes of data:
Reply from 142.250.66.238: bytes=32 time=27ms TTL=117
Reply from 142.250.66.238: bytes=32 time=14ms TTL=117
Reply from 142.250.66.238: bytes=32 time=8ms TTL=117
Reply from 142.250.66.238: bytes=32 time=9ms TTL=117
Reply from 142.250.66.238: bytes=32 time=8ms TTL=117
Reply from 142.250.66.238: bytes=32 time=7ms TTL=117
Reply from 142.250.66.238: bytes=32 time=16ms TTL=117

The above results says displays a summary of the ping results, including the number of packets sent, received, lost, and the approximate round-trip times.

Now if you have a stable connection, the next thing to test is your internet speed:

Visit an online speed test website like speedtest.net, fast.com, or Google’s speed test. These services measure your download and upload speeds, as well as latency.

Run the test to see if the results are consistent with your internet plan — eg anything above 10 Megabits per second is good in my books.

Keep in mind that your connection can also depend on factors such as:

  • Your Wifi signal strength,
  • The number of people using the network — eg is someone downloading a large movie
  • Your hardware such as your router, modem or network interface card (NIC)

2. Make sure that there are no antivirus or firewall blocking NPM

One reason why SSL cert errors like ERR_SSL_DECRYPTION_FAILED_OR_BAD_RECORD_MAC comes up is that the firewall is blocking your node install.

To solve this problem, we just need to add a enable firewall rule for NodeJS.

On Windows:

  1. Search Windows Defender Firewall in the search bar.

  1. Go to Allow an app or feature through Windows Defender Firewall.

  1. Click on Change settings.

  1. Now look for the Node.js runtime (.exe), it should look like something below:

  1. Select/ check the Node application to allow it past the firewall. Choose between checking Public or Private (or both — depends on your network configuration).

  2. Click OK and hopefully the problem should have been fixed!

Help: I can’t see Node.js!

If you don’t have Node.js JavaScript Runtime in the list, you can following the below steps:

  1. Click on Allow another app button at the bottom of the popup window
  2. Click on Browse
  3. Find the location of your node.exe file. The default path: C:\Program Files\nodejs. If you have NVM installed, the path may be different. Click on Add after you found node.exe.
  4. Then go through step 1 onwards.

3. If you are behind a corporate proxy, make sure to check proxy settings

After we have cleared the existing proxy settings, we first need to make sure that we set the registry:

npm config set registry https://registry.npmjs.org/

Now set the new proxy settings with the following commands. Replace the proxyname with your corporate proxy URL.

npm config set proxy http://username:password@proxyname:8080

npm config set https-proxy http://username:password@proxyname:8080

Keep in mind that when you are using username and password, they need to be encoded. For example, if your password is: Welcome@12# then it will be like Welcome%4012%23.

Additionally, with your username, you may need to also include the domain name + username aswell.

For example, lets say we work at a company with domain BIGCORP and your username is johnnyweekend with password Welcome@12#, then your NPM proxy config might look something like this:

npm config set proxy http://bigcorp\\jonnyweekend:Welcome%4012%23@bigcorpproxy:8080

Tip: Check your corporate proxy settings and make sure that they are not blocking NPM registry

Check with your corporate network team that the proxy is not blocking the following URL: https://registry.npmjs.org

4. Use the strict-ssl=false flag

If you are unable to obtain the registry’s SSL certificate or are still experiencing issues after adding it to your trusted list, you can temporarily disable strict SSL checking by running the following command:

npm config set strict-ssl false

Note that disabling strict SSL checking can leave your system vulnerable to man-in-the-middle attacks, so it should only be used as a temporary workaround. Once you have resolved the SSL certificate issue, be sure to re-enable strict SSL checking by running:

npm config set strict-ssl true

5. Remove cache, node_modules folder and package-lock.json and install again

Tip: Try clear NPM cache

We can try running npm cache clear --force to clear the NPM cache.
If this does not work — proceed to step 2

  1. We need to delete the /node_modules with the following command (you might need to use sudo before each command):

rm -rf node_modules

  1. Delete package-lock.json file using the rm command:

rm -rf package-lock.json

  1. Install the dependencies using the following command:

npm install

Summary

In this post, I went over the issue of ERR_SSL_DECRYPTION_FAILED_OR_BAD_RECORD_MAC. This error usually means that we are using NPM to download the packages from the repository (eg https://registry.npmjs.org) there was an error at SSL/TLS handshake.

Specifically, the decryption of the required package data or a mismatch in the message authentication code (MAC) was failing.

This issue can be narrowed down to a few possibilities. Firstly it could be that you are not on a stable and fast connection, you have antivirus or a firewall block the connections. The other reason could be that you are behind a corporate proxy and that is messing up the SSL certs that should of been exchanged.

To fix this issue, we can try to reinstall everything, clearing the cache, using the strict-ssl=false NPM flag and verifying that we have a stable/fast connection and checking that no software is blocking our NPM calls.

The «SSL error Decryption failed or bad record mac» error occurs in Python when an encrypted SSL/TLS connection is being established and there is an issue with the SSL/TLS certificate or key. The error message suggests that the client could not successfully decrypt the encrypted data received from the server or that the data has been tampered with during transmission.

Method 1: Update Python Package

To fix the Python SSL error «Decryption failed or bad record mac», you can update the Python package. Here’s how you can do it:

Step 1: Check your current Python version

Before updating the Python package, check your current Python version using the following command:

import platform
print(platform.python_version())

Step 2: Update the Python package

You can update the Python package using the following command:

!pip install --upgrade python

Step 3: Verify the updated Python version

After updating the Python package, verify the updated Python version using the following command:

import platform
print(platform.python_version())

Step 4: Test your code

Now, you can test your code to see if the Python SSL error «Decryption failed or bad record mac» is fixed.

Here’s an example code that uses the requests library to make a HTTPS request:

import requests

response = requests.get("https://www.google.com")
print(response.content)

If the Python SSL error «Decryption failed or bad record mac» is fixed, you should see the content of the HTTPS response without any errors.

That’s it! By updating the Python package, you should be able to fix the Python SSL error «Decryption failed or bad record mac».

Method 2: Check SSL Certificate Configuration

If you’re encountering the Python SSL error «Decryption failed or bad record mac,» it may be due to an issue with the SSL certificate configuration. Here’s how you can check the SSL certificate configuration to resolve the issue:

Step 1: Import the required libraries

Step 2: Create an SSL context

context = ssl.create_default_context()

Step 3: Set the SSL context options

context.options |= ssl.OP_NO_TLSv1 | ssl.OP_NO_TLSv1_1

Step 4: Create a socket and connect to the server

s = socket.socket(socket.AF_INET, socket.SOCK_STREAM)
s.connect(('example.com', 443))

Step 5: Wrap the socket with the SSL context

ssl_socket = context.wrap_socket(s, server_hostname='example.com')

Step 6: Verify the SSL certificate

cert = ssl_socket.getpeercert()
if not cert:
    raise ssl.SSLError('Certificate not found')

Step 7: Print the SSL certificate details

By following these steps, you can check the SSL certificate configuration and resolve the Python SSL error «Decryption failed or bad record mac.»

Method 3: Disable Hostname Verification

If you are facing the Python SSL error «Decryption failed or bad record mac», you can try to fix it by disabling hostname verification. Here are the steps to do it:

Step 1: Import the required modules

import ssl
import urllib.request

Step 2: Create an SSL context with hostname verification disabled

context = ssl.create_default_context()
context.check_hostname = False
context.verify_mode = ssl.CERT_NONE

Step 3: Use the SSL context to make the HTTPS request

url = "https://example.com"
req = urllib.request.Request(url)
response = urllib.request.urlopen(req, context=context)

Here, we first create an SSL context with hostname verification disabled. Then, we use this context to make the HTTPS request using the urllib.request.urlopen() method.

Note that disabling hostname verification can be a security risk, as it makes your application vulnerable to man-in-the-middle attacks. Use it only if you are sure that the server you are connecting to is trustworthy.

I hope this helps you fix the Python SSL error «Decryption failed or bad record mac» with hostname verification disabled.

Method 4: Upgrade to the Latest OpenSSL Library

To fix the Python SSL error «Decryption failed or bad record mac», you can upgrade to the latest OpenSSL library. Here are the steps to do it:

  1. Check if OpenSSL is already installed on your system by running the following command in the terminal:

    If OpenSSL is not installed, you can download and install it from the official website.

  2. Upgrade OpenSSL to the latest version by running the following command:

    sudo apt-get update
    sudo apt-get install openssl
  3. Verify that OpenSSL has been upgraded by running the following command:

    The output should show the latest version of OpenSSL.

  4. Restart your Python application and check if the SSL error has been resolved.

Here is an example code that demonstrates how to use the upgraded OpenSSL library in Python:

import ssl
import urllib.request

context = ssl.SSLContext(ssl.PROTOCOL_TLSv1_2)
context.set_ciphers('HIGH:!DH:!aNULL')

url = 'https://www.example.com'
response = urllib.request.urlopen(url, context=context)

data = response.read()
print(data)

In this code, we create a SSL context with the upgraded OpenSSL library using the ssl.SSLContext method. We then set the ciphers to use with the context.set_ciphers method.

We make a request to an SSL-enabled website using the urllib.request.urlopen method and pass in the SSL context. We then read the response using the response.read method.

This should help you fix the Python SSL error «Decryption failed or bad record mac» by upgrading to the latest OpenSSL library.

I solved this finally on mac os

On terminal

cd /usr/local/include
sudo rm -R node
cd ../lib
sudo rm -R node_modules
cd ../bin
sudo rm -R node

to check that node doesn’t exist anymore
node -v

Goto https://github.com/nvm-sh/nvm
and use the installation. script to install nvm — node package manager

if you have bre installed on your compute
brew update

and update all other packages i.e openssl

Close terminal and restart the terminal

to check nvm is installed
command -v nvm

to install nodejs and npm again

THIS IS IMPORTANT

  1. Make sure you are on a strong 4g or 5g network, if not you might encounter error

nvm install —lts

After installation
You are good to go with other npm installation and global installation

You should use nvm and not the downloaded node version if you want to install packages globally as well.

I want to add an existing Git repository to GitLab using this command : git push -u origin --all but I got the following error message :

fatal: unable to access 'https://gitlab.com/Name/MyProject.git/': SSL read: error:1
SSL routines:SSL3_GET_RECORD:decryption failed or bad record mac, errno
0

Any idea why ?

  • git
  • ssl
  • gitlab

VonC's user avatar

VonC

1.3m530 gold badges4425 silver badges5266 bronze badges

asked Feb 17, 2017 at 20:30

Kivo's user avatar

KivoKivo

3858 silver badges25 bronze badges

1 Answer

Community's user avatar

answered Feb 18, 2017 at 1:12

VonC's user avatar

VonCVonC

1.3m530 gold badges4425 silver badges5266 bronze badges

1

  • Make sure to upgrade to the latest Git version first, to see if the error persists

    Feb 18, 2017 at 1:17

I have a python script which runs quite well on the windows server but throws an SSLError exception when running on Ubuntu 16.04.5.

I have used pygsheetsto connect to the google sheet.

import pygsheets
from oauth2client.service_account import ServiceAccountCredentials

scope = [
        'https://spreadsheets.google.com/feeds',
        'https://www.googleapis.com/auth/drive'
         ]

credentials01 = ServiceAccountCredentials.from_json_keyfile_name('creds01.json', scope)
credentials02 = ServiceAccountCredentials.from_json_keyfile_name('creds02.json', scope)

file01 = pygsheets.authorize(credentials=credentials01)
file02 = pygsheets.authorize(credentials=credentials02)
wb01 = file01.open('Database System 2')
wb02 = file02.open('Database System 2')

if __name__ == '__main__':
    manager = multiprocessing.Manager()
    output_dfs = manager.list()
    new_dfs_dict = manager.dict()
    for l in main_list:
        for i in range(0, len(l[0]), 5):
            processes = []
            ids_sublist = []
            for j in range(i, i + 5):
                try:
                    ids_sublist.append(l[0][j])
                except:
                    pass
            for ID in ids_sublist:
                processes.append(multiprocessing.Process(target=fetch_data, args=(ID, start_date, end_date, new_dfs_dict, output_dfs)))
            for p in processes:
                p.start()
            for p in processes:
                p.join()

        for ID in l[0]:
            if not l[1].empty:
                cols_list = list(l[2][ID].columns)
                cols_list.remove('Type')
                cols_list[1:1] = ['Type']
                l[2][ID] = l[2][ID][cols_list]
                l[2][ID].update(new_dfs_dict[ID])
                l[2][ID] = pd.merge(l[2][ID], new_dfs_dict[ID])
            else:
                l[2][ID] = new_dfs_dict[ID]
        ready_to_set_df = pd.DataFrame()
        for ID in l[2]:
            ready_to_set_df = pd.concat([ready_to_set_df, l[2][ID]], sort=False)
            output_sheet = wb01.worksheet_by_title(l[3])            
            output_sheet.clear()
            output_sheet.set_dataframe(ready_to_set_df.fillna(0), 'A1')

    output_df = pd.DataFrame(columns=bank_portal_data_header)
    for df in output_dfs:
        output_df = output_df.append(df)
    try:
        data_sheet = wb02.worksheet_by_title(end_date)
        data_df = data_sheet.get_as_df(has_header=True)
        output_df = data_df[bank_portal_data_header].append(output_df)
        output_df = output_df.drop_duplicates(keep=False)
        data_sheet.clear()
        data_sheet.set_dataframe(output_df, 'A1', copy_head=True)
    except:
        data_sheet = wb02.add_worksheet(end_date)
        data_sheet.set_dataframe(output_df, 'A1', copy_head=True)

It throws the SSLError at data_sheet.clear()

The strange part is the script runs wonderfully on the Windows Server. Thanks

Понравилась статья? Поделить с друзьями:
  • Ошибка deck на додж стратус
  • Ошибка df013 на рено дастер как устранить
  • Ошибка dde bmw e46
  • Ошибка decals wad
  • Ошибка df009 рено логан