Beware of QR Code Scams with Python
In an era dominated by smartphones and contactless technology, QR codes have become a ubiquitous part of our daily lives. They’re found everywhere, from restaurant menus to advertising materials, offering quick and convenient ways to access information. However, this convenience has also given rise to a new threat: QR code scams.
What is a QR Code Scam?
A QR code scam involves criminals replacing legitimate QR codes with malicious ones, leading unsuspecting individuals to fake websites or applications designed to steal personal information or commit financial fraud. These scams are an emerging digital threat, and it’s essential to stay vigilant to protect yourself in the digital age.
How Do QR Code Scams Work?
QR code scams operate through various tactics, including:
- Malicious Redirects: Scammers place their QR codes over legitimate ones, redirecting users to fraudulent websites. Victims may unknowingly enter sensitive information, such as passwords or credit card details, which the scammers can exploit.
- App Downloads: Some QR code scams prompt users to download seemingly harmless apps. These apps may contain malware that can compromise your device’s security and steal data.
- Phishing Attacks: Scammers use fake QR codes to mimic trusted brands, luring users into entering personal information. Once obtained, this data can be used for identity theft or other fraudulent activities.
- Fake Promotions: QR codes advertising attractive discounts or giveaways can lead to fake surveys or contests designed to collect your personal information.
Protecting Yourself Against QR Code Scams
To safeguard yourself from QR code scams, follow these essential steps:
- Verify the Source: Only scan QR codes from trusted sources. Double-check the source of the QR code to ensure it’s legitimate, especially when it involves sensitive data or financial transactions.
- Inspect the URL: Before entering any personal information, look at the URL of the website you’re redirected to. Ensure it’s the official website of the service or business in question.
- Use a QR Code Scanner: Instead of using generic QR code scanners, consider downloading a reputable QR code scanner app. These apps often have built-in security features to detect malicious codes.
- Stay Informed: Keep up with the latest scams and threats in the digital world. Knowledge is a powerful defense against falling victim to these schemes.
- Report Suspicious Activity: If you come across a QR code that looks suspicious, report it to the relevant authorities or the business involved. This can help prevent others from becoming victims.
- Regularly Update Your Devices: Ensure your smartphone and other devices are up to date with the latest security patches and updates to mitigate the risk of malware infiltration.
Python Code
import requests
import json
from pyzbar.pyzbar import decode
from PIL import Image
import base64
import validators
# Function to check if the URL is safe
def is_url_safe(json_data):
data = json.loads(json_data)
categories = data['data']['attributes']['last_analysis_stats']
# Calculate the total of categories other than "harmless"
total_other_categories = sum(value for key, value in categories.items() if key != "harmless")
# Get the count of "harmless"
harmless_count = categories["harmless"]
# Check if the total of other categories is lower than "harmless"
return harmless_count > total_other_categories
# Function to read QR code from an image file and assign it to url_to_check
def read_qr_code_image(image_path):
try:
# Open the image using Pillow
image = Image.open(image_path)
# Decode QR code from the image using pyzbar
decoded_objects = decode(image)
# Check if any QR code was detected
if decoded_objects:
# Get the URL from the QR code
qr_code_url = decoded_objects[0].data.decode('utf-8')
return qr_code_url
else:
return None
except Exception as e:
print(f"Error reading QR code from image: {e}")
return None
# Function to get the redirected URL
def get_redirected_url(url):
try:
while True:
response = requests.head(url, allow_redirects=True)
history = response.__dict__['history'] or None
if history:
url = history[-1].headers['Location']
else:
return url
except Exception as e:
print(f"Error getting redirected URL: {e}")
return None
# Specify the path to the image containing the QR code
qr_code_image_path = "path_to_qr_code_image.png"
# Read the QR code from the image and assign it to url_to_check
url_to_check = read_qr_code_image(qr_code_image_path)
if validators.url(url_to_check):
redirected_url = get_redirected_url(url_to_check)
if redirected_url:
url_to_check = redirected_url
url_id = base64.urlsafe_b64encode(url_to_check.encode()).decode().strip("=")
else:
url_id = None
print("No valid QR code found in the image.")
if url_id:
url = f"https://www.virustotal.com/api/v3/urls/{url_id}"
headers = {
"accept": "application/json",
"x-apikey": "get your api key from virus total"
}
response = requests.get(url, headers=headers)
# Check if the request was successful
if response.status_code == 200:
# Get the JSON data from the response
json_data = response.json()
# Check if the URL is safe using the updated function
result = is_url_safe(json.dumps(json_data))
if result:
print(f"The URL {url_to_check} is safe.")
else:
print(f"The URL {url_to_check} is not safe.")
else:
print("Request failed with status code:", response.status_code)
else:
print("No valid QR code found in the image.")
QR codes have undeniably simplified access to information, but they’ve also provided cybercriminals with new opportunities to exploit unsuspecting individuals. By staying vigilant and taking steps to protect yourself, you can continue to enjoy the benefits of QR codes while avoiding potential scams in the digital age.