# Des mots, des mots, des mots

**Catégorie:** Programmation - **Difficulté:** Difficile

**Description:**

<figure><img src="/files/hMvkDQ3hfr7yMuAEWT0s" alt=""><figcaption></figcaption></figure>

Netcat : *`nc challenges.404ctf.fr 30980`*

**Solution:**

Pour ce challenge, nous devions dans un premier répondre à 4 "énigmes" donnant les différentes règles à implémenter dans notre script :&#x20;

<figure><img src="/files/sKD0dORWMot5AFdtrTlv" alt="" width="563"><figcaption></figcaption></figure>

Après avoir répondu à toutes les règles pas simples à comprendre pour un être humain (normalement constitué :joy:), nous pouvons les donner à un outil tel que Copilot afin qu'il nous aide à créer le bon code.\
Pour ce faire, nous commençons par une base de pwntool pour récupérer et renvoyer les réponses puis ensuite générer des fonctions pour chaque règle.

Voici donc le code utilisé pour ce challenge :&#x20;

```python
from pwn import *

n = remote("challenges.404ctf.fr",30980)
voyelles = "aeiouyAEIOUY"
consonnes = "bcdfghjklmnpqrstvwxzBCDFGHJKLMNPQRSTVWXZ"
alphabet = "abcdefghijklmnopqrstuvwxyzABCDEFGHIJKLMNOPQRSTUVWXYZ"

def isvoy(letter):
		if(letter in voyelles):
			return 1
		return 0

def nb_consonnes(str1):
	res = 0
	for i in str1:
		if(i in consonnes):
			res += 1
	return res

def find_prev_voy(letter):
	ind = alphabet.index(letter)
	for i in range(ind - 1,-1,-1):
		if(alphabet[i] in voyelles):
			return alphabet[i]

def sort_word(word):
    char_counts = {}
    for char in word:
        char_counts[char] = char_counts.get(char, 0) + 1    
    sorted_word = sorted(word, key=lambda char: (-char_counts[char], ord(char)))
    return ''.join(sorted_word)


def rule1(str1):
	str1 = "".join([chr(i) for i in reversed(str1)])
	return str1

def rule2(res):
    longueur = len(res)
    if longueur % 2 == 0:
        moitie = longueur // 2
        partie1 = res[:moitie]
        partie2 = res[moitie:]
        mot_modifie = partie2 + partie1
    else: 
        lettre_centrale = longueur // 2
        mot_modifie = res.replace(res[lettre_centrale], "") 
    return mot_modifie

def rule3(t):
	gg = t.decode()
	gg = [ord(i) for i in gg]
	gg = rule1(gg)
	gg = rule2(gg)
	print(gg)
	if(len(gg) >= 3):
		if(gg[2] in consonnes):
			voy = []
			t = list(t.decode())
			r = list(t)
			for i in r:
				if(i in voyelles):
					voy.append(i)
			voy.insert(len(voy),voy[0])
			voy = voy[1:]
			ind = 0
			for i in range(0,len(t)):
				if(t[i] in voyelles):
					r[i] = voy[ind % len(voy)]
					ind += 1
			r = [ord(i) for i in r]
			r = rule1(r)
			r = rule2(r)
			return r
		else:
			voy = []
			t = list(t.decode())
			r = list(t)
			for i in r:
				if(i in voyelles):
					voy.append(i)
			voy.insert(0,voy[len(voy)-1])
			voy = voy[:len(voy)-1]
			ind = 0
			for i in range(0,len(t)):
				if(t[i] in voyelles):
					r[i] = voy[ind % len(voy)]
					ind += 1
			r = [ord(i) for i in r]
			r = rule1(r)
			r = rule2(r)
			return r
	else:
		return gg
def rule4(t):
	r = list(t)
	i = 0
	while(i != len(r)):
		if(r[i] in consonnes):
			vp = ord(find_prev_voy(r[i]))
			s = 0
			for j in range(i-1,-1,-1):	
				s += ord(r[j]) * 2**(i-j) * isvoy(r[j])
			a = ((vp + s) % 95) + 32
			r.insert(i+1,chr(a))
		i += 1
	return r

for i in range(100):
	t = n.recv()
	tt = t
	print(t.decode("utf-8"))
	if(i == 0):
		n.sendline(b"cosette")
	if(i == 1):
		n.sendline(b"ettesoc")
	if(i == 2):
		t = t[t.index(b"e : ") + 5:]
		t = t[:t.index(b"}\n>>")]
		t = rule1(t)
		t = rule2(t)
		n.sendline(t.encode())
	if(i == 3):
		t = t[t.index(b"e : {") + 5:]
		t = t[:t.index(b"}\n>>")]

		t = rule3(t)
		n.sendline(t.encode())
	if(i == 4):
		t = t[t.index(b"e : {") + 5:]
		t = t[:t.index(b"}\n>>")]
		r = rule3(t)
		r = "".join(rule4(r))
		r = sort_word(r)
		n.sendline(r.encode())
		print(r)
	if(i == 5):
		#t = t.decode("utf-8")
		t = t[t.index(b"Entr") + 11:]
		t = t[:t.index(b"}")]
		t = t.split(b" ")
		res = ""
		print(t,len(t))
		c = 0
		for i in t:
			r = rule3(i)
			r = "".join(rule4(r))
			r = sort_word(r)
			res += r + " "
			c += 1
		print(c)
		print(res)
		res = res[:len(res)-1]
		n.sendline(res.encode())
```

Une fois lancer, le script va répondre à toutes les questions du bot et nous renvoyer le flag à la fin : <br>

<figure><img src="/files/kDAZiJRlZNmUiRC9kV3g" alt="" width="563"><figcaption></figcaption></figure>

Ce challenge n'était pas le plus simple étant donné la "complexité" des règles à respecter.

<details>

<summary>🚩 FLAG</summary>

```
404CTF{:T]cdeikm_)W_doprsu_nt_;adei}
```

</details>


---

# Agent Instructions: Querying This Documentation

If you need additional information that is not directly available in this page, you can query the documentation dynamically by asking a question.

Perform an HTTP GET request on the current page URL with the `ask` query parameter:

```
GET https://writeups.ayweth20.com/2023/404ctf-2023/programmation/des-mots-des-mots-des-mots.md?ask=<question>
```

The question should be specific, self-contained, and written in natural language.
The response will contain a direct answer to the question and relevant excerpts and sources from the documentation.

Use this mechanism when the answer is not explicitly present in the current page, you need clarification or additional context, or you want to retrieve related documentation sections.
