Make a Rubber Ducky with a Raspberry Pico

I am taking a slight detour from the Raycasting series of posts (don’t worry, the next post in the series is coming soon) to cover another small project I have been working on, creating a Rubber Duckly using a Raspberry Pico and CircuitPython.


A Rubber Ducky is a keystroke injection tool that is often disguised as a USB flash drive to trick an unsuspecting victim into plugging it into their computer. The computer recognizes the Rubber Ducky as a USB keyboard (and mouse if required), and when it is plugged in, it executes a sequence of pre-programmed keystrokes, which will be executed against the target computer, as if the user did it. This attack thus exploits the security roles and permissions assigned to the user logged in at the time.
This is a good time to note that using a Rubber Ducky for dubious intents is illegal and a terrible idea, and I take no responsibility for the consequences if anyone chooses to use what they learn here to commit such acts.

To create the Rubber Ducky described in this post, you will need four things:
1. A Rasberry Pico
2. A Micro USB Cable
3. CircuitPython
4. The Adafruit HID Library of CircuitPython

First, you will need to install CircuitPython on your Raspberry Pico. This link will provide all the instructions and downloads you will require to do this.
Next, you will need to install the Adafruit HID Library. Instructions on how to do this can be found here.

Now that all the pre-requisites are installed and configured, the source code below can be deployed using the process described in the first link. The Source code below executes a sequence of keystrokes that opens Notepad on the target computer and type out a message. Just note that the keystrokes are slowed down significantly to make what is happening visible to the user Typically, this will not be done with a Rubber Ducky.

import board
import digitalio
import time
import usb_hid
from adafruit_hid.keyboard import Keyboard
from adafruit_hid.keycode import Keycode

kbd = Keyboard(usb_hid.devices)

led = digitalio.DigitalInOut(board.LED)
led.direction = digitalio.Direction.OUTPUT
led.value = True
time.sleep(10)
while True:
    kbd.press(Keycode.GUI, Keycode.R)
    time.sleep(.09)
    kbd.release_all()
    kbd.press(Keycode.N)
    time.sleep(.09)
    kbd.release(Keycode.N)
    time.sleep(.09)
    kbd.press(Keycode.O)
    time.sleep(.09)
    kbd.release(Keycode.O)
    time.sleep(.09)
    kbd.press(Keycode.T)
    time.sleep(.09)
    kbd.release(Keycode.T)
    time.sleep(.09)
    kbd.press(Keycode.E)
    time.sleep(.09)
    kbd.release(Keycode.E)
    time.sleep(.09)
    kbd.press(Keycode.P)
    time.sleep(.09)
    kbd.release(Keycode.P)
    time.sleep(.09)
    kbd.press(Keycode.A)
    time.sleep(.09)
    kbd.release(Keycode.A)
    time.sleep(.09)
    kbd.press(Keycode.D)
    time.sleep(.09)
    kbd.release(Keycode.D)
    time.sleep(.09)
    kbd.press(Keycode.ENTER)
    time.sleep(.09)
    kbd.release(Keycode.ENTER)
    time.sleep(.09)

    kbd.press(Keycode.H)
    time.sleep(.09)
    kbd.release(Keycode.H)
    time.sleep(.09)
    kbd.press(Keycode.E)
    time.sleep(.09)
    kbd.release(Keycode.E)
    time.sleep(.09)
    kbd.press(Keycode.L)
    time.sleep(.09)
    kbd.release(Keycode.L)
    time.sleep(.09)
    kbd.press(Keycode.L)
    time.sleep(.09)
    kbd.release(Keycode.L)
    time.sleep(.09)
    kbd.press(Keycode.O)
    time.sleep(.09)
    kbd.release(Keycode.O)
    time.sleep(.09)
    kbd.press(Keycode.ENTER)
    time.sleep(.09)
    kbd.release(Keycode.ENTER)
    time.sleep(100)

led.value = False

Here is a video of the Rubbert Ducky in Action:

Make a Rubber Ducky with a Raspberry Pico

2021 PROJECTS

In this post, I will cover some projects I have worked on over the last few months and some projects I have planned for the future.

Bipedal Robot


I am currently busy building a bipedal robot based on this Instructables post by K.Biagini. I used his design as a foundation and added additional components and functionality (such as arms and a Piezo for sound).

