<?xml version="1.0" encoding="UTF-8"?>
<rss version="2.0" xmlns:atom="http://www.w3.org/2005/Atom" xmlns:dc="http://purl.org/dc/elements/1.1/">
  <channel>
    <title>Forem: Peter G.</title>
    <description>The latest articles on Forem by Peter G. (@cisc0_pete).</description>
    <link>https://forem.com/cisc0_pete</link>
    <image>
      <url>https://media2.dev.to/dynamic/image/width=90,height=90,fit=cover,gravity=auto,format=auto/https:%2F%2Fdev-to-uploads.s3.amazonaws.com%2Fuploads%2Fuser%2Fprofile_image%2F1945391%2Fd7f400ff-1bc2-4d34-b4af-d821be03cb22.png</url>
      <title>Forem: Peter G.</title>
      <link>https://forem.com/cisc0_pete</link>
    </image>
    <atom:link rel="self" type="application/rss+xml" href="https://forem.com/feed/cisc0_pete"/>
    <language>en</language>
    <item>
      <title>Rasp-Pi Network ID tool</title>
      <dc:creator>Peter G.</dc:creator>
      <pubDate>Sat, 05 Oct 2024 20:32:43 +0000</pubDate>
      <link>https://forem.com/cisc0_pete/rasp-pi-network-id-tool-5hcm</link>
      <guid>https://forem.com/cisc0_pete/rasp-pi-network-id-tool-5hcm</guid>
      <description>&lt;p&gt;I needed a tool that could display relevant network information as quick as possible. Armed with a Raspberry Pi 3 B+, 2.13 inch Waveshare e-paper HAT V2, and a curiosity to explore its potential, I set out to develop a tool that could display network data. This was born out of necessity while I was setting up VLANs within PfSense. I got tired of using "ipconfig /release" and "ipconfig /renew" while testing network segregation and firewall rules. I will share that project in an additional post. &lt;/p&gt;

&lt;p&gt;I plan making this post as concise as possible. During my research to make this project a reality, I dug through a lot of fluff to find the information I needed. &lt;/p&gt;

&lt;p&gt;I assume you know how to flash the OS on to the PI. We will start post Pi imager. I used a fresh 64GB SD card. Also, noticed that the 128GB SD card I had initially used would not boot properly. I did not delve further to determine whether is was the SD card size or some operator error. Usually the latter..&lt;br&gt;
&lt;/p&gt;

&lt;div class="highlight js-code-highlight"&gt;
&lt;pre class="highlight plaintext"&gt;&lt;code&gt;pi@NetworkID:~ $ sudo apt update
pi@NetworkID:~ $ sudo apt upgrade

#install required packages
pi@NetworkID:~ $ sudo apt-get install python3-rpi.gpio python3-spidev python3-pil python3-pip
&lt;/code&gt;&lt;/pre&gt;

&lt;/div&gt;



&lt;p&gt;Next we will enable the SPI interface. We will do this from the raspi-config interface.&lt;br&gt;
&lt;/p&gt;

&lt;div class="highlight js-code-highlight"&gt;
&lt;pre class="highlight plaintext"&gt;&lt;code&gt;pi@NetworkID:~ $ sudo raspi-config
&lt;/code&gt;&lt;/pre&gt;

&lt;/div&gt;



&lt;p&gt;Choose option 3 - Interface options&lt;/p&gt;

&lt;p&gt;&lt;a href="https://media.dev.to/dynamic/image/width=800%2Cheight=%2Cfit=scale-down%2Cgravity=auto%2Cformat=auto/https%3A%2F%2Fdev-to-uploads.s3.amazonaws.com%2Fuploads%2Farticles%2Fac2ekxdr1v76j1r797ds.png" class="article-body-image-wrapper"&gt;&lt;img src="https://media.dev.to/dynamic/image/width=800%2Cheight=%2Cfit=scale-down%2Cgravity=auto%2Cformat=auto/https%3A%2F%2Fdev-to-uploads.s3.amazonaws.com%2Fuploads%2Farticles%2Fac2ekxdr1v76j1r797ds.png" alt="Interface options"&gt;&lt;/a&gt;&lt;/p&gt;

