Showing posts with label python. Show all posts
Showing posts with label python. Show all posts

Dec 13, 2022

Upgrade to Python 3.11 on Ubuntu 22.04 LTS

My Ubuntu 22.04 (WSL) comes with Python 3.10.6, and I need to upgrade it to 3.11 for a workshop. (More importantly is, it claims to be 10-60% faster than the previous 3.10. 😎

Here are the steps:

$ sudo add-apt-repository ppa:deadsnakes/ppa

$ sudo apt update  

$ sudo apt install python3.11-full

$ python3.11 --version
Python 3.11.1


Next. To set Python 3.11 as default.

$ sudo update-alternatives --install /usr/bin/python3 python3 /usr/bin/python3.10 110

$ sudo update-alternatives --install /usr/bin/python3 python3 /usr/bin/python3.11 100

$ sudo update-alternatives --config python3


Dec 11, 2022

Python-HTTPX Vs. Python-Requests

#!/usr/bin/evn python3 

# -*- coding: utf-8 -*-

import httpx

import requests

 

In general, both the module are similar, Here, I just make a simple comparison on what are the differences between Python HTTPX and Requests module.

 


Requests HTTPX
Sessions requests.Session() httpx.Client()
Async support
Not supported
httpx.AsyncClient()
HTTP/2 support
Not supported httpx.Client(http2=True)
httpx.AsyncClient(http2=True)


I have started moving over to HTTPX since Dec 2022.


Links:

Oct 30, 2022

wtfis

Found an interesting tool called wtfis.

wtfis is a commandline tool that gathers information about a domain, FQDN or IP address using various OSINT services. 

This tool assumes that you are using free tier / community level accounts, and so makes as few API calls as possible to minimize hitting quotas and rate limits.

Setup

wtfis uses these environment variables:

  • VT_API_KEY (required) - Virustotal API key
  • PT_API_KEY (optional) - Passivetotal API key
  • PT_API_USER (optional) - Passivetotal API user
  • SHODAN_API_KEY (optional) - Shodan API key

Installation

$ pip install wtfis

Usage:

$ wtfis -h
usage: wtfis [-h] [-m N] [-s] [-n] [-1] [-V] entity

positional arguments:
  entity                Hostname, domain or IP

options:
  -h, --help            show this help message and exit
  -m N, --max-resolutions N
                        Maximum number of resolutions to show (default: 3)
  -s, --use-shodan      Use Shodan to enrich IPs
  -n, --no-color        Show output without colors
  -1, --one-column      Display results in one column
  -V, --version         Print version number


Links:

Oct 25, 2022

MHDDoS - DDoS Attack Script

MHDDoS is a DDoS Attack Script written in Python3. It includes 56 attack methods (DoS/DDoS). 


Installation (1st way)

$ git clone https://github.com/MHProDev/MHDDoS.git
$ cd MHDDoS
$ pip install -r requirements.txt

 Installation (2nd way)

$ docker pull ghcr.io/mhprodev/mhddos:latest


Links:

Oct 9, 2022

Telegram MTProto API Framework

Pyrogram - Telegram MTProto API Framework for Python.

Pyrogram is a modern, elegant and asynchronous MTProto API framework. It enables you to easily interact with the main Telegram API through a user account (custom client) or a bot identity (bot API alternative) using Python. 

QuickStart

  1. Install Pyrogram with pip3 install -U pyrogram.
  2. Get your own Telegram API key from https://my.telegram.org/apps.
  3. Open the text editor of your choice and paste the following:
    1. import asyncio
      from pyrogram import Client 
      api_id = 12345
      api_hash = "0123456789abcdef0123456789abcdef" 
      async def main():
          async with Client("my_account", api_id, api_hash) as app:
              await app.send_message("me", "Greetings from **Pyrogram**!") 
      asyncio.run(main())
  4. Replace api_id and api_hash values with your own.
  5. Save the file as hello.py.
  6. Run the script with python3 hello.py
  7. Follow the instructions on your terminal to login.
  8. Watch Pyrogram send a message to yourself. 


Links:

Oct 5, 2022

Upgrade to Python 3.10 on Ubuntu 20.04 LTS

My Ubuntu 20.04 comes with Python 3.8.10, and I need to upgrade it to 3.10 for a workshop.

Here are the steps:

$ sudo add-apt-repository ppa:deadsnakes/ppa
$ sudo apt-get update

$ apt-get update

$ apt list | grep python3.10

$ sudo apt-get install python3.10

$ sudo update-alternatives --install /usr/bin/python3 python3 /usr/bin/python3.8 1
$ sudo update-alternatives --install /usr/bin/python3 python3 /usr/bin/python3.10 2

$ sudo update-alternatives --config python3

$ python3 -V

Sep 18, 2022

Attack Tools Collection

Here is a list of attacking tools collected recently.

AutoDeAuth - A tool built to automatically deauth local networks.

Aced - A tool to parse and resolve a single targeted Active Directory principal's DACL. will identify interesting inbound access allowed privileges against the targeted account, resolve the SIDS of the inbound permissions, and present that data to the operator. Additionally, the logging features of pyldapsearch have been integrated with Aced to log the targeted principal's LDAP attributes locally which can then be parsed by pyldapsearch's companion tool BOFHound to ingest the collected data into BloodHound.

Aura - A Python Source Code Auditing And Static Analysis On A Large Scale. It is a static analysis framework developed as a response to the ever-increasing threat of malicious packages and vulnerable code published on PyPI.

Coercer - A Python Script To Automatically Coerce A Windows Server To Authenticate On An Arbitrary Machine Through 9 Methods.

GraphCrawler - GraphQL Automated Security Testing Toolkit. It is the most powerful automated testing toolkit for any GraphQL endpoint. (Req: Python3, Docker Python dependencies)

pycvss3 - Python API for the CVSS v3.

Sep 6, 2022

ApacheTomcatScanner

ApacheTomcatScanner - A python script to scan for Apache Tomcat server vulnerabilities.

Features:

  • Multi-threaded workers to search for Apache tomcat servers.
  • Multiple target source possible:   
    • Retrieving list of computers from a Windows domain (through LDAP query)   
    • Reading targets line by line from a file.        
    • Reading individual targets (IP/DNS/CIDR) from -tt/--target option.    
  • Custom list of ports to test.    
  • Tests for /manager/html access and default credentials.    
  • List the CVEs of each version with the --list-cves option


Links:

Sep 1, 2022

Using Python in Power BI

Microsoft Power BI is a business analytics tool which allows users to gain insight from their data. User can easily create an interactive dashboard by just dragging and dropping data columns into the visualization plane.

In this article, Yannawut Kimnaruk will show you how to use Python to leverage the capabilities of Power BI.

What We'll Cover:    

  • How to install Python    
  • How to set up Python in Power BI    
  • How to use Python to get data    
  • How to use Python to transform data    
  • How to use Python to visualize data


Links:

Jul 21, 2022

Utils: rh_access.py

Just release a small util to query CVE released by Red Hat.


$ ./rh_access.py -e cve-2022-34484 cve-2022-29226 cve-2022-26354 -v

rh_access.py

Links:


Jul 6, 2022

SSLyze – Fast and powerful SSL/TLS scanning tool

SSLyze tool is an automated cyber security tool that is used to scan the target domain for SSL/TLS vulnerabilities like Heartbleed, OpenSSL, and many more. This tool is developed in the Python language and is also available on the GitHub platform.


Installation:

$ cd repo

$ git clone https://github.com/nabla-c0d3/sslyze.git

$ cd sslyze

$ sudo python3 setup.py install

$ sslyze -h

$ sslyze www.geeksforgeeks.org

 

Links:

May 27, 2022

Invert a Complex Dictionary in Python

Have you ever need to invert a dictionary with value being a list in Python?

Here is what I mean. We need to convert the following dict:

{ "apple"      : [ "green", "red" ], 

  "watermelon" : [ "green" ], 

  "strawberry" : [ "red" ], 

  "lemon"      : [ "green", "yellow" ] }

To a new dict as below:

{ 'green'  : ['apple', 'watermelon', 'lemon'], 

  'red'    : ['apple', 'strawberry'], 

  'yellow' : ['lemon'] } 


Here's my solution which using the defaultdict from collections:

>>> from collections import defaultdict

>>> a_dict = { "apple" : [ "green", "red" ], "watermelon" : [ "green" ], "strawberry" : [ "red" ], "lemon" : [ "green", "yellow" ] }

>>> b_dict = defaultdict(list)

>>> for k,v in a_dict.items():

...    for k1 in v:

...        b_dict[k1].append(k)

...

>>> b_dict

defaultdict(<class 'list'>, {'green': ['apple', 'watermelon', 'lemon'], 'red': ['apple', 'strawberry'], 'yellow': ['lemon']})


There is another way that simplies what we have above:

>>> from collections import defaultdict

>>> a_dict = { "apple" : [ "green", "red" ], "watermelon" : [ "green" ], "strawberry" : [ "red" ], "lemon" : [ "green", "yellow" ] }

>>> b_dict = defaultdict(list)

>>> { b_dict[k1].append(k) for k,v in a_dict.items() for k1 in v }

>>> b_dict


Alright, hope this helps!!

May 2, 2022

Python and GitHub Secrets

This is a simple note to show how to access GitHub Secrets with Python.

First, to add a new secret, go to GitHub repository > Settings > Secrets > New Repository Secret.

Second, define a Name ('SEC_NAME') and put in the Value.

 

Next, map them as environment variables in GitHub Actions Workflow.

....

    - name: Run tests

        env:

            API_KEY: ${{ secrets.SEC_NAME }}

        run:  |

....

 

Finally, refer to the env variable in Python script.

import os

API_KEY = os.environ['API_KEY']

....



Apr 21, 2022

Print Colors And Formatted Text in Terminal

This is my note on how to print formatted text and colors in terminal using Python. There are several methods to output colored text to terminal.

Terminal can be so plain. And formatted text (aka styled text or rich text) can be used as opposed to plan text, has styling info like:

  • color (text and background)
  • style (bold and italic)
  • others (strike-through, underline)

 

1. Using ANSI Escape Codes

ANSI escape codes are used to control the formatting and color in Linux terminal. To encode this formatting info, certain sequences of bytes are embedded into the text, which the terminal looks for and interprets as commands and executes them.

print('\x1b[3;31;43m' + 'Hello world!' + '\x1b[0m')

The python statement above will produce the output in "red" text-color, with "yellow" background, and "italic" style.

The general syntax is \x1b[A;B;C   and the first ANSI escape code used is  \x1b[3;31;43m  . The second ANSI escape code used is \x1b[0m , and this is the code used to reset the color/style to defaults values. 

A is for text formatting style, ranges from 1 to 9.

  • 1 : bold
  • 2 : faint
  • 3 : italic
  • 4 : underline
  • 5 : blinking
  • 6 : fast blinking
  • 7 : reverse
  • 8 : hide
  • 9 : strikethrough

B is for text color, ranges from 30 t0 37.

C is for background color, ranges from 40 to 47.

  • 30/40 : black
  • 31/41 : red
  • 32/42 : green
  • 33/43 : yellow
  • 34/44 : blue
  • 35/45 : magenta
  • 36/46 : cyan
  • 37/47 : white


2. Using built-in modules : colorama, termcolor

Example of using colorama

from colorama import init, Fore, Back, Style

init (autoreset=True, strip=False)

print(Fore.RED + + Back.GREEN + Style.DIM + f'Red text on Green in dim')

print(f'Normal')

 

Example of using termcolor

>>> from termcolor import colored
>>> print(colored('Hello, World!', 'green', 'on_red'))

A more complex example:

# Python program to print
# colored text and background
import sys
from termcolor import colored, cprint

text = colored('Hello, World!', 'red', attrs=['reverse', 'blink'])
print(text)
cprint('Hello, World!', 'green', 'on_red')

print_red_on_cyan = lambda x: cprint(x, 'red', 'on_cyan')
print_red_on_cyan('Hello, World!')
print_red_on_cyan('Hello, Universe!')

for i in range(10):
    cprint(i, 'magenta', end=' ')

cprint("Attention!", 'red', attrs=['bold'], file=sys.stderr)


Links

  • https://www.geeksforgeeks.org/print-colors-python-terminal/
  • https://www.geeksforgeeks.org/formatted-text-linux-terminal-using-python/


Apr 6, 2022

KEV Dashboard

Just finished KEV Dashboard today.

Here is another simple python script on creating simple dashboard for CISA's Known Exploited Vulnerabilitiy (KEV).

There are 2 modes, text-based (default) and simple chart-based.

Text-based dashboard

Simple chart-based dashboard

The code will be uploaded to Github soon.


Apr 5, 2022

Publish kev-catalog on GitHub

The cisa-alerts.py script has been renamed to kev-catalog.py and been published to GitHub today. Just download, setup and run the script.

$ git clone https://github.com/myseq/kev-catalog

$ cd kev-catalog/

$ pip3 install -r requirements.txt

$ python3 kev-catalog.py -v 


kev-catalog.py

Links:

Apr 4, 2022

Update on cisa-alerts.py

cisa-alerts.py

Update on 'cisa-alerts.py'. 

  • Search CVE within catalog.
  • Search string within catalog.
  • Specify the top N vendors and products.
  • Specify the last N days of CVE added to catalog.

 

cisa-alerts.py -e 2017-0143

cisa-alerts.py -s keep

cisa-alerts.py -l 4 -i 6


Links:

Apr 3, 2022

Display Images on Terminal

This is easy way to display images on a terminal using Python. The module is called climage and has the following features:

  • convert images to NASI Escape codes
  • allow 8/16/256 bit color codings
  • provide ASCII/Unicode support

Installation

$ pip install climage

Usage (in Python)

convert(filename, is_unicode=False, is_truecolor=False, is_256color=True, is_16color=False, is_8color=False, width=80, palette=”default”)

Parameters:
filename : Name of image file.
is_unicode :  If true, conversion is done in unicode format, otherwise ASCII characters will be used.
is_truecolor :  Whether to use RGB colors in generation, if supported by terminal. Defaults False.
is_256color : Whether to use 256 colors encoding. Defaults True.
is_16color : Whether to use 16 colors encoding. Defaults False.
is_8color : Whether to use first 8 System colors. Defaults False.
width : Number of blocks of console to be used. Defaults to 80.
palette : Sets mapping of RGB colors scheme to system colors. Options are : [“default”, “xterm”, “linuxconsole”, “solarized”, “rxvt”, “tango”, “gruvbox”, “gruvboxdark”]. Default is “default”.

 

to_file(infile, outfile, is_unicode=False, is_truecolor=False, is_256color=True, is_16color=False, is_8color=False, width=80, palette=”default”)

Parameters:
infile : The name/path of image file.
outfile :   File in which to store ANSI encoded string. 



Links:

  • https://www.geeksforgeeks.org/display-images-on-terminal-using-python/
  • https://pypi.org/project/climage/

Apr 2, 2022

Create Progress Bar in Terminal

This is easy way to create and show the progress bar in terminal using Python. This is useful for installation or loading a page. The module is called tqdm and it eases your mind with a small progress bar to show an estimation of a process.

Installation

$ pip install tqdm

Usage (in Python)

A simple example for testing

from tqdm import tqdm

 

for i in tqdm(range(int(9e6))):
    pass


Use a parameter to specify the description of progress bar.

from tqdm import tqdm
from time import sleep

for i in tqdm(range(0, 100), desc ="Loading"):
    sleep(.1)


To specify the total number of expected iterations.

from tqdm import tqdm
from time import sleep

for i in tqdm(range(0, 100), total = 500,desc ="Loading"):
    sleep(.1)


To specify the entire width.

from tqdm import tqdm
from time import sleep

for i in tqdm(range(0, 100), ncols = 100,
desc ="Loading"): 

    sleep(.1)


To specify the minimum progress display update (default is 0.1 seconds).

from tqdm import tqdm
from time import sleep

for i in tqdm(range(0, 100), mininterval = 3, desc ="Loading"):
    sleep(.1)


To fill the progress bar with ASCII characters.

from tqdm import tqdm
from time import sleep

for i in tqdm(range(0, 100), ascii ="123456789$"):
    sleep(.1)


Links:

  • https://www.geeksforgeeks.org/python-how-to-make-a-terminal-progress-bar-using-tqdm/
  • https://pypi.org/project/tqdm/

Apr 1, 2022

7 Newly Added Known Exploited Vulnerabilities

cisa-alerts.py
 

With the update of the cisa-alerts script today, it can now show the details of what's new in CISA's Known Exploited vulnerabilites JSON file.

There are 7 newly added Known Exploited vulnerabilities, and 1 of them is for Microsoft Windows User Profile Service Privilege Escalation Vulnerability (cve-2021-34484). 

All the 7 vulnerabilities need to be patched by Apr 21, 2022 (20 days for remediation).


Links: