This Python script will connect to a specified server (typically over TCP, like a CTF challenge or a simple netcat listener), send an "Enter" keypress (newline character \n), receive data, and continuously repeat this until the string "flag{" is detected in the received data. It will then print the extracted flag and exit.
Important Considerations:
Server Type: This script assumes a basic TCP connection. For HTTP, FTP, SSH, etc., you would need specific client libraries. This is common for "netcat-style" challenges.
Line Endings: Some servers might expect \r\n (CRLF) instead of just \n (LF). I've included a comment on how to change this.
Buffering: If the flag is very long or split across multiple recv calls, this script might not catch the full flag. For this specific "send enter until flag{}" scenario, it's usually sufficient, as the server often sends the whole flag at once.
Rate Limiting/Sleep: Some servers might disconnect you if you send data too fast. A small time.sleep() might be necessary.
telnetlib Alternative: For more complex interactive shell-like challenges, Python's telnetlib can be easier to use as it handles some aspects of Telnet protocol negotiation. However, for a simple "send enter" loop, socket is perfectly fine.
python
import socket
import time
import sys
def send_enter_until_flag(host, port, flag_prefix="flag{", buffer_size=4096, delay=0.1):
"""
Connects to a server, sends 'Enter' repeatedly, and listens for a flag.
Args:
host (str): The target server's IP address or hostname.
port (int): The target server's port.
flag_prefix (str): The string to look for that indicates the start of the flag.
buffer_size (int): The maximum amount of data to receive at once.
delay (float): A small delay in seconds between sending 'Enter' to avoid overwhelming the server.
"""
s = None
try:
# Create a TCP/IP socket
s = socket.socket(socket.AF_INET, socket.SOCK_STREAM)
s.settimeout(10) # Set a timeout for connection and subsequent operations
print(f"[*] Attempting to connect to {host}:{port}...")
s.connect((host, port))
print(f"[*] Successfully connected to {host}:{port}")
# Send a newline character (Enter key)
# Use b'\n' for Unix-like systems, or b'\r\n' for Windows/Telnet-like systems
newline_char = b'\n'
# Buffer to accumulate received data, in case the flag is split
received_buffer = b""
while True:
try:
# Receive data from the server
data = s.recv(buffer_size)
if not data:
print("[!] Server closed the connection unexpectedly.")
break # Server disconnected
# Append received data to the buffer
received_buffer += data
# Decode the buffer for searching (assuming UTF-8, ignore errors for robustness)
decoded_data = received_buffer.decode('utf-8', errors='ignore')
# Print the received data (useful for debugging)
print(f"\n[<] Received:\n{decoded_data.strip()}")
# Check if the flag prefix is in the received data
if flag_prefix in decoded_data:
print("\n[!!!] FLAG PREFIX DETECTED!")
start_index = decoded_data.find(flag_prefix)
end_index = decoded_data.find('}', start_index)
if end_index != -1:
full_flag = decoded_data[start_index : end_index + 1]
print(f"[+] Extracted Flag: {full_flag}")
# Optionally, if the server might send more data, you could clear the buffer
# received_buffer = b""
# If you want to stop after the first flag, uncomment the break below
# break
else:
print(f"[*] Flag prefix found but closing brace '}}' not found. Data might be truncated or flag continues. Full buffer:\n{decoded_data}")
# If the flag might come in parts, you might want to wait for more data
# For now, let's keep sending Enter if '}' isn't found
# Send 'Enter'
print("[>] Sending: [ENTER]")
s.sendall(newline_char)
# Clear the buffer after processing, to avoid re-processing old data,
# unless you expect flags to be built across multiple receives
# For this specific "send enter until flag{}" type, clearing is usually fine.
received_buffer = b""
# Wait for a short period to avoid overwhelming the server
time.sleep(delay)
except socket.timeout:
print("[!] Socket timeout. No data received for a while.")
# You might choose to send another 'Enter' or break
# For now, let's send another Enter
print("[>] Sending another [ENTER] after timeout...")
s.sendall(newline_char)
time.sleep(delay) # Wait before next recv
continue # Try receiving again
except ConnectionResetError:
print("[!] Connection reset by peer. Server forcibly closed the connection.")
break
except BrokenPipeError:
print("[!] Broken pipe. The server disconnected.")
break
except Exception as e:
print(f"[!] An error occurred during send/receive: {e}")
break
except ConnectionRefusedError:
print(f"[!] Connection refused. Is the server running on {host}:{port}?")
except socket.gaierror:
print(f"[!] Hostname resolution failed for {host}. Is the hostname correct?")
except Exception as e:
print(f"[!] An unexpected error occurred: {e}")
finally:
if s:
print("[*] Closing connection.")
s.close()
print("[*] Script finished.")
if __name__ == "__main__":
print("--- Send Enter Until Flag Script ---")
print("This script will send 'Enter' repeatedly to a server until 'flag{}' is detected.")
target_host = input("Enter target host (e.g., 127.0.0.1 or example.com): ").strip()
while True:
try:
target_port = int(input("Enter target port (e.g., 1337): ").strip())
break
except ValueError:
print("[!] Invalid port. Please enter a number.")
send_enter_until_flag(target_host, target_port)
How to Use:
Save: Save the code as a Python file (e.g., flag_finder.py).
Run: Open a terminal or command prompt and navigate to where you saved the file.
bash
python flag_finder.py
Input: The script will prompt you for the target host and port.
Host: Enter the IP address (e.g., 127.0.0.1 for localhost) or hostname.
Port: Enter the port number the server is listening on.
Example Scenario (Testing):
You can test this script with a simple netcat listener:
Open Terminal 1 (Server):
bash
nc -lvp 12345
(Or netcat -lvp 12345 on some systems)
Open Terminal 2 (Run Script):
bash
python flag_finder.py
Enter 127.0.0.1 for host.
Enter 12345 for port.
Observe:
The script will connect and send [ENTER].
In Terminal 1 (netcat), you'll see a blank line appear each time the script sends [ENTER].
Type something like Hello there! in the netcat terminal and press Enter. The script will receive and print it.
Now, in the netcat terminal, type Here is your flag{this_is_the_secret_flag} and press Enter.
The script in Terminal 2 will detect "flag{", print the extracted flag, and then close the connection.
User
Use pwntools
Assistant
Okay, let's create a pwntools script to achieve this. pwntools is an excellent library for CTF challenges and binary exploitation, abstracting away a lot of the raw socket complexity.
Key pwntools features we'll use:
remote(host, port): Establishes a TCP connection.
sendline(data): Sends data followed by a newline (\n). Perfect for simulating an "Enter" keypress.
recvuntil(substring, timeout=...): Receives data until substring is found or a timeout occurs. This is ideal for detecting "flag{".
log functions: For clear and colored output.
python
from pwn import *
import sys
def send_enter_until_flag_pwntools(host, port, flag_prefix=b"flag{", flag_suffix=b"}", receive_timeout=5):
"""
Connects to a server using pwntools, sends 'Enter' repeatedly,
and listens for a flag.
Args:
host (str): The target server's IP address or hostname.
port (int): The target server's port.
flag_prefix (bytes): The byte string to look for that indicates the start of the flag.
flag_suffix (bytes): The byte string to look for that indicates the end of the flag.
receive_timeout (int): How long (in seconds) to wait for data/flag after each 'Enter'.
If the flag is not found within this timeout, another 'Enter' is sent.
"""
p = None # Initialize process/remote object
try:
log.info(f"[*] Attempting to connect to {host}:{port}...")
p = remote(host, port)
log.success(f"[*] Successfully connected to {host}:{port}")
# Optional: Receive any initial banner the server might send.
# This prevents the first sendline from being eaten by an initial prompt.
try:
initial_banner = p.recv(timeout=1).decode('utf-8', errors='ignore')
if initial_banner:
log.info(f"[<] Initial banner:\n{initial_banner.strip()}")
else:
log.info("[*] No initial banner received within 1 second.")
except EOFError:
log.warning("[!] Server closed connection during initial banner read.")
return
except PwnlibTimeout:
log.info("[*] No initial banner received within 1 second (timeout).")
except Exception as e:
log.warning(f"[!] Error receiving initial banner: {e}")
log.info(f"[*] Starting 'send Enter until {flag_prefix.decode()}' loop...")
while True:
try:
# Send an 'Enter' (newline character)
# An empty byte string `b''` with `sendline` sends just `\n`.
log.info("[>] Sending: [ENTER]")
p.sendline(b'')
# Attempt to receive data until the flag prefix is found.
# If it's not found within `receive_timeout` seconds, it will raise PwnlibTimeout.
log.info(f"[*] Waiting for data (or '{flag_prefix.decode()}') for {receive_timeout} seconds...")
# `p.recvuntil` consumes data from the buffer and keeps receiving
# until the substring is found or timeout.
# It returns the data *including* the substring.
data_up_to_flag_prefix = p.recvuntil(flag_prefix, timeout=receive_timeout)
# If we reach this line, `flag_prefix` was found!
log.success(f"[{flag_prefix.decode()}] DETECTED!")
# Now, receive the rest of the flag until `flag_suffix`.
# This will consume any remaining data in the buffer and
# continue receiving new data until `flag_suffix` is found.
data_after_flag_prefix = p.recvuntil(flag_suffix, timeout=receive_timeout)
# Combine the parts to get the full raw flag string
full_flag_raw = data_up_to_flag_prefix + data_after_flag_prefix
full_flag_str = full_flag_raw.decode('utf-8', errors='ignore')
# Extract just the flag{} part if needed (e.g., if there's text before/after)
start_index = full_flag_str.find(flag_prefix.decode())
end_index = full_flag_str.find(flag_suffix.decode(), start_index)
if start_index != -1 and end_index != -1:
extracted_flag = full_flag_str[start_index : end_index + len(flag_suffix.decode())]
log.success(f"[!!!] FULL FLAG EXTRACTED: {extracted_flag}")
else:
log.warning(f"[*] Flag prefix found but full flag ({flag_suffix.decode()}) couldn't be accurately extracted. Raw data:\n{full_flag_str}")
break # Flag found, exit the loop
except PwnlibTimeout:
# If `recvuntil` times out, it means the flag prefix wasn't found in this iteration.
# The loop will continue to send another 'Enter'.
log.info(f"[*] No '{flag_prefix.decode()}' detected within {receive_timeout} seconds. Sending another [ENTER].")
continue # Continue the while loop to send another Enter
except EOFError:
log.error("[!] Server closed the connection unexpectedly (EOFError).")
break # Server disconnected
except PwnlibException as e:
log.error(f"[!] A pwntools-specific error occurred: {e}")
break # Exit on other pwntools errors
except Exception as e:
log.critical(f"[!] An unexpected error occurred: {e}")
break # Exit on any other critical error
except ConnectionRefusedError:
log.error(f"[!] Connection refused. Is the server running on {host}:{port}?")
except socket.gaierror:
log.error(f"[!] Hostname resolution failed for {host}. Is the hostname correct?")
except Exception as e:
log.critical(f"[!] An unexpected error occurred during connection: {e}")
finally:
if p:
log.info("[*] Closing connection.")
p.close()
log.info("[*] Script finished.")
if __name__ == "__main__":
log.info("--- Pwntools Flag Finder Script ---")
log.info("This script will send 'Enter' repeatedly to a server until 'flag{}' is detected.")
target_host = input("Enter target host (e.g., 127.0.0.1 or example.com): ").strip()
while True:
try:
target_port = int(input("Enter target port (e.g., 1337): ").strip())
break
except ValueError:
log.warning("[!] Invalid port. Please enter a number.")
send_enter_until_flag_pwntools(target_host, target_port)
How to Use:
Install Pwntools: If you don't have it, install it:
bash
pip install pwntools
Save: Save the code as a Python file (e.g., pwntools_flag_finder.py).
Run: Open a terminal or command prompt and navigate to where you saved the file.
bash
python pwntools_flag_finder.py
Input: The script will prompt you for the target host and port.
Host: Enter the IP address (e.g., 127.0.0.1 for localhost) or hostname.
Port: Enter the port number the server is listening on.
Example Test Scenario (using netcat as a server):
Open Terminal 1 (Simulate Server with netcat):
bash
nc -lvp 12345
(Or netcat -lvp 12345 on some systems)
Open Terminal 2 (Run Pwntools Script):
bash
python pwntools_flag_finder.py
Enter 127.0.0.1 for host.
Enter 12345 for port.
Observe:
The pwntools script will connect and send [ENTER].
In Terminal 1 (netcat), you'll see a blank line appear each time the script sends [ENTER].
Type some random text in the netcat terminal and press Enter. The script will receive and print it (as [<] Initial banner: or as part of the [*] Waiting for data... output).
Now, in the netcat terminal, type:
code
Hello, here's some random text...
And now, the flag: flag{this_is_your_secret_flag_123}
And press Enter.
The pwntools script in Terminal 2 will detect "flag{", print the extracted flag, and then close the connection.
This pwntools version is generally more robust and concise for network interactions in CTF contexts.