Blog

ISSessions CTF 2021 Programming - Morse

Mar 31, 2021 | 2 minutes read

Morse

Given a morse code string, convert it back to ASCII, and submit within 3 seconds.

This one needed a bit more work than I could do in bash. Python it is!

Solution

import requests
import cv2
from lxml import html
 
MORSE_CODE_DICT = {'A': '.-', 'B': '-...',
                   'C': '-.-.', 'D': '-..', 'E': '.',
                   'F': '..-.', 'G': '--.', 'H': '....',
                   'I': '..', 'J': '.---', 'K': '-.-',
                   'L': '.-..', 'M': '--', 'N': '-.',
                   'O': '---', 'P': '.--.', 'Q': '--.-',
                   'R': '.-.', 'S': '...', 'T': '-',
                   'U': '..-', 'V': '...-', 'W': '.--',
                   'X': '-..-', 'Y': '-.--', 'Z': '--..',
                   '1': '.----', '2': '..---', '3': '...--',
                   '4': '....-', '5': '.....', '6': '-....',
                   '7': '--...', '8': '---..', '9': '----.',
                   '0': '-----', ', ': '--..--', '.': '.-.-.-',
                   '?': '..--..', '/': '-..-.', '-': '-....-',
                   '(': '-.--.', ')': '-.--.-'}
  
# Function to decrypt the string
# from morse to english
def decrypt(message):
    # extra space added at the end to access the
    # last morse code
    message += ' '
 
    decipher = ''
    citext = ''
    for letter in message:
 
        # checks for space
        if (letter != ' '):
 
            # counter to keep track of space
            i = 0
 
            # storing morse code of a single character
            citext += letter
 
        # in case of space
        else:
            # if i = 1 that indicates a new character
            i += 1
 
            # if i = 2 that indicates a new word
            if i == 2:
 
                # adding space to separate words
                decipher += ' '
            else:
 
                # accessing the keys using their values (reverse of encryption)
                decipher += list(MORSE_CODE_DICT.keys())[list(MORSE_CODE_DICT
                                                              .values()).index(citext)]
                citext = ''
 
    return decipher
 
def morse():
    s = requests.session()
    url = "http://progmorse.ctf.issessions.ca/"
    page = s.get(url)
    tree = html.fromstring(page.content)
    htmlimg = tree.xpath('//p[@class="data"]/text()')
    code = decrypt(htmlimg[0]).lower().strip()
    print(code)
    resp = s.get(url + "?answer=" + code)
    print(resp.content)

This heavily relied on exising StackOverflow code to convert between morse code and ASCII, since I wanted to get this done as soon as possible for some quick points.