&lt;p&gt;&lt;a href="https://media.dev.to/dynamic/image/width=800%2Cheight=%2Cfit=scale-down%2Cgravity=auto%2Cformat=auto/https%3A%2F%2Fdev-to-uploads.s3.amazonaws.com%2Fuploads%2Farticles%2Ftaoyvszn7mmp1ksh8n9y.png" class="article-body-image-wrapper"&gt;&lt;img src="https://media.dev.to/dynamic/image/width=800%2Cheight=%2Cfit=scale-down%2Cgravity=auto%2Cformat=auto/https%3A%2F%2Fdev-to-uploads.s3.amazonaws.com%2Fuploads%2Farticles%2Ftaoyvszn7mmp1ksh8n9y.png" alt="Enable SPI"&gt;&lt;/a&gt;&lt;/p&gt;

&lt;p&gt;Enable the SPI interface by selsecting the option. Then select finish when the main screen reappears.&lt;br&gt;
&lt;/p&gt;

&lt;div class="highlight js-code-highlight"&gt;
&lt;pre class="highlight plaintext"&gt;&lt;code&gt;pi@NetworkID:~ $ git clone https://github.com/waveshare/e-Paper.git
Cloning into 'e-Paper'...
remote: Enumerating objects: 8711, done.
remote: Counting objects: 100% (1961/1961), done.
remote: Compressing objects: 100% (264/264), done.
remote: Total 8711 (delta 1745), reused 1778 (delta 1694), pack-reused 6750 (from 1)
Receiving objects: 100% (8711/8711), 42.23 MiB | 307.00 KiB/s, done.
Resolving deltas: 100% (6242/6242), done.
Updating files: 100% (3002/3002), done.

&lt;/code&gt;&lt;/pre&gt;

&lt;/div&gt;



&lt;p&gt;Give it few seconds to clone the repository. When it has finished, navigate to the e-paper directory that was created and run setup.py&lt;br&gt;
&lt;/p&gt;

&lt;div class="highlight js-code-highlight"&gt;
&lt;pre class="highlight plaintext"&gt;&lt;code&gt;pi@NetworkID:~ $ cd e-Paper/RaspberryPi_JetsonNano/python/

pi@NetworkID:~/e-Paper/RaspberryPi_JetsonNano/python $ sudo python3 setup.py install
&lt;/code&gt;&lt;/pre&gt;

&lt;/div&gt;



&lt;p&gt;This is where I made a mistake. I needed to install Python3 Setup Tools and netifaces. These libraries are crucial for proper set up and network interface queries using python.&lt;br&gt;
&lt;/p&gt;

&lt;div class="highlight js-code-highlight"&gt;
&lt;pre class="highlight plaintext"&gt;&lt;code&gt;pi@NetworkID:~/e-Paper/RaspberryPi_JetsonNano/python $ sudo apt install python3-setuptools
Reading package lists... Done
Building dependency tree... Done
Reading state information... Done
python3-setuptools is already the newest version (66.1.1-1).
python3-setuptools set to manually installed.
0 upgraded, 0 newly installed, 0 to remove and 0 not upgraded.

pi@NetworkID:~/e-Paper/RaspberryPi_JetsonNano/python $ sudo apt install python3-netifaces

&lt;/code&gt;&lt;/pre&gt;

&lt;/div&gt;



&lt;p&gt;Now lets try to run Setup.py again. &lt;br&gt;
Now after we have all the libraries and configurations correct, let's write some code!&lt;br&gt;
&lt;/p&gt;

&lt;div class="highlight js-code-highlight"&gt;
&lt;pre class="highlight plaintext"&gt;&lt;code&gt;import subprocess
import netifaces
from waveshare_epd import epd2in13_V2
from PIL import Image, ImageDraw, ImageFont
from datetime import datetime

# Initialize e-Paper display
# Specifically for 2.13" V2 
epd = epd2in13_V2.EPD()

# Define fonts
font = ImageFont.truetype('/usr/share/fonts/truetype/dejavu/DejaVuSans-Bold.ttf', 12)
font_small = ImageFont.truetype('/usr/share/fonts/truetype/dejavu/DejaVuSans-Bold.ttf', 10)

def get_network_info(interface):
    try:
        # Get network information for the specified interface
        if interface in netifaces.interfaces():
            addresses = netifaces.ifaddresses(interface)
            ip_address = addresses[netifaces.AF_INET][0]['addr']
            netmask = addresses[netifaces.AF_INET][0]['netmask']
            gateway = netifaces.gateways()['default'][netifaces.AF_INET][0]
            mac_address = addresses[netifaces.AF_LINK][0]['addr']
            return ip_address, netmask, gateway, mac_address
        else:
            print(f"Interface {interface} not found.")
            return None, None, None, None
    except Exception as e:
        print(f"Error retrieving network information: {e}")
        return None, None, None, None