I had to modify his 3D models to achieve what I wanted. Here are links to download my modified 3d Models:
– Body Extension (to fit in the extra components) – Link
– Modified Head – Link
– Arms – Link

Here is a list of all the electronic components used:
– 1x Arduino Nano
– 6x micro servos
– 2 x push buttons
– 1x mini toggle switch
– 1x 9v Battery
– 1x ultrasonic sensor (HC-SR04)
– 1x RGB LED
– 1x Piezo

These components are connected as follows:

Pinout configuration of Arduino Nano:

Pin NumberConnected Hardware
2Ultrasonic Sensor Echo Pin
3RGB LED Red Pin
4Push Button 1
5RGB LED Green Pin
6RGB LED Blue Pin
7Push Button 2
8Servo Signal Pin (Right Hip)
9Servo Signal Pin (Right Ankle)
10Servo Signal Pin (Left Hip)
11Piezo
12Servo Signal Pin (Left Ankle)
13Ultrasonic Sensor Trigger Pin
14 (A0)Servo Signal Pin (Left Arm)
15 (A1)Servo Signal Pin (Right Arm)

This is still an in-progress project and is not done, Especially from a coding perspective on the Arduino, but once I have completed this project, I will create a post containing the complete source code.

Rotary Control

I needed a rotary control for another project discussed below, so I decided to build one as per this Post on the Prusa Printers blog. It is based on an Arduino Pro Micro and uses Rotary Encoder Module.

I modified the code available on the Prusa blog to mimic keyboard WASD inputs. Turning the dial left and right will input A and D, respectively. Pressing in the dial control push button will switch to up and down inputs, thus turning the dial left and right will input W and S.
Here is the modified code (Based on Prusa Printers blog post code):

#include <ClickEncoder.h>
#include <TimerOne.h>
#include <HID-Project.h>

#define ENCODER_CLK A0 
#define ENCODER_DT A1
#define ENCODER_SW A2

ClickEncoder *encoder; // variable representing the rotary encoder
int16_t last, value; // variables for current and last rotation value
bool upDown = false;
void timerIsr() {
  encoder->service();
}

void setup() {
  Serial.begin(9600); // Opens the serial connection
  Keyboard.begin();
  encoder = new ClickEncoder(ENCODER_DT, ENCODER_CLK, ENCODER_SW); 

  Timer1.initialize(1000); // Initializes the timer
  Timer1.attachInterrupt(timerIsr); 
  last = -1;
} 

void loop() {  
  value += encoder->getValue();

  if (value != last) { 
    if (upDown)
    {
    if(last<value) // Detecting the direction of rotation
        Keyboard.write('s');
      else
        Keyboard.write('w');
    }
    else
    {
      if(last<value) // Detecting the direction of rotation
        Keyboard.write('d');
      else
        Keyboard.write('a');
    }
    last = value; 
    Serial.print("Encoder Value: "); 
    Serial.println(value);
  }

  // This next part handles the rotary encoder BUTTON
  ClickEncoder::Button b = encoder->getButton(); 
  if (b != ClickEncoder::Open) {
    switch (b) {
      case ClickEncoder::Clicked: 
        upDown = !upDown;
      break;      
      
      case ClickEncoder::DoubleClicked: 
        
      break;      
    }
  }

  delay(10); 
}

I use the rotary control with a Raspberry Pi to control a camera pan-tilt mechanism. Here is a video showing it in action:

I will cover the purpose of the camera as well as the configuration and coding related to the pan-tilt mechanism later in this post.

Raspberry Pi Projects

Raspberry Pi and TensorFlow lite

TensorFlow is a deep learning library developed by Google that allows for the easy creation and implementation of Machine Learning models. There are many articles available online on how to do this, so I will not focus on how to do this.

At a high level, I created a basic object identification model created on my windows PC and then converted the model to a TensorFlow lite model that can be run on a Raspberry pi 4. When the TensorFlow lite model is run on the Raspberry Pi, a video feed is shown of the attached Raspberry Pi camera, with green blocks around items that the model has identified with a text label of what the model believes the object is, as well as a numerical percentage which indicates the level of confidence the model has in the object identification.

I have attached a 3inch LCD screen (in a 3D printed housing) to the Raspberry Pi to show the video feed and object identification in real-time.

The Raspberry Pi Camera is mounted on a pan-tilt bracket which is controlled via two micro servos. As mentioned earlier, the pan-tilt mechanism is controlled via the dial control discussed earlier. The pan-tilt mechanism servos are driven by an Arduino Uno R3 connected to the Raspberry Pi 4 via USB. I initially connected servos straight to Raspberry Pi GPIO pins. However, this resulted in servo jitter. After numerous modifications and attempted fixes, I was not happy with the results, so I decided to use an Arduino Uno R3 to drive the servos instead and connect it to the Raspberry Pi Via USB. I have always found hardware interfacing significantly easier with Arduino and also the result more consistent.

Here is a diagram of how the servos are connected to the Arduino Uno R3:

Below is the Arduino source code I wrote to control the servos. Instructions are sent to the Arduino through serial communication via USB, and the servos are adjusted accordingly.

#include <Servo.h>
#define SERVO1_PIN A2
#define SERVO2_PIN A3

Servo servo1;
Servo servo2;
String direction;
String key;
int servo1Pos = 0;
int servo2Pos = 0;

void setup()
{
  servo1Pos = 90;
  servo2Pos = 90;
  Serial.begin(9600);
  servo1.attach(SERVO1_PIN);
  servo2.attach(SERVO2_PIN);

  servo1.write(30);
  delay(500);
  servo1.write(180);
  delay(500);
  servo1.write(servo1Pos);
  delay(500);
  servo2.write(30);
  delay(500);
  servo2.write(150);
  delay(500);
  servo2.write(servo2Pos);
  delay(500);
  Serial.println("Started");
  servo1.detach();
  servo2.detach();
}

String readSerialPort()
{
  String msg = "";
  if (Serial.available()) {
    delay(10);
    msg = Serial.read();
    Serial.flush();
    msg.trim();
    Serial.println(msg);
  }
  return msg;
}

void loop()
{
  direction = "";
  direction = readSerialPort();
  //Serial.print("direction : " + direction);
  key = "";

  if (direction != "")
  {
    direction.trim();
    key = direction;

    servo1.attach(SERVO1_PIN);
    servo2.attach(SERVO2_PIN);

    if (key == "97")
    {
      if (servo2Pos > 30)
      {
        servo2Pos -= 10;
      }
      servo2.write(servo2Pos);
      delay(500);
      Serial.print("A");
    }

    else if (key == "115")
    {
      if (servo1Pos < 180)
      {
        servo1Pos += 10;
      }
      servo1.write(servo1Pos);
      delay(500);
      Serial.print("S");
    }

    else if (key == "119")
    {
      if (servo1Pos > 30)
      {
        servo1Pos -= 10;
      }
      servo1.write(servo1Pos);
      delay(500);
      Serial.print("W");
    }

    else if (key == "100")
    {
      if (servo2Pos < 150)
      {
        servo2Pos += 10;
      }
      servo2.write(servo2Pos);
      delay(500);
      Serial.print("D");
    }

    delay(100);
    servo1.detach();
    servo2.detach();
  }

}

On the Raspberry Pi, the following Python script is used to transfer the rotary control input via serial communication to the Arduino:

# Import libraries
import serial
import time
import keyboard
import pygame

pygame.init()
screen = pygame.display.set_mode((1, 1))

with serial.Serial("/dev/ttyACM0", 9600, timeout=1) as arduino:
    time.sleep(0.1)
if arduino.isOpen():
    done = False
while not done:
    for event in pygame.event.get():
    if event.type == pygame.QUIT:
    done = True
elif event.type == pygame.KEYDOWN:
if event.key == pygame.K_s:
    arduino.write('s'.encode())

if event.key == pygame.K_w:
    arduino.write('w'.encode())

if event.key == pygame.K_a:
    arduino.write('a'.encode())

if event.key == pygame.K_d:
    arduino.write('d'.encode())
time.sleep(0.5)

arduino.Close();
print ("Goodbye")

The next thing I want to implement on this project is face tracking using TensorFlow lite with automated camera movement.

Raspberry Pi Zero W Mini PC

I built a tiny PC using a Raspberry Pi Zero W combined with a RII RT-MWK01 V3 wireless mini keyboard and a 5 inch LCD display for Raspberry Pi with a 3D printed screen stand.


It is possible to run Quake 1 on the Raspberry Pi Zero following the instructions in this GitHub, and it runs great.

Raspberry Pi Mini Server Rack

I have 3D printed a mini server rack and configured a four Raspberry Pi Cluster consisting of three raspberry Pi 3s and one Raspberry Pi 2. They are all networked via a basic five-port switch.