def get_ssid(interface):
    try:
        # Execute the iwgetid command to get the SSID of the specified interface
        result = subprocess.run(['iwgetid', interface, '--raw'], capture_output=True, text=True)
        if result.returncode == 0:
            return result.stdout.strip()
        else:
            return "SSID not found"
    except Exception as e:
        print(f"Error retrieving SSID: {e}")
        return "SSID error"

def display_network_info(ip_address, netmask, gateway, mac_address, ssid=None):
    # Create new image with white background (landscape orientation)
    image = Image.new('1', (epd.height, epd.width), 255)
    draw = ImageDraw.Draw(image)

    # Clear display
    epd.init(epd.FULL_UPDATE)
    epd.displayPartBaseImage(epd.getbuffer(image))

    # Draw network information on the display
    draw.text((10, 10), f"IP Address: {ip_address}", font=font, fill=0)
    draw.text((10, 30), f"Subnet Mask: {netmask}", font=font, fill=0)
    draw.text((10, 50), f"Default Gateway: {gateway}", font=font, fill=0)

    # Add timestamp
    current_time = datetime.now().strftime('%Y-%m-%d %H:%M:%S')
    draw.text((10, 70), f"Timestamp: {current_time}", font=font, fill=0)

    # If SSID is available, display it
    if ssid:
        draw.text((10, 90), f"SSID: {ssid}", font=font, fill=0)

    # Display MAC address
    draw.text((10, 110), f"MAC Address: {mac_address}", font=font, fill=0)

    # Rotate the image 90 degrees clockwise
    image = image.rotate(90, expand=True)

    # Display rotated image on the e-Paper display
    epd.init(epd.FULL_UPDATE)
    epd.display(epd.getbuffer(image))

    # Sleep to conserve power
    epd.sleep()

def main():
    # Check for wireless connection first
    # Wirelss connection need to be configured before hand

    if 'wlan0' in netifaces.interfaces():
        interface = 'wlan0'
        ip_address, netmask, gateway, mac_address = get_network_info(interface)
        ssid = get_ssid(interface)
        if ip_address:
            display_network_info(ip_address, netmask, gateway, mac_address, ssid)
    # If no wireless connection, check for wired connection
    # Make sure the name of the interface here matches what is running on your device
    elif 'eth0' in netifaces.interfaces():
        interface = 'eth0'
        ip_address, netmask, gateway, mac_address = get_network_info(interface)
        if ip_address:
            display_network_info(ip_address, netmask, gateway, mac_address)
    else:
        print("No network interface found.")

if __name__ == '__main__':
    main()
&lt;/code&gt;&lt;/pre&gt;

&lt;/div&gt;



&lt;p&gt;I choose to use crontab to run this script at reboot.&lt;br&gt;
&lt;/p&gt;

&lt;div class="highlight js-code-highlight"&gt;
&lt;pre class="highlight plaintext"&gt;&lt;code&gt;pi@NetworkID:~ $ contab -e 

# Use option one, or whichever editor you'd like.
# At the end of the file add this line.

@reboot /usr/bin/python3 /home/pi/network_monitor.py

# This will run the script at each reboot. 

&lt;/code&gt;&lt;/pre&gt;

&lt;/div&gt;



</description>
      <category>raspberrypi</category>
      <category>networking</category>
      <category>waveshare</category>
      <category>pfsense</category>
    </item>
    <item>
      <title>CANBUS Speed Converter</title>
      <dc:creator>Peter G.</dc:creator>
      <pubDate>Sat, 05 Oct 2024 20:30:25 +0000</pubDate>
      <link>https://forem.com/cisc0_pete/canbus-speed-converter-50mi</link>
      <guid>https://forem.com/cisc0_pete/canbus-speed-converter-50mi</guid>
      <description>&lt;p&gt;This python script uses a text file made up of exported values from Tshark. This exported column is strictly made up of each CANBUS payload which is a 5 byte Hex value. (10 characters) This program converts CANBUS hex values into KPH or MPH.&lt;/p&gt;

&lt;p&gt;Here is the command I used to extract this information from CanID589.pcap which itself was an exported dissection from Wireshark of specifically CANBUS ID 589 which refers to speed. There 32 other different types of CANBUS IDs but we need not be concerned with those values at the moment.&lt;br&gt;
&lt;/p&gt;

&lt;div class="highlight js-code-highlight"&gt;
&lt;pre class="highlight plaintext"&gt;&lt;code&gt;┌──(kali㉿Z3r0)-[/media/sf_Shared_Kali/NCL Doc/scanningrecon]
└─$ tshark -r CanID589.pcap -T fields -e data.data &amp;gt; Data_speed.txt

&lt;/code&gt;&lt;/pre&gt;

&lt;/div&gt;



&lt;p&gt;(-r) reads the existing pcap file while (-T fields) instructs Tshark to output specific fields (rather than full packet details, summaries, or raw data). It's a way to customize the output, extracting only the desired information instead of dumping all packet data. The -e option is used to specify which field(s) from the packet to extract. In this case, data.data represents the data bytes of each packet. "data.data" refers to the actual content (payload) of the CANBUS frames in hexadecimal form. I had to experiment with different values until the correct data was exported to the text file. &lt;/p&gt;

&lt;p&gt;Here is a list of the different fields related to the CAN protocol.&lt;/p&gt;

&lt;ul&gt;
&lt;li&gt;can.id: The CAN identifier field (CAN ID)&lt;/li&gt;
&lt;li&gt;can.dlc: Data Length Code (how many data bytes are present)&lt;/li&gt;
&lt;li&gt;can.data: The payload data&lt;/li&gt;
&lt;li&gt;can.errorframe: CAN error frame&lt;/li&gt;
&lt;li&gt;data.data: The raw byte data (this is what this script is using)&lt;/li&gt;
&lt;/ul&gt;

&lt;p&gt;This can also been done individually for each packet but I had 352 different Can.ID = "589" (speed) packets to iterate through&lt;br&gt;
&lt;/p&gt;

&lt;div class="highlight js-code-highlight"&gt;
&lt;pre class="highlight plaintext"&gt;&lt;code&gt;def format_hex_value(hex_value):
    # Tshark exported specific packets to column data.data unformatted.
    return ' '.join(hex_value[i:i+2] for i in range(0, len(hex_value), 2))

def calculate_speed_from_hex_value(hex_value):
    # 5 byte check 
    if len(hex_value) &amp;lt; 10:
        raise ValueError("Hex value must have at least 10 characters for 5 bytes")

    # Extract the relevant bytes from payload (the last two bytes)
    high_byte = int(hex_value[-4:-2], 16)  
    low_byte = int(hex_value[-2:], 16)

    speed = (high_byte &amp;lt;&amp;lt; 8) + low_byte  
    # Example: 00 00 00 04 e1 - (04 &amp;lt;&amp;lt; 8) + e1 = 1024 + 225 = 1249

    # Convert speed from centi-KPH to KPH then to MPH
    speed_kph = speed / 100.0  # Assuming the value is in centi-KPH
    speed_mph = speed_kph * 0.621371  # Convert KPH to MPH

    return speed_mph

def main():
    speeds = []

    with open('data_speed.txt', 'r') as file:
        for line in file:
            hex_value = line.strip() 

            if hex_value:  

                formatted_hex_value = format_hex_value(hex_value)
                print(f"Formatted Hex Value: {formatted_hex_value}")  

                try:
                    # Calculate speed and store it in the speeds list
                    speed_mph = calculate_speed_from_hex_value(hex_value)
                    speeds.append(speed_mph)
                    print(f"Calculated Speed: {speed_mph:.2f} MPH")
                except ValueError as e:
                    print(f"Error processing value '{hex_value}': {e}")


    speeds.sort() 
    #Sort lowest to highest

    print("\nFinal Sorted Speeds (MPH):")
    for speed in speeds:
        print(f"{speed:.2f} MPH")

if __name__ == "__main__":
    main()


&lt;/code&gt;&lt;/pre&gt;

&lt;/div&gt;



&lt;p&gt;If anyone has any questions, comments, additions, or constructive criticism please feel free to contact me. Thank you&lt;/p&gt;

</description>
      <category>can</category>
      <category>canbus</category>
      <category>python</category>
      <category>wireshark</category>
    </item>
  </channel>
</rss>