I am currently busy with a few different projects using the Pi cluster and will have some posts in the future going into some more details on these projects.

I developed a little Python application to monitor my different Raspberry Pis and show which ones are online (shown in green) and offline (shown in red).

The application pings each endpoint every 5 seconds, and it is also possible to click on an individual endpoint to ping it immediately. The list of endpoints is read from a CSV file, and it is easy to add additional endpoints. The UI is automatically updated on program startup with the endpoints listed in the CSV file.

Here is the Python source code of the application:

import PySimpleGUI as sg
import csv
import time
import os
from apscheduler.schedulers.background import BackgroundScheduler


def ping(address):
    response = os.system("ping -n 1 " + address)
    return response


def update_element(server):
    global window
    global layout
    response = ping(server.address)
    if response == 0:
        server.status = 1
        window.Element(server.name).Update(button_color=('white', 'green'))
        window.refresh()
    else:
        server.status = 0
        window.Element(server.name).Update(button_color=('white', 'red'))
        window.refresh()


def update_window():
    global serverList
    for server in serverlist:
        update_element(server)


class server:
    def __init__(self, name, address, status):
        self.name = name
        self.address = address
        self.status = status


serverlist = []

with open('servers.csv') as csv_file:
    csv_reader = csv.reader(csv_file, delimiter=',')
    line_count = 0
    for row in csv_reader:
        if line_count == 0:
            line_count += 1
        else:
            serverlist.append(server(row[0], row[1], 0))
            line_count += 1

layout = [
    [sg.Text("Server List:")],
]

for server in serverlist:
    layout.append([sg.Button('%s' % server.name, 
                    button_color=('white', 'orange'), 
                    key='%s' % server.name)])

window = sg.Window(title="KillerRobotics Server Monitor", 
                    layout=layout, margins=(100, 30))
window.finalize()
scheduler = BackgroundScheduler()
scheduler.start()

scheduler.add_job(update_window, 'interval', seconds=5, id='server_check_job')

while True:
    event, values = window.read()
    if event == sg.WIN_CLOSED:
        scheduler.remove_all_jobs()
        scheduler.shutdown()
        window.close()
        break
    elif event in [server.name for server in serverlist]:
        scheduler.pause()
        update_element([server for server in 
                         serverlist if server.name == event][0])
        scheduler.resume()

Raspberry Pi Pico

I ordered a few Raspberry Pi Picos on its release, and thus far, I am very impressed with this small and inexpensive microcontroller.

The Raspberry Pi Pico sells for $4 (USD) and has the following specifications:
– RP2040 microcontroller chip designed by Raspberry Pi
– Dual-core Arm Cortex-M0+ processor, flexible clock running up to 133 MHz
– 264KB on-chip SRAM
– 2MB on-board QSPI Flash
– 26 multifunction GPIO pins, including 3 analogue inputs
– 2 × UART, 2 × SPI controllers, 2 × I2C controllers, 16 × PWM channels
– 1 × USB 1.1 controller and PHY, with host and device support
– 8 × Programmable I/O (PIO) state machines for custom peripheral support
– Low-power sleep and dormant modes
– Accurate on-chip clock
– Temperature sensor
– Accelerated integer and floating-point libraries on-chip

It is a versatile little microcontroller that nicely fills the gap between Arduino and similar microcontrollers and the more traditional Raspberry Pis or similar single board computers.
I have only scratched the surface of using the Pico on some really basic projects, but I have quite a few ideas of using it on some more interesting projects in the future.

3D Printing

I ran into some problems with my 3D printer (Wanhao i3 Mini) over the last few months. The First problem was that half of the printed LCD display died, which was an annoyance, but the printer was still usable. The next issue, which was significantly more severe, was that the printer was unable to heat up the hot end.

My first course of action was to replace both the heating cartridge and the thermistor to ensure that neither of those components were to blame, and unfortunately, they were not. After some diagnostics with a multimeter on the printer’s motherboard, I determined that no power was passing through to the heating cartridge connectors on the motherboard.

I ordered a replacement motherboard and installed it, and the 3D printer is working as good as new again. When I have some more time, I will try and diagnose the exact problem on the old motherboard and repair it.
Here are photos of the old motherboard I removed from the printer:

Below are some photos of a few things I have 3D printed the last few months:

2021 PROJECTS