<?xml version="1.0" encoding="UTF-8"?><rss xmlns:dc="http://purl.org/dc/elements/1.1/" xmlns:content="http://purl.org/rss/1.0/modules/content/" xmlns:atom="http://www.w3.org/2005/Atom" version="2.0" xmlns:cc="http://cyber.law.harvard.edu/rss/creativeCommonsRssModule.html">
    <channel>
        <title><![CDATA[Stories by Masumi Nakamura on Medium]]></title>
        <description><![CDATA[Stories by Masumi Nakamura on Medium]]></description>
        <link>https://medium.com/@mnakamura1337?source=rss-6eb056f6c84------2</link>
        <image>
            <url>https://cdn-images-1.medium.com/fit/c/150/150/1*Xfvn_5zeAONuj3-EBPW8CA.png</url>
            <title>Stories by Masumi Nakamura on Medium</title>
            <link>https://medium.com/@mnakamura1337?source=rss-6eb056f6c84------2</link>
        </image>
        <generator>Medium</generator>
        <lastBuildDate>Sun, 06 Dec 2026 09:29:33 GMT</lastBuildDate>
        <atom:link href="https://medium.com/@mnakamura1337/feed" rel="self" type="application/rss+xml"/>
        <webMaster><![CDATA[yourfriends@medium.com]]></webMaster>
        <atom:link href="http://medium.superfeedr.com/" rel="hub"/>
        <item>
            <title><![CDATA[Reverse engineering visual novels 101, part 2]]></title>
            <link>https://medium.com/hackernoon/reverse-engineering-visual-novels-101-part-2-9258f547262a?source=rss-6eb056f6c84------2</link>
            <guid isPermaLink="false">https://medium.com/p/9258f547262a</guid>
            <category><![CDATA[software-development]]></category>
            <category><![CDATA[japanese]]></category>
            <category><![CDATA[reverse-engineering]]></category>
            <category><![CDATA[visual-novel]]></category>
            <category><![CDATA[programming]]></category>
            <dc:creator><![CDATA[Masumi Nakamura]]></dc:creator>
            <pubDate>Tue, 04 Oct 2016 12:08:40 GMT</pubDate>
            <atom:updated>2017-07-14T10:51:01.048Z</atom:updated>
            <cc:license>https://creativecommons.org/licenses/by-sa/4.0/</cc:license>
            <content:encoded><![CDATA[<figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*CCH2EIavTEjZFJcdFHpOmw.png" /></figure><p>Hey, it’s been a while <a href="https://medium.com/@mnakamura1337/reverse-engineering-visual-novels-101-d0bc3bf7ab8">since my last post</a>, so I thought a quick reminder of what’s going on here would be helpful. We’re dabbling in reverse engineering, and visual novels are our target. In the first part of this article, we’ve learned to analyze container formats using marvelous <a href="http://kaitai.io/">Kaitai Struct tool</a>, which makes it pretty easy for just about everyone who knows a little about computers to try their hand in proper “clean room” reverse engineering, without deep knowledge of CPUs, registers, disassembly, etc.</p><p>Our main target is still <a href="https://vndb.org/v13353">Koisuru Shimai no Rokujuso</a>, a lesser known, but still nicely done visual novel from PeasSoft. Last time we’ve discovered that it uses an engine that’s probably called “Yuka”. We’ve successfully extracted game files from .ykc containers, got our hands on visuals, sounds and music, but the final challenge still awaits: <em>the script</em>.</p><h3>Meditation on novel’s internals</h3><p>Before diving into the vast depths of binary dumps, let’s take a moment to reflect on how most of the visual novel engines work. Visual novel consists of the text (dialogues, narratives), visuals and sounds. To make it all come together, some sort of a control program is needed. Technically it is possible to just stuff it all as machine code in the middle of .exe file, but in 99% of cases (ok, I’m lying — in 100% of the cases I’ve seen by my very own eyes) engine authors don’t do that. Instead, these control instructions are kept as a separate file in some sort of (improvised) domain-specific scripting language. That’s what they universally call <strong>“the script”</strong>. Let’s take a peek at how it may look:</p><pre>$ tarot = 0<br>$ memory = 0</pre><pre>scene bg01_1 with dissolve</pre><pre>play music &quot;bgm/8.mp3&quot; fadein (2.0)<br>play ambience &quot;amb/forest.mp3&quot; fadein (3.0)<br>&quot;Morning.&quot;<br>&quot;Not my favourite time of the day.&quot;<br>&quot;The morning is when you’re not awake enough to do anything…&quot;</pre><p>This is a small fragment of script’s source code of one of the VNs using <a href="https://www.renpy.org/">Ren’Py</a> — that’s one of the most well-known free-as-in-beer &amp; free-as-in-speech engines. Leaving aside the question of whether it’s a good or bad idea to use Ren’Py per se, let’s just investigate what’s typical for visual novel’s script (and that’s exactly what we’ll be looking for):</p><ul><li><strong>the text</strong> — it might be the narrative (i.e. not spoken by a character, but part of the story told by a narrator) or some dialogue lines (attributes to the certain character)</li><li>commands to deal with <strong>visuals</strong> — backgrounds / sprites (`scene bg01_1`) / character graphics / event graphics, sometimes augumenting them with some visual effect (`with dissolve`)</li><li>commands to play back the <strong>music or sound effects</strong> (`play music`, `play ambience`), sometimes also coming up with some extra arguments, most frequently with durations of fade-ins and fade-outs (i.e. slow gradual increase or decrease in sound’s volume)</li><li>dealing with <strong>variables</strong>: setting (`$ tarot = 0`), getting, checking conditions and branching</li><li>some extra stuff, like playing back <strong>voice files</strong> pronounced by certain characters, <strong>flow control</strong> and various service features, like <strong>comments, labels, macros</strong>, etc</li></ul><p>Of course, in the real world most of the time we won’t be able to access the script’s source code — that would be too easy. It’s been probably half-a-century already since people learned to create compilers (as opposed to interpreters), so nowadays most likely the source code is being compiled into the executable byte code, which is then executed by the VN engine using some sort simple (or not so simple) virtual machine. Sometimes you’ll get lucky — for some popular engines you’ll be able to get a ready-made toolset — compilers, decompilers, debuggers, script validators, etc. — but most of the time life’s not that convenient.</p><p>Let’s get back to our visual novel that we’ve started to dissect in our previous article — <a href="https://vndb.org/v13353">Koisuru Shimai no Rokujuso</a>. After unpacking of its archives, we found inside the images, the sounds, the music files, and the most mysterious artifact so far — a handful of files with .yks extension. Presumably, it’s where the novel’s script is (remember, the engine is presumably called Yuka, so it’s YKS = <strong>Y</strong>u<strong>K</strong>a <strong>S</strong>cript). To be precise, it’s not just <em>one</em> script, but there’s a quite a few of them:</p><pre>YKS/ScriptStart.yks<br>YKS/trial/Yoyaku.yks<br>YKS/trial/trial_00100.yks<br>YKS/trial/trial_00200.yks<br>YKS/all/all_00010.yks<br>…<br>YKS/all/all_02320.yks</pre><p>That makes us 103 files total in YKS/all/. Let me remind you that we’ve downloaded the trial version — but, it looks like the developers were kind of lazy to rip the full game content properly and we’ve got trial scripts in trial/ and full game scripts in all/.</p><p>Judging from my experience, visual novel authors tend to walk one of two ways: either packing every script bit into one huge file, or making tons of files for every scene / event in the game. Looks like it’s the latter we’re facing here. By the way, note that there’s also a distinct “ScriptStart.yks” — but probably it won’t be as interesting to us as the rest of the files. You see, engine developers frequently want their engine to be as all-purpose as possible and choose to implement elements like UI, saving/loading, CG galleries, menus, options screens, etc using the engine itself. It’s definitely possible to diassemble all that stuff too, but (a) it’s certainly not the best place to start given it lacks any text or other visual hints, (b) it’s not that interesting for our purposes. So, I propose to make a head on start and begin with more plausible scripts.</p><h3>Where’s my martini, shaken, not stirred?</h3><p>As in our previous article, we start with basic intelligence first. So, get your Aston Martin ready and let’s scout the surroundings.</p><p>First of all, this is a Windows game, so it’s a quite viable idea to just find some Windows box, run it and see what happens. That’s what we get right after hitting the “Start new game” button in main menu:</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*L1to8cjr3XRvGlJ3CHlYsQ.png" /><figcaption>The very first text that one encounters in the visual novel.</figcaption></figure><p>The start of the story greets us. We’ve got a background here (half-a-minute search reveals that it’s a “bg01_01.png” from the BG/ directory), and we’ve got some text. Seeking for text is usually a very good idea to start from, so let’s retype it from the screen:</p><pre>恋する姉妹の六重奏「セクステット」体験版Ver2をダウンロード頂きありがとうございます。</pre><p>If you have any problems typing Japanese (and I bet at least some of you have completely no idea even where to start), here’s a quick primer on how to do it with some effort in several easy steps.</p><h3>Typing Japanese in your PC without knowing anything about it</h3><p>As you can see, Japanese text consists of individual characters (usually fitting into a square), so we take them one by one and:</p><ul><li>check if it’s a punctuation mark first using the following line:</li></ul><pre>「…」、（）。</pre><p>If you’ve got lucky, just copy-n-paste it. Note that both Japanese “commas”, “periods” and “brackets” are special.</p><ul><li>if that’s not a punctuation, look for the character in this line:</li></ul><pre>あいうえおかきくけこさしすせそたちつてとなにぬねのはひふへほまみむめもやゆよらりるれろわを</pre><ul><li>then this line:</li></ul><pre>アイウエオカキクケコサシスセソタチツテトナニヌネノハヒフヘホマミムメモヤユヨラリルレロワ</pre><ul><li>still no luck? for example, you’ve got 恋 — then we’re doomed, it’s kanji; zoom your font up to 300–500% to make the details clearer and got to <a href="http://jisho.org/#radical">jisho.org, “search by radical” section</a>; once there, look closely at the table of the elements that form kanji characters (these are called “radicals”) and look for the parts that look like parts of the kanji; taking 恋 as an example — a quick mediation reveals that bottom part of this character is 心 — pressing down this radical shortens a list of possible kanji to browse dramatically — it’s no longer multiple thousands, but a few dozen; browsing through them, we’re bound to find fifth character in “10” section — that would be the 恋 we’re looking for;</li></ul><p>Sure it’s might be time consuming, but it’s better than nothing. Another semi-cheating method is to go to <a href="http://translate.google.com/">Google Translate</a>, turn Japanese input there, switch into “drawing” mode and try to draw what you see. In 80% of the cases, you’ll be lucky and you’ll get your kanji right away. In other 20%, looking up kanji in a dictionary like a jisho.org is an ultimately foolproof method.</p><p>Another note that I’d like to point out is that I’m not sure if that would be “Ver2” or “Ｖｅｒ２” — note that it’s not the different fonts I’m using here, but so called “full-width characters” — that’s completely distinct characters, to be found in Unicode somewhere around U+FF01..U+FF5E — obviously, if we’re comparing binary representations, we need to be exact.</p><p>The text we’ve copied will help us in two ways. First of all, we can translate it and find out what’s going on. Even if you don’t read Japanese, you can always stick it into Google Translate or some other automatic translator and get a rough idea. So, actually, it’s not the beginning of the story. Authors thank us for downloading the trial version, so it’s not the “first chapter”, but some kind of a preface, some words from the authors. Second, we can take this line, encode it as ShiftJIS (as we’ve figured out in the previous article, there are really high chances that this engine internals all use ShiftJIS) and seek the files for it. Let’s take a piece of it and do the encoding:</p><pre>$ echo ‘ダウンロード頂きありがとうございます’ | iconv -t sjis | hd<br>00000000 83 5f 83 45 83 93 83 8d 81 5b 83 68 92 b8 82 ab<br>00000010 82 a0 82 e8 82 aa 82 c6 82 a4 82 b2 82 b4 82 a2<br>00000020 82 dc 82 b7</pre><p>So, here’s the hex string we need to seek in all our files. Alas, we fail here. Life’s not gonna be that easy.</p><h3>ShiftJIS: how does it work</h3><p>Time to make yet another excursion into Japanese PC culture and get ourselves familiar with ShiftJIS encoding. They say that there are as many Japanese characters as stars in the sky. I dunno if that’s the case, but it’s hard to argue that at the very least there are much more characters in Japanese that characters in English. Thus, having 1 byte to encode them all (with 256 possible values) is barely feasible. Thus, ShiftJIS uses at least 1 byte and at most 2 bytes. As you might see <a href="http://www.kreativekorp.com/charset/encoding.php?name=Shift-JIS">from this table</a>, byte values of 00..7F are equal to ASCII (thus making ShiftJIS compatible with ASCII), and byte values of 81..9F and E0..EA mean that it’s a 2-byte combo. Note that for, again, for sake of ASCII compatibility, second byte <a href="http://www.kreativekorp.com/charset/encoding.php?name=Shift-JIS&amp;char=82">is not arbitrary</a>, but can be somewhere between 40 and FF.</p><h4>Shortest crash course in Japanese language ever possible</h4><p>Looks like we won’t escape yet another dive into Japanese language basics. So, to put it blunt, Japanese uses 3 groups of symbols:</p><ul><li><strong>hiragana</strong> — look something like ありがとうございます — i.e. simple round cursive shapes; ~50 glyphs, but there are a few variations like “big i = い, small i = ぃ”; 1 syllable = 1 glyph.</li><li><strong>katakana</strong> — look something like ダウンロード — i.e. square-like, straight lines, pretty useful for typesetting; it corresponds to the same sounds as hiragana, but is mostly used to write down the loanwords (ダウンロード = da-u-n-lo:-do = download).</li><li><strong>kanji</strong> — look something like 体験版 — i.e. complex drawings with lots of elements, fit into square shape; most of the time it’s kanji that give the most pain for Japanese language learners, and it’s many thousands of them.</li></ul><p>Also, there are a few other symbols, like punctuation. For our purposes (albeit proper Japanese scholar would like to kill me for such a hypocrisy), let’s say that they are mostly equal to those of European languages. There are:</p><ul><li>a “full stop” — 。</li><li>a “period” — 、</li><li>ellipses — …</li><li>quotes — 「」</li><li>full-width question mark — ？</li><li>full-width exclamation mark — ！</li><li>and some other, less frequently used symbols</li></ul><p>But there’s a catch, as you might have seen: there are no spaces in Japanese. The trick is simple: in Japanese text you have “significant” words (which are written with a mix of kanji and hiragana) and participles, which are always written in hiragana. This way, one can detect start of the words by changing of script. Let’s take the name of our game as an example: 恋する姉妹の六重奏</p><ul><li>恋 — kanji</li><li>する — hiragana</li><li>姉妹 — kanji</li><li>の — hiragana</li><li>六重奏 — kanji</li></ul><p>Ok, so what are we gonna do with all that stuff? Knowing that helps a lot in detection of obfuscated Japanese. For starters, let’s do a very simple thing: frequence stats. Taking a full ready-made script of any Japanese novel (there’s a couple of them available for download at <a href="https://tlwiki.org/">tlwiki</a>, for instance), we do a quick look up for the Unicode codepoint ranges for all 3 scripts we’re interested in and we run the following script on that (pun intended):</p><pre>stats = {}<br>$stdin.each_char { |c|<br>  t = case c.ord<br>      when 0x3041..0x309F then :hiragana<br>      when 0x30A0..0x30FF then :katakana<br>      when 0x4E00..0x9FCC then :kanji<br>      end<br>  stats[t] ||= 0<br>  stats[t] += 1<br>}<br>p stats</pre><p>and, voila, we’ve got something like that:</p><pre>{nil=&gt;72384, :kanji=&gt;5731, :hiragana=&gt;15377, :katakana=&gt;2241}</pre><p>That means that a typical Japanese text would have ~25% of kanji, 65% of hiragana and 10% of katakana:</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/388/1*OL9LKIV0qsXBzDkhdcoKiQ.png" /><figcaption>Knowing distribution of different classes of characters in Japanese aids statistical analysis methods</figcaption></figure><h3>Enough of the theory, give me some hands-on!</h3><p>Ok, time to get our tools ready and dive into it. As a very quick reminder for those who have forgotten our first article, we’re using a new tool named <a href="http://kaitai.io/">Kaitai Struct</a> to reverse engineer the binary files of unknown structure.</p><p>Kaitai Struct allows one to make some templates in .ksy markup language, which can be applied to the file (or, better yet, the files) to quickly visualize their inner structure in a nice tree view. As soon as you finish writing a .ksy, you’ve got a huge bonus as well: you can just compile the .ksy into a module in any supported target language.</p><p>By the way, since the last article, Kaitai Struct received lots of love and now, besides Java, JavaScript, Python &amp; Ruby, it supports C++, C#, Perl and PHP as well. If we’ll take a look at <a href="http://www.tiobe.com/tiobe-index/">some top programming language list</a>, that means top 10 are covered, and, out of top 20, if we’re not considering domain-specific stuff, only Delphi, Visual Basic, Swift and Go are missing. That said, I’ve never seen anyone using Delphi like in a decade and I would hardly imagine anyone using ancient Visual Basic (*not* modern .NET one) for reverse engineering.</p><p>We went over the basic syntax of Kaitai Struct templates in the first article, so, if you still haven’t read it or just want to brush it up —<a href="https://medium.com/@mnakamura1337/reverse-engineering-visual-novels-101-d0bc3bf7ab8"> that’s the best time to do it</a>.</p><p>Ok, let’s quickly take a look at hex dumps of a couple of files and hack up the following quick template for a start:</p><pre>meta:<br>  id: yks<br>  application: Yuka Engine<br>  endian: le<br>seq:<br>  - id: magic<br>    contents: [&quot;YKS001&quot;, 1, 0]<br>  - id: magic2<br>    contents: [0x30, 0, 0, 0, 0, 0, 0, 0, 0x30, 0, 0, 0]<br>  - id: unknown1<br>    type: u4<br>  - id: unknown2<br>    type: u4<br>  - id: unknown3<br>    type: u4<br>  - id: unknown4<br>    type: u4<br>  - id: unknown5<br>    type: u4<br>  - id: unknown6<br>    type: u4<br>  - id: unknown7<br>    type: u4</pre><p>One might see similarities with YKC format right away. Given that YKC format started with a header that had its own length in the very beginning, I might say it’s a safe bet that that fixed 0x30 in “magic2” field everything is actually the size of first header, so I went straight ahead and parsed everything up to 0x30. That gives us 7 integers, and we’ve got to guess what is what.</p><p>So, for Yoyaku.yks (file size is 27741 bytes):</p><pre>  [.] <a href="http://twitter.com/unknown1">@unknown1</a> = 1845<br>  [.] <a href="http://twitter.com/unknown2">@unknown2</a> = 7428<br>  [.] <a href="http://twitter.com/unknown3">@unknown3</a> = 795<br>  [.] <a href="http://twitter.com/unknown4">@unknown4</a> = 20148<br>  [.] <a href="http://twitter.com/unknown5">@unknown5</a> = 7593<br>  [.] <a href="http://twitter.com/unknown6">@unknown6</a> = 25<br>  [.] <a href="http://twitter.com/unknown7">@unknown7</a> = 0</pre><p>For trial_00100.yks (file is 91267 bytes long):</p><pre>  [.] <a href="http://twitter.com/unknown1">@unknown1</a> = 6433<br>  [.] <a href="http://twitter.com/unknown2">@unknown2</a> = 25780<br>  [.] <a href="http://twitter.com/unknown3">@unknown3</a> = 2376<br>  [.] <a href="http://twitter.com/unknown4">@unknown4</a> = 63796<br>  [.] <a href="http://twitter.com/unknown5">@unknown5</a> = 27471<br>  [.] <a href="http://twitter.com/unknown6">@unknown6</a> = 5<br>  [.] <a href="http://twitter.com/unknown7">@unknown7</a> = 0</pre><p>And, for the sake of comparison, something from “all”, for example, “all_00010.yks” (12968 bytes long):</p><pre>  [.] <a href="http://twitter.com/unknown1">@unknown1</a> = 933<br>  [.] <a href="http://twitter.com/unknown2">@unknown2</a> = 3780<br>  [.] <a href="http://twitter.com/unknown3">@unknown3</a> = 353<br>  [.] <a href="http://twitter.com/unknown4">@unknown4</a> = 9428<br>  [.] <a href="http://twitter.com/unknown5">@unknown5</a> = 3540<br>  [.] <a href="http://twitter.com/unknown6">@unknown6</a> = 1<br>  [.] <a href="http://twitter.com/unknown7">@unknown7</a> = 0</pre><p>What do we see here? First of all, I can bet a million that we’re looking at either offsets or some size sections in a given file, as for 91K file the numbers are between 25..63K, and for 12K file, they keep between 3..9K. Closer inspection reveals that probably only “unknown2”, “unknown4” and “unknown5” are offsets or sizes — they are all divisible by 4 and are large enough. “unknown7” always seems to be zero. “unknown6” seems to be small enough, so it’s probably a counter for some entities. It might be the number of scenes / sprites / backgrounds, size of memory pool reserved for variables in our virtual machine, or something like that.</p><p>After 0x30, even with a naked eye (I mean, with just a hex editor), one can see a range of steadily increasing numbers (ok, <em>almost</em> steadily increasing). Probably it is <em>not</em> the byte code: it the byte code you’d expect to see lots of repetitive patterns. Most likely there are also some kinds of offsets — for example, these could be offsets to starts of statements in the byte code or offsets to variable length strings in some other section or something like that. Given that we’ve identified first possible section and given that we have 7 unknown values in the header, it’s only natural to give it a try and check if anything of that looks like:</p><ul><li>a size of this section</li><li>an absolute offset of the end of this section = start of next section</li><li>number of 4-byte integers in this section</li></ul><p>That said, we hit the bulls eye in the first or second shot. “unknown1” proves to match the quantity of entities in our first section, and “unknown2” seems to be a pointer to the start of the next section. In practice, that’d mean that the following is always true:</p><blockquote>unknown2 = 0x30 + unknown1 * 4</blockquote><p>Let’s jot that down, and while we’re at it, we’ll move our header description into distinct type “header”, and we’ll use names like sect1..sectX for the following sections that we’ll discover:</p><pre>seq:<br>  - id: header<br>    type: header<br>  - id: sect1<br>    size: header.sect2_ofs - 0x30<br>    type: sect1<br>types:<br>  header:<br>    seq:<br>      - id: magic<br>        contents: [&quot;YKS001&quot;, 1, 0]<br>      - id: magic2<br>        contents: [0x30, 0, 0, 0, 0, 0, 0, 0, 0x30, 0, 0, 0]<br>      - id: sect1_qty<br>        type: u4<br>      - id: sect2_ofs<br>        type: u4<br>      - id: unknown3<br>        type: u4<br>      - id: unknown4<br>        type: u4<br>      - id: unknown5<br>        type: u4<br>      - id: unknown6<br>        type: u4<br>      - id: unknown7<br>        type: u4<br>  sect1:<br>    seq:<br>      - id: entries<br>        type: u4<br>        repeat: expr<br>        repeat-expr: _root.header.sect1_qty</pre><p>“trial_00100” turns out to look like that with our new .ksy:</p><pre>  [-] <a href="http://twitter.com/header">@header</a><br>    [.] <a href="http://twitter.com/magic">@magic</a> = 59 4b 53 30 30 31 01 00<br>    [.] <a href="http://twitter.com/magic2">@magic2</a> = 30 00 00 00 00 00 00 00 30 00 00 00<br>    [.] <a href="http://twitter.com/sect1_qty">@sect1_qty</a> = 6433<br>    [.] <a href="http://twitter.com/sect2_ofs">@sect2_ofs</a> = 25780<br>    [.] <a href="http://twitter.com/unknown3">@unknown3</a> = 2376<br>    [.] <a href="http://twitter.com/unknown4">@unknown4</a> = 63796<br>    [.] <a href="http://twitter.com/unknown5">@unknown5</a> = 27471<br>    [.] <a href="http://twitter.com/unknown6">@unknown6</a> = 5<br>    [.] <a href="http://twitter.com/unknown7">@unknown7</a> = 0<br>  [-] <a href="http://twitter.com/sect1">@sect1</a><br>    [-] <a href="http://twitter.com/entries">@entries</a> (6433 = 0x1921 entries)<br>      [.]    0 = 6<br>      [.]    1 = 7<br>      [.]    2 = 3<br>      [.]    3 = 3<br>      [.]    4 = 4<br>      ...<br>      [.] 6425 = 2371<br>      [.] 6426 = 2372<br>      [.] 6427 = 34<br>      [.] 6428 = 1<br>      [.] 6429 = 2373<br>      [.] 6430 = 2374<br>      [.] 6431 = 1<br>      [.] 6432 = 2375</pre><p>It is obvious now that our assumption about “sect1” entries being increasing offsets or something is not entirely correct. There are not <em>only</em> increasing numbers, there is a fair deal of repetitions, thus these actually <em>could be</em> the bytecode. Increasing numbers seem to follow the pattern of starting with 0 or 1 and increasing steadily by 1 up to 2375. As one might notice, “unknown3” = 2376 — and it looks just like the total number of these values. That probably means that our proposed “bytecode” in sect1 references some other table with exactly 2376 different values (probably indexed from 0 up to 2375 inclusive). What could it be?</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/534/1*zPqLkfNzN6r7tgCfSBzpjw.png" /><figcaption>Increasing numbers in 16-byte records neatly lined up</figcaption></figure><p>I guess it’s evident that these are 16-byte long records (exactly 1 line here), and inside they carry something that looks very much like steadily increasing indices or offsets. A stupid guess, may be there are 2376 of them? Let’s check that out, renaming “unknown3” to “sect2_qty” and adding this trivial piece to collect “sect2” as 16-byte records:</p><pre>  - id: sect2<br>    size: 16<br>    repeat: expr<br>    repeat-expr: header.sect2_qty</pre><p>and looks like we hit the jackpot. It’s exactly that:</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*Cu9ohQrAf20wjWoAxuVLvQ.png" /><figcaption>End of “sect2”, in assumption that there are exactly “sect2_qty” 16-byte records in it</figcaption></figure><p>Even with the naked eye one can see that these strict 16-byte records end exactly at our assumed end of “sect2” and that means that there are exactly “sect2_qty” of them. Something completely different lies beyond them. How does it look? That’s definitely not 4-byte integers, almost everything seems to be non-zero. After looking at these for several minutes, I think I can’t make a good guess on what it is. There are no periodic patterns, nothing. Only thing worth noticing is lots of 0xaa bytes. Tons of 0x28 too, and these can be encountered always on every second byte — no two 0x28 come in sequence. Let’s check out the end of file — does it look the same there, or we’ve got something else, i.e. more sections? Nah, same patterns seem to occur there as well:</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/531/1*Mp_GYoBhqdL0szbK5T2psQ.png" /><figcaption>End of file. Abudance of <strong>0xaa</strong> and <strong>0x28</strong>. End of “sect3”?</figcaption></figure><p>Thus that’s a safe bet that we’re observing a third and final section of this file. There’s nothing beyond that. Let’s jump back to the very beginning and recall what we were going to find here. Header? Check. Bytecode? Check. Text? Nope. Probably here they are, but encoded in some way to make it less evident. Are they compressed? Probably not, if they were, there won’t be so many repetitions of <strong>0xaa</strong> and <strong>0x82</strong>. Actually, repetitive 0x28 in something like</p><pre>28 08 28 1b 28 0e 28 6c 26 6f 28 07 3a 14 28 6b</pre><p>looks really, really suspicious. Rewind to our short excursion into Japanese ShiftJIS encoding and get a specimen of a normal Japanese text in ShiftJIS:</p><pre>82 a0 82 e8 82 aa 82 c6 82 a4 82 b2 82 b4 82 a2</pre><p>Is it just me, or it’s a simple substitution cypher, where every single byte is replaced with some other single byte using some mapping table. Ok, what shall we do to encode <strong>0x82</strong> as <strong>0x28</strong>? Of course, that could be any arbitrary table, but most of the times all humans are lazy and thus opt for ready-made functions. It’s not like there are tons of them. Actually, I can only name 3 from top of my head:</p><ul><li><strong>addition/subtraction</strong> — one can just add (or subtract, which is the same operation from CPU’s point of view) some constant to every byte, wrapping the result around in case of overflow</li><li><strong>ROL/ROR</strong> — a <a href="https://en.wikipedia.org/wiki/Circular_shift">circular shift</a> by a certain amount of bits; note that circular shift right or left by 4 bits just swaps 2 hexadecimal digits in every byte</li><li><strong>exclusive or (XOR)</strong> — one can do XOR operation, combining each byte with some other fixed byte; an approach which is definitely most overused, but still effective and thus still popular</li></ul><p>There are quite a few heavy-duty tools like <a href="https://blog.didierstevens.com/programs/xorsearch/">XORSearch</a>, that can help you to brute-force such simple algorithms, but in this case, it’s even simpler, so I’ve got a match on second try. Lots of <strong>0xaa</strong> bytes allows us to guess that there are many zeroes in the stream, which, XORed with <strong>0xaa</strong>, give us lots of <strong>0xaa</strong>’s. Besides, <strong>0x82</strong> ^ <strong>0xaa</strong> is mysteriously <strong>0x28 </strong>(and XOR operation is so versatile that you can derive that by doing <strong>0x82 ^ 0x28 = 0xaa</strong>).</p><p>To be frank, <strong>0xaa</strong> is one of the most abused XOR patterns, which one has to try almost immediately (akin to passwords “123456”, “qwerty”, or top 10 from <a href="https://github.com/danielmiessler/SecLists/blob/master/Passwords/10k_most_common.txt">lists like these</a> when brute-forcing passwords). <strong>0xaa</strong> is <strong>0b10101010</strong>, that is, XORing a value with <strong>0xaa</strong> toggles every 2nd bit in it. Yeah, a lot of people still think it’s a cool idea.</p><p>Fortunately, Kaitai Struct supports such cases with a <strong>process:</strong> clause. It’s enough to add the following:</p><pre>  - id: sect3<br>    size-eos: true<br>    process: xor(0xaa)</pre><p>and, here you go, we’re finally observing the rich inner world of string constants in our script:</p><pre>000000: 69 66 00 c8 00 00 00 47 6c 6f 62 61 6c 46 6c 61<br>000010: 67 00 3d 00 ff ff 00 00 01 00 00 00 3d 00 7b 00<br>000020: 0d 00 00 00 57 69 6e 64 6f 77 4e 61 6d 65 53 65<br>000030: 74 00 97 f6 82 b7 82 e9 8e 6f 96 85 82 cc 98 5a<br>000040: 8f 64 91 74 28 83 66 83 6f 83 62 83 4f 29 81 7c<br>000050: 46 69 6c 65 20 3a 20 74 72 69 61 6c 68 5f 6d 61<br>000060: 79 75 2e 79 6b 73 00 7d 00 09 00 00 00 44 72 61<br>000070: 77 53 74 6f 70 00 47 72 61 70 68 69 63 48 69 64<br>000080: 65 00 0a 00 00 00 54 72 61 6e 73 69 74 69 6f 6e<br>000090: 00 02 00 00 00 64 00 00 00 0a 00 00 00 0b 00 00<br>0000a0: 00 47 72 61 70 68 69 63 4c 6f 61 64 00 00 00 00</pre><p>or, in ASCII:</p><pre>000000: if.....GlobalFla<br>000010: g.=.........=.{.<br>000020: ....WindowNameSe<br>000030: t........o.....Z<br>000040: .d.t(.f.o.b.O).|<br>000050: File : trialh_ma<br>000060: yu.yks.}.....Dra<br>000070: wStop.GraphicHid<br>000080: e.....Transition<br>000090: .....d..........<br>0000a0: .....d..........</pre><p>To be honest, we’ve got really lucky here: there are a lot of ASCII strings, which make our life easier. From the first glance, one might say that there’s just a bunch of C-style zero terminated strings mashed together, but careful inspection reveal that is not exactly the case. Sure, strings are in there, but other than that, we’ve got more binary between it too, like</p><pre>ff ff 00 00 01 00 00 00</pre><p>or</p><pre>02 00 00 00 64 00 00 00 0a 00 00 00 0b 00 00 00</pre><p>There’s one printable ASCII symbol in it (`d` = 0x64), but probably these are <em>not</em> strings. And, finally, we’ve got the original novel text in Japanese in ShiftJIS with all these 0x82s.</p><h3>Hooray, we’re done?</h3><p>Ok, let’s summarize what we’ve got:</p><ol><li><strong>sect1</strong>, consisting of 4-byte integers (presumably, it <em>is</em> the bytecode); at least some of these 4-byte integers are references to 16-byte records in sect2</li><li><strong>sect2</strong>, consisting of 16-byte records with some increasing numbers inside (presumably — offsets referencing some other section, maybe <strong>sect3</strong>?)</li><li><strong>sect3</strong>, consisting mostly of null-terminated ShiftJIS-encoded strings and some more intricate data (presumably — it’s the string resources and other constants that bytecode references)</li></ol><p>And, while we’re still enjoying this little victory, I guess we’ll call it a day. This article became much longer than it was originally expected (and definitely much longer than your average Medium.com article). Actually, if we were translating this novel, what we’ve achieved today is enough to pass the torch to the translators. For that, all we need to do is rip out all the Japanese texts from sect3 and hand them over for translation. Just iterating over the sect3 contents, ignoring all unprintable stuff gives us something like (of course, you need to convert it to your system’s encoding, probably UTF-8, if you’re not on a ShiftJIS system), yields:</p><pre>恋する姉妹の六重奏(デバッグ)－File : trialh_mayu.yks<br>まゆ<br>「きゃっ……！！」<br>教育的指導を兼ねて、お望み通りメチャクチャにしてやろうじゃないか！！<br>「あっ……お、おにぃっ……」<br>自分から誘っておきながら、不安そうな表情を浮かべるまゆ。<br>そんなまゆを、ソファーに押しつけて……胸を露出させ、股間が丸見えになる体勢を強いる。<br>「んぁっ……」</pre><h3>What’s next?</h3><p>My thanks to everyone who had the patience to follow up to this place. Stay tuned for the next article where we’ll dig in into the bytecode itself and will try to understand how all discovered sections are interlinked. Be sure to subscribe, if you don’t want to miss it.</p><p>A summary of useful links:</p><ul><li>Kaitai Struct — <a href="http://kaitai.io/">http://kaitai.io/</a></li><li>PeasSoft — <a href="http://peassoft.com/">http://peassoft.com/</a> (warning, NSFW!)</li><li>One can find specifications and tools for a few visual novel engines (in .ksy format too) at <a href="https://github.com/mnakamura1337/">my GitHub projects</a>.</li><li>You can also read this article <a href="https://habrahabr.ru/post/309414/">in Russian</a>.</li></ul><p>If you feel like translating this tutorial into your language to help more people learn reverse engineering — it is CC-BY-SA-licensed, so you’re totally welcome!</p><p>If you like this article and found it helpful, please click ❤ below to recommend it to others, or share it with your friends in social networks. It means a lot to me and motivates me to write more :)</p><figure><a href="http://bit.ly/HackernoonFB"><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*0hqOaABQ7XGPT-OYNgiUBg.png" /></a></figure><figure><a href="https://goo.gl/k7XYbx"><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*Vgw1jkA6hgnvwzTsfMlnpg.png" /></a></figure><figure><a href="https://goo.gl/4ofytp"><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*gKBpq1ruUi0FVK2UM_I4tQ.png" /></a></figure><blockquote><a href="http://bit.ly/Hackernoon">Hacker Noon</a> is how hackers start their afternoons. We’re a part of the <a href="http://bit.ly/atAMIatAMI">@AMI</a> family. We are now <a href="http://bit.ly/hackernoonsubmission">accepting submissions</a> and happy to <a href="/service/mailto:partners@amipublications.com">discuss advertising &amp; sponsorship</a> opportunities.</blockquote><blockquote>If you enjoyed this story, we recommend reading our <a href="http://bit.ly/hackernoonlatestt">latest tech stories</a> and <a href="https://hackernoon.com/trending">trending tech stories</a>. Until next time, don’t take the realities of the world for granted!</blockquote><figure><a href="https://goo.gl/Ahtev1"><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*35tCjoPcvq6LbB3I6Wegqw.jpeg" /></a></figure><img src="https://medium.com/_/stat?event=post.clientViewed&referrerSource=full_rss&postId=9258f547262a" width="1" height="1" alt=""><hr><p><a href="https://medium.com/hackernoon/reverse-engineering-visual-novels-101-part-2-9258f547262a">Reverse engineering visual novels 101, part 2</a> was originally published in <a href="https://medium.com/hackernoon">HackerNoon.com</a> on Medium, where people are continuing the conversation by highlighting and responding to this story.</p>]]></content:encoded>
        </item>
        <item>
            <title><![CDATA[Reverse engineering visual novels 101]]></title>
            <link>https://medium.com/hackernoon/reverse-engineering-visual-novels-101-d0bc3bf7ab8?source=rss-6eb056f6c84------2</link>
            <guid isPermaLink="false">https://medium.com/p/d0bc3bf7ab8</guid>
            <category><![CDATA[programming]]></category>
            <category><![CDATA[japanese]]></category>
            <category><![CDATA[reverse-engineering]]></category>
            <category><![CDATA[visual-novel]]></category>
            <category><![CDATA[hacking]]></category>
            <dc:creator><![CDATA[Masumi Nakamura]]></dc:creator>
            <pubDate>Thu, 14 Jul 2016 03:14:25 GMT</pubDate>
            <atom:updated>2017-07-13T21:48:09.987Z</atom:updated>
            <cc:license>https://creativecommons.org/licenses/by-sa/4.0/</cc:license>
            <content:encoded><![CDATA[<figure><img alt="" src="https://cdn-images-1.medium.com/max/477/1*CqiFdFj7o4BVDsTjNCXN1w.png" /></figure><p>I’d like to make a confession: I love visual novels. For those of you who aren’t in the trend, visual novels are something inbetween of interactive books, games-that-mostly-consist-of-reading-lotsa-text, and radio plays with images. Needless to say that the vast majority of them comes from Japan. I could say that for the last 5 years I’m totally into it, ignoring most other forms of entertainment media, like paper books, audio books or TV.</p><p>Since the early childhood I’ve been an avid tinkerer: I just love to get inside things and figure out how they work. Such an attitude slowly got me a reverse engineer and malware analyst position in a well-known national company, so I thought: why don’t I combine these two hobbies and see what would happen?</p><p>I had these thoughts for several years already, but everything changed when I encountered <a href="http://kaitai.io/">Kaitai Struct</a> framework this spring. It’s a new framework for binary structures reverse engineering (although the authors seem to insist that it’s purely for peaceful purposes :)) The basic idea is simple, yet catchy: you use a special markup language to declaratively mark up binary data with a structure — and, voila, you compile it with a special compiler and you’ve got yourself a parsing library in any of supported programming languages. There is also a handy visualizer / hex viewer available. Shall we give it a spin?</p><p>To make it practical and demonstrate typical stuff one encounters while doing basic reverse engineering work, I propose that we start with something not-so-trivial, namely a beautiful visual novel called <a href="https://vndb.org/v13353">Koisuru Shimai no Rokujuso</a> (originally 恋する姉妹の六重奏) by PeasSoft. It’s a fun, easy-going romantic comedy with a splendid visual part that’s PeasSoft is usually famous for. As a reverse engineering object, it’s also nice thing to explore, as it looks like we’ll be kind of breaking fresh ground. And it’s much more interesting that just duplicating work of others on well-explored stuff like <a href="http://kikyou.info/tvp/">Kirikiri</a> or <a href="https://www.renpy.org/">Ren’Py</a>.</p><h3>Pre-flight check</h3><p>First of all, let’s take a look at the list of stuff we’ll need:</p><ul><li><a href="http://kaitai.io/">Kaitai Struct </a>— compiler, visualizer, and runtime library for your favorite programming language</li><li><a href="http://java.com/download/">Java runtime </a>— unfortunately, Kaitai Struct is written in Scala and thus requires JRE to run</li><li>Ruby — Kaitai Struct visualizer is written in Ruby</li><li>any of languages supported by KS (at time of writing, this is C++, C#, Java, JavaScript, Ruby and Python) — I’ll be using Ruby myself, but it’s not that important, as we’ll be literally using it to write several lines of code at the conclusion of our exploration</li><li>some kind of a hex editor; it’s not important which one, they all suck :) I use <a href="https://utils.kde.org/projects/okteta/">Okteta</a>, but fell free to use anything you like, as long as it can do the basic stuff like viewing hex dump, jumping to an address and quickly copying marked up fragment into a file</li></ul><h3>Getting ‘em ready</h3><p>There we go, now we need an object of our dissection, which is a visual novel distribution. We’ve got lucky here, PeasSoft legally offers trial versions of their visual novels for free download at their site. Trial version is more than enough for us to get acquantied with their formats. Seek for the page that looks like this at their site:</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*GVxDJQ1ELX74NVXOYnGb8A.png" /><figcaption>Trial version download page</figcaption></figure><p>That blue list with numbers on the left is actually a pack of mirror links — you can use any one them to download the distro.</p><h3>Think-think-think</h3><p>Having downloaded it, let’s start with the basic intelligence. What do we know already about our target? At least the version we’ve downloaded runs on Windows OS using Intel CPUs (actually there *is* an Android version that runs on ARMs, but it’s sold only at Japanese app markets, and it’s not so easy to extract from a phone). So, what can we assume given that it’s Windows/Intel?</p><ul><li>integer numbers in binary formats will be using little-endian encoding</li><li>Windows programmers still live in a stone age and use Shift-JIS encoding (and not UTF-8 which rest of the world uses)</li><li>end-of-line markers, if we’ll ever encounter them, will be using “\r\n”, and not just “\n”</li></ul><p>Quick overview of our loot shows us the following:</p><ul><li>data01.ykc — 8,393,294</li><li>data02.ykc — 560,418,878</li><li>data03.ykc — 219,792,804</li><li>sextet.exe — 978,944</li><li>AVI/op.mpg — 122,152,964</li></ul><p>So, here we have <strong>a single .exe file</strong> (obviously, an executable engine), <strong>a few enormous .ykc files</strong> (most likely —content archives or containers) and <strong>op.mpg</strong> —an opening video (one can easily open it with any video player).</p><p>It could come useful to do a quick inspection of exe file in a hex editor. Most modern developers are sane enough and have finally switched to use popular ready-made libraries for image / music / sound processing, instead of inventing their own in-house compression formats. And all these libraries usually bear some signatures which can be easily spotted by a naked eye. Things to look for:</p><ul><li>“libpng version 1.0.8 — July 24, 2000” — libpng usage, it means that images will be in .png format</li><li>“zlib version error”, “Unknown zlib error” — zlib markers, which mean that zlib compression will be employed; actually, it can be a false positive, as zlib compression is embedded in png library, so it might be just the part of libpng</li><li>“Xiph.Org libVorbis I 20020717” — libvorbis, it means that music / sounds / voices might use ogg/vorbis format</li><li>“Corrupt JPEG data”, “Premature end of JPEG file” —a few strings from libjpeg; if they’re here — it means that the chances are that the engine can work with JPEG images too</li><li>“D3DX8 Shader Assembler Version 0.91” — something inside the engine uses D3DX8 shaders</li><li>lots of strings like “Microsoft Visual C++ Runtime Library”, “`local vftable’”, “`eh vector constructor iterator’” and so on reveal that this exe is linked with Microsoft C++ library, thus it was originally written in C++; actually, one can even derive an exact version of compiler (and a library), but it would be of little use for us now — we’re not going to disassemble exe or anything, we’re still attempting to do a fair “clean room” job</li></ul><p>It’s also a good idea to look for stuff like “version”, “copyright”, “compiler”, “engine”, “script” — and, given that it’s a Windows exe, don’t forget to look for it in 2-byte encodings like UTF16-LE — chances are that you’ll end up with something interesting. In our case, we’ve got “Yuka Compiler Error”, “YukaWindowClass”, “YukaApplicationWindowClass”, “YukaSystemRunning”, and mentions of “start.yks” and “system.ykg”. It would be a fair bet to say that developers named their engine “Yuka” and all the files related to it have extensions which start with “yk” — “ykc”, “yks”, “ykg”. Also we can spot “CDPlayMode” and “CDPlayTime” — probably it means that the engine can play music tracks from Audio CDs, and “MIDIStop” with “MIDIPlay” suggest that there’s support for MIDI music too.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/672/1*VV1OzK_dsLdiyQ1hPWG_oA.png" /><figcaption>Various fancy signature strings inside .exe give us some bold hints</figcaption></figure><p>To sum it all up, it means that:</p><ul><li>images would be probably in .png and .jpeg formats, which is actually a very good news — we won’t need to mess with custom compression or anything</li><li>music, sounds and voices probably would use .ogg files (but may also use MIDI or CDDA, though unlikely — trail version is a file download, not a physical CD)</li></ul><h3>Let’s get dangerous</h3><p>Ok, time to roll up our sleeves and get our hands dirty. There are several files — that is actually very good news too. If you do reverse engineering, having several specimens could be a very valuable asset, as you can fully employ statistical methods, comparing these specimens to each other. It’s much harder to guess what that 7F 02 00 00 might mean if that’s the only thing you have.</p><p>Let’s check if these files all have the same format. Judging from that they all follow the same “data*.ykc” pattern — they do. Checking beginnings of the files reveals that they all start with “YKC001\0\0” — which proves us right.</p><p>Another quick check: let’s see if they are compressed. Just take any compressor and try to compress one file, then check compression ratio. I’ve just used zip:</p><ul><li>before — 8,393,294 bytes</li><li>after— 6,758,313 bytes</li></ul><p>Yeah, it applies some compression, but not too much. Chances are that it’s uncompressed, or at least some files would be uncompressed. Actually, if there are .pngs or .oggs in that archive, they are already well-compressed, so it looks like the truth.</p><p>Basic theory suggests that every archive would have some sort of header, something an application would start reading its archive with, and 99% of file would be filled with archive contents — either files or some blocks of data. Note the header is not always at the very beginning of the file — it might be at some offset at the end of file, or at some offset from the beginning. It’s highly unlikely, though, that the header would be right in the middle of contents.</p><p>Checking the beginning of the files reveals:</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/659/1*H-D00bHzbNoXntDIFO3O0A.png" /></figure><p>There we go:</p><ul><li>59 4B 43 30 │ 30 31 00 00 — it’s just a signature, some magic string to check that the file is actually a container; it’s “YKC001” in ASCII — chances are that it means something like “Yuka Container”, version 001</li><li>18 00 00 00 │ 00 00 00 00 │ 1A 00 80 00 │ 34 12 00 00 — that’s the header</li><li>and then we see the body of some kind of the file; it’s very easy to see in data02.ykc — archive starts with a text file, something like a config or some script language, sporting lines like “WindowSize = 1280, 800”, “TransitionWaitType = 2”, etc</li></ul><p>Let’s compare the headers of all three files we have:</p><pre>data01.ykc: 18 00 00 00 │ 00 00 00 00 │ 1A 00 80 00 │ 34 12 00 00<br>data02.ykc: 18 00 00 00 │ 00 00 00 00 │ 4E E1 66 21 │ F0 6E 00 00<br>data03.ykc: 18 00 00 00 │ 00 00 00 00 │ 5C E1 18 0D │ 48 E4 00 00</pre><p>I don’t know what “18 00 00 00 │ 00 00 00 00” is yet, but it doesn’t really matter as it’s all the same everywhere. The other two fields are much more interesting — they look a lot like two 4-byte integers. So, it’s time to grab onto Kaitai Struct and start hacking away a rough sketch of our format:</p><pre>meta:<br>  id: ykc<br>  application: Yuka Engine<br>  endian: le<br>seq:<br>  - id: magic<br>    contents: [&quot;YKC001&quot;, 0, 0]<br>  - id: magic2<br>    contents: [0x18, 0, 0, 0, 0, 0, 0, 0]<br>  - id: unknown1<br>    type: u4<br>  - id: unknown2<br>    type: u4</pre><p>Nothing too that scary, isn’t it? Actually, .ksy is just a plain YAML files. That “meta” section is made up of our early findings — i.e. that we’re working on “ykc” files, the application that it uses is called “Yuka Engine” (it’s just a friendly reminder for fellow researchers, like a comment — it doesn’t really affect parsing) and we’ll be using little endian integers by default (that is “endian: le”).</p><p>Then we have a “seq” section which describes how to parse the file — that’s an list of fields. Each field must have a name (“id”) — and that’s exactly we’re working for — and description of its contents. We were using 2 clauses here:</p><ul><li>“contents: [0x18, 0, 0, 0, 0, 0, 0, 0]” marks up a field with the fixed contents. It actually means that during the parsing KS would automatically read the right number of bytes and compare it with given pattern. If they won’t match, an exception would be thrown.</li><li>“type: u4” marks up “u”nsigned integer, 4 bytes long field. It would use default endianness, which we’ve specified in “meta”.</li></ul><p>Let’s try our ksy file in a visualizer:</p><pre>ksv data01.ykc ykc.ksy</pre><p>and, lo and behold, our data01.ykc laid out nicely:</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*Fd_YqK-f-QAB85DV6QiScg.png" /><figcaption>Kaitai Struct visualizer in all its console glory</figcaption></figure><p>Yeah, the visualizer is console based, so you can start feeling like a Real Hacker they show in the movies right about now. But let’s take a look at the tree structure first:</p><pre>[-] [root]<br>  [.] <a href="http://twitter.com/magic">@magic</a> = 59 4b 43 30 30 31 00 00<br>  [.] <a href="http://twitter.com/magic2">@magic2</a> = 18 00 00 00 00 00 00 00<br>  [.] <a href="http://twitter.com/unknown1">@unknown1</a> = 8388634<br>  [.] <a href="http://twitter.com/unknown2">@unknown2</a> = 4660</pre><p>One can use arrow keys in the visualizer to walk through all these fields, use “Tab” to jump to hex viewer and back and use “Enter” to open closed tree nodes, show the instances (we’ll talk about them later) and view the hex dumps full screen. To make article easier to read, I won’t be showing full screenshots of the visualizer, only the interesting parts of the tree as text.</p><p>Ok, that was data01.ykc, let’s check out data02.ykc:</p><pre>[-] [root]<br>  [.] <a href="http://twitter.com/magic">@magic</a> = 59 4b 43 30 30 31 00 00<br>  [.] <a href="http://twitter.com/magic2">@magic2</a> = 18 00 00 00 00 00 00 00<br>  [.] <a href="http://twitter.com/unknown1">@unknown1</a> = 560390478<br>  [.] <a href="http://twitter.com/unknown2">@unknown2</a> = 28400</pre><p>and data03.ykc:</p><pre>[-] [root]<br>  [.] <a href="http://twitter.com/magic">@magic</a> = 59 4b 43 30 30 31 00 00<br>  [.] <a href="http://twitter.com/magic2">@magic2</a> = 18 00 00 00 00 00 00 00<br>  [.] <a href="http://twitter.com/unknown1">@unknown1</a> = 219734364<br>  [.] <a href="http://twitter.com/unknown2">@unknown2</a> = 58440</pre><p>Not that much, actually. There’s not a file directory or anything. Let’s note the sizes of original container files and see if any of these could be offsets or pointers inside the file:</p><ul><li>data01.ykc — 8393294 <a href="http://twitter.com/unknown1">@unknown1</a> = 8388634</li><li>data02.ykc — 560418878 <a href="http://twitter.com/unknown1">@unknown1</a> = 560390478</li><li>data03.ykc — 219792804 <a href="http://twitter.com/unknown1">@unknown1</a> = 219734364</li></ul><p>Wow, looks like we’ve hit the bullseye. Let’s check out what’s happening at that offset in the file:</p><pre>meta:<br>  id: ykc<br>  application: Yuka Engine<br>  endian: le<br>seq:<br>  - id: magic<br>    contents: [&quot;YKC001&quot;, 0, 0]<br>  - id: magic2<br>    contents: [0x18, 0, 0, 0, 0, 0, 0, 0]<br>  - id: unknown_ofs<br>    type: u4<br>  - id: unknown2<br>    type: u4<br>instances:<br>  unknown3:<br>    pos: unknown_ofs<br>    size-eos: true</pre><p>We’ve added another field named “unknown3”. However, this time it’s not in “seq” section, but in “instances” section. It’s actually the very same thing, but “instances” is used to describe fields which are not going in sequence, thus they can be anywhere in the stream and require note of position (“pos”) to start parsing from. So, our “unknown3” starts with “unknown_ofs” (“pos: unknown_ofs”) and spans up to the end of file (=stream, so “size-eos: true”). As we have no idea what we’ll get there, so far it will be read just as a byte stream. Nothing too fancy, but let’s take a look:</p><pre>[-] [root]<br>  [.] <a href="http://twitter.com/magic">@magic</a> = 59 4b 43 30 30 31 00 00 <br>  [.] <a href="http://twitter.com/magic2">@magic2</a> = 18 00 00 00 00 00 00 00 <br>  [.] <a href="http://twitter.com/unknown_ofs">@unknown_ofs</a> = 8388634<br>  [.] <a href="http://twitter.com/unknown2">@unknown2</a> = 4660<br>  [-] unknown3 = 57 e7 7f 00 0a 00 00 00 18 00 00 00 13 02 00 00…</pre><p>Hey, note the length of that “unknown3”. It looks exactly like “unknown2”. So it turns out that the first header of YKC file is actually not the header itself, but a reference to some other point of file to find the real header. Let’s fix our .ksy file to add this knowledge:</p><pre>meta:<br>  id: ykc<br>  application: Yuka Engine<br>  endian: le<br>seq:<br>  - id: magic<br>    contents: [&quot;YKC001&quot;, 0, 0]<br>  - id: magic2<br>    contents: [0x18, 0, 0, 0, 0, 0, 0, 0]<br>  - id: header_ofs<br>    type: u4<br>  - id: header_len<br>    type: u4<br>instances:<br>  header:<br>    pos: header_ofs<br>    size: header_len</pre><p>Nothing too complex here: we’ve just renamed “unknown” fields to have more meaningful names and replaced “size-eos: true” (which means reading everything up to the end of file) with “size: header_len” (which specifies exact amount of bytes to read). Probably that’s pretty close to original idea. Load it up once again and now let’s focus on that field we’ve named “header”. It looks something like that in data01.ykc:</p><pre>000000: 57 e7 7f 00 0a 00 00 00 18 00 00 00 13 02 00 00<br>000010: 00 00 00 00 61 e7 7f 00 0b 00 00 00 2b 02 00 00<br>000020: db 2a 00 00 00 00 00 00 6c e7 7f 00 11 00 00 00<br>000030: 06 2d 00 00 92 16 00 00 00 00 00 00 7d e7 7f 00</pre><p>in data02.ykc:</p><pre>000000: d1 2b 66 21 0c 00 00 00 18 00 00 00 5a 04 00 00<br>000010: 00 00 00 00 dd 2b 66 21 14 00 00 00 72 04 00 00<br>000020: 26 1a 00 00 00 00 00 00 f1 2b 66 21 16 00 00 00<br>000030: 98 1e 00 00 a8 32 00 00 00 00 00 00 07 2c 66 21</pre><p>in data03.ykc:</p><pre>000000: ec 30 17 0d 26 00 00 00 18 00 00 00 48 fd 00 00<br>000010: 00 00 00 00 12 31 17 0d 26 00 00 00 60 fd 00 00<br>000020: 0d 82 03 00 00 00 00 00 38 31 17 0d 26 00 00 00<br>000030: 6d 7f 04 00 d0 85 01 00 00 00 00 00 5e 31 17 0d</pre><p>At the first glance, it doesn’t make any sense at all. On the second thought, though, a sequence of repeating bytes catches our eye. That is `e7 7f` in the first file, `2b 66` in the second, and `30 17` with `31 17` in the third. Actually, it looks very much like that we’re dealing with fixed length records here, 0x14 (20 decimal) bytes long. By the way, this hypothesis goes well with header lengths in all three files too: all three of 4660, 28400, and 58440 are divisible by 20. Let’s give it a try:</p><pre>meta:<br>  id: ykc<br>  application: Yuka Engine<br>  endian: le<br>seq:<br>  - id: magic<br>    contents: [&quot;YKC001&quot;, 0, 0]<br>  - id: magic2<br>    contents: [0x18, 0, 0, 0, 0, 0, 0, 0]<br>  - id: header_ofs<br>    type: u4<br>  - id: header_len<br>    type: u4<br>instances:<br>  header:<br>    pos: header_ofs<br>    size: header_len<br>    type: header<br>types:<br>  header:<br>    seq:<br>      - id: entries<br>        size: 0x14<br>        repeat: eos</pre><p>Check out what happened with “header” instance here. It’s still positioned at “header_ofs” and has size of “header_len” bytes, but it’s no longer a mere byte array. It has its own type, “type: header”. This means that we can specify a custom type and this type will be used to process the given field. Here we go, it’s right below, in that “types:” section. As you might have already guessed, actually “type” follows exactly the same format as the main file (i.e. root) — one can use the same “seq” section to specify the sequence of subfields, “instances”, it can have its own subtypes (“types”), etc, etc.</p><p>So, we’ve specified a “header” type, which consists of a single field — “entries”. We know that this field need to be 0x14 bytes long (“size: 0x14”), but we demand it to be repeated as long as possible (i.e. up to end of the stream — that is “repeat: eos”).</p><p>By the way, note that the concept of “stream” is not the same as we’ve seen before, when “stream” actually meant “whole file”. This time we’ve dealing with a substructure that has fixed size (“size: header_len”), so that repetition will be limited by that size anyway. So we can rest assured that if there would be something beyond that length, it won’t be contaminating this structure of ours.</p><p>Ok, let’s give it a try:</p><pre>[-] header<br>    [-] <a href="http://twitter.com/entries">@entries</a> (233 = 0xe9 entries)<br>      [.]   0 = 57 e7 7f 00|0a 00 00 00|18 00 00 00|13 02 00 00|00 00 00 00 <br>      [.]   1 = 61 e7 7f 00|0b 00 00 00|2b 02 00 00|db 2a 00 00|00 00 00 00 <br>      [.]   2 = 6c e7 7f 00|11 00 00 00|06 2d 00 00|92 16 00 00|00 00 00 00 <br>      [.]   3 = 7d e7 7f 00|14 00 00 00|98 43 00 00|69 25 00 00|00 00 00 00 <br>      [.]   4 = 91 e7 7f 00|15 00 00 00|01 69 00 00|d7 12 00 00|00 00 00 00 <br>      [.]   5 = a6 e7 7f 00|12 00 00 00|d8 7b 00 00|27 3f 07 00|00 00 00 00</pre><p>Now it starts to make some sense, isn’t it? It really looks like a repeated structure. Let’s check out the second file too:</p><pre>[-] header<br>    [-] <a href="http://twitter.com/entries">@entries</a> (1420 = 0x58c entries)<br>      [.]    0 = d1 2b 66 21|0c 00 00 00|18 00 00 00|5a 04 00 00|00 00 00 00 <br>      [.]    1 = dd 2b 66 21|14 00 00 00|72 04 00 00|26 1a 00 00|00 00 00 00 <br>      [.]    2 = f1 2b 66 21|16 00 00 00|98 1e 00 00|a8 32 00 00|00 00 00 00 <br>      [.]    3 = 07 2c 66 21|16 00 00 00|40 51 00 00|a2 16 00 00|00 00 00 00 <br>      [.]    4 = 1d 2c 66 21|16 00 00 00|e2 67 00 00|89 c4 00 00|00 00 00 00 <br>      [.]    5 = 33 2c 66 21|16 00 00 00|6b 2c 01 00|fa f5 00 00|00 00 00 00</pre><p>By the way, do you see that (233 = 0xe9 entries) and (1420 = 0x58c entries)? It’s plausible to deduce that it could be number of files in the archive. Our first archive is relatively small (8 MiB), dividing it by 233 files yields us 36022 bytes per file on average. Looks legit for a bunch of scripts, configs, etc. The second archive is the largest (560 MiB), having 1420 files yields 394661 bytes per file, which looks ok for stuff like images, voice files, etc.</p><p>`57 e7 7f 00`, `61 e7 7f 00`, `6c e7 7f 00` and so on look very much like an increasing sequence of integers, what could it mean? In the second file it’s `d1 2b 66 21`, `dd 2b 66 21`, `f1 2b 66 21`. Hang on a sec here, I think I’ve seen it somewhere already. Let’s roll back to the beginning of our work — that’s it! It’s close to the full length of file — thus, it looks like offsets yet again. Ok, let’s try to describe the structure of these 20-bytes records. Judging by the looks, I’d say that these are 5 integers. We’ll describe another type named “file_entry”. Giving full listings becomes a bother, so if you’ll excuse me I won’t copy-paste whole file from now on and will just show you the changed “types” section:</p><pre>types:<br>  header:<br>    seq:<br>      - id: entries<br>        repeat: eos<br>        type: file_entry<br>  file_entry:<br>    seq:<br>      - id: unknown_ofs<br>        type: u4<br>      - id: unknown2<br>        type: u4<br>      - id: unknown3<br>        type: u4<br>      - id: unknown4<br>        type: u4<br>      - id: unknown5<br>        type: u4</pre><p>No new .ksy features tackled here. We’ve added “type: file_entry” for entries and described this subtype as 5 sequential u4 integers. Checking it out in visualizer:</p><pre>[-] header<br>    [-] <a href="http://twitter.com/entries">@entries</a> (233 = 0xe9 entries)<br>      [-]   0<br>        [.] <a href="http://twitter.com/unknown_ofs">@unknown_ofs</a> = 8382295<br>        [.] <a href="http://twitter.com/unknown2">@unknown2</a> = 10<br>        [.] <a href="http://twitter.com/unknown3">@unknown3</a> = 24<br>        [.] <a href="http://twitter.com/unknown4">@unknown4</a> = 531<br>        [.] <a href="http://twitter.com/unknown5">@unknown5</a> = 0<br>      [-]   1<br>        [.] <a href="http://twitter.com/unknown_ofs">@unknown_ofs</a> = 8382305<br>        [.] <a href="http://twitter.com/unknown2">@unknown2</a> = 11<br>        [.] <a href="http://twitter.com/unknown3">@unknown3</a> = 555<br>        [.] <a href="http://twitter.com/unknown4">@unknown4</a> = 10971<br>        [.] <a href="http://twitter.com/unknown5">@unknown5</a> = 0<br>      [-]   2<br>        [.] <a href="http://twitter.com/unknown_ofs">@unknown_ofs</a> = 8382316<br>        [.] <a href="http://twitter.com/unknown2">@unknown2</a> = 17<br>        [.] <a href="http://twitter.com/unknown3">@unknown3</a> = 11526<br>        [.] <a href="http://twitter.com/unknown4">@unknown4</a> = 5778<br>        [.] <a href="http://twitter.com/unknown5">@unknown5</a> = 0</pre><p>Any thoughts? Yet another idea: “unknown3” is a pointer to the beginning of the file in our archive, “unknown4” is most likely being length of this file. It’s simple because 24 + 531 = 555, and 555 + 10971 = 11526. That’s simply the files that go on sequentially in the container. One might also note the same for unknown_ofs and unknown2: 8382295 + 10 = 8382305, 8382305 + 11 = 8382316. That means that “unknown2” is a length of some other subrecords which begin at “unknown_ofs” offset. “unknown5” always seems to be equal to 0.</p><p>Come on, let’s add some special magic into “file_entry” to read these blocks of data, i.e. record at (unknown_ofs; unknown2) and file body at (unknown3; unknown4). It would look like that:</p><pre>  file_entry:<br>    seq:<br>      - id: unknown_ofs<br>        type: u4<br>      - id: unknown_len<br>        type: u4<br>      - id: body_ofs<br>        type: u4<br>      - id: body_len<br>        type: u4<br>      - id: unknown5<br>        type: u4<br>    instances:<br>      unknown:<br>        pos: unknown_ofs<br>        size: unknown_len<br>        io: _root._io<br>      body:<br>        pos: body_ofs<br>        size: body_len<br>        io: _root._io</pre><p>Actually, we’ve done that trick with “instances” before, so it’s not that new. The only real new “magic” thing here is that “io: _root._io” specification. What does it do?</p><p>Do you remember when I’ve mentioned that KS has concept of “stream” that’s being read, and if you effectively limit that “stream” by offset and size while parsing a substructure, it’s not the same “stream” that equals to whole file we had from the very beginning? That’s the case here. Without this “io” specification, “pos: body_ofs” would try to seek to “body_ofs” position in a stream that corresponds to our “file_entry” record, which is actually 20 bytes long — and that’s not what we want (not to mention that it would result in an error). So we need some special magic to specify that we want to read not from the current IO stream, but from IO stream that corresponds to the whole file — that is “_root._io”.</p><p>Ok, what have we got with all that?</p><pre>    [-] <a href="http://twitter.com/entries">@entries</a> (233 = 0xe9 entries)<br>      [-]   0<br>        [.] <a href="http://twitter.com/unknown_ofs">@unknown_ofs</a> = 8382295<br>        [.] <a href="http://twitter.com/unknown_len">@unknown_len</a> = 10<br>        [.] <a href="http://twitter.com/body_ofs">@body_ofs</a> = 24<br>        [.] <a href="http://twitter.com/body_len">@body_len</a> = 531<br>        [.] <a href="http://twitter.com/unknown5">@unknown5</a> = 0<br>        [-] unknown = 73 74 61 72 74 2e 79 6b 73 00 <br>        [-] body = 59 4b 53 30 30 31 01 00 30 00 00 00…<br>      [-]   1<br>        [.] <a href="http://twitter.com/unknown_ofs">@unknown_ofs</a> = 8382305<br>        [.] <a href="http://twitter.com/unknown_len">@unknown_len</a> = 11<br>        [.] <a href="http://twitter.com/body_ofs">@body_ofs</a> = 555<br>        [.] <a href="http://twitter.com/body_len">@body_len</a> = 10971<br>        [.] <a href="http://twitter.com/unknown5">@unknown5</a> = 0<br>        [-] unknown = 73 79 73 74 65 6d 2e 79 6b 67 00 <br>        [-] body = 59 4b 47 30 30 30 00 00 40 00 00 00…</pre><p>It’s easier to check out with interactive visualizer, but even on this static shot it’s easy to tell that `73 74 61 72 74 2e 79 6b 73 00` is an ASCII string. Checking out string representation, it turns out that it’s “start.yks” with trailing zero byte. And `73 79 73 74 65 6d 2e 79 6b 67 00` is actually “system.ykg”. Bingo, it’s the file names. And we’re damn sure of them that they are the strings, not just some bytes. Let’s mark it up:</p><pre>  file_entry:<br>    seq:<br>      - id: filename_ofs<br>        type: u4<br>      - id: filename_len<br>        type: u4<br>      - id: body_ofs<br>        type: u4<br>      - id: body_len<br>        type: u4<br>      - id: unknown5<br>        type: u4<br>    instances:<br>      filename:<br>        pos: filename_ofs<br>        size: filename_len<br>        type: str<br>        encoding: ASCII<br>        io: _root._io<br>      body:<br>        pos: body_ofs<br>        size: body_len<br>        io: _root._io</pre><p>The new stuff here is that “type: str” — it means that the bytes we’ve captured must be interpreted as a string — and “encoding: ASCII” specifies encoding (we’re not really sure, but so far it’s been ASCII). Visualizer again:</p><pre>  [-] header<br>    [-] <a href="http://twitter.com/entries">@entries</a> (233 = 0xe9 entries)<br>      [-]   0<br>        [.] <a href="http://twitter.com/filename_ofs">@filename_ofs</a> = 8382295<br>        [.] <a href="http://twitter.com/filename_len">@filename_len</a> = 10<br>        [.] <a href="http://twitter.com/body_ofs">@body_ofs</a> = 24<br>        [.] <a href="http://twitter.com/body_len">@body_len</a> = 531<br>        [.] <a href="http://twitter.com/unknown5">@unknown5</a> = 0<br>        [-] filename = &quot;start.yks\x00&quot;<br>        [-] body = 59 4b 53 30 30 31 01 00 30 00 00 00…<br>      [-]   1<br>        [.] <a href="http://twitter.com/filename_ofs">@filename_ofs</a> = 8382305<br>        [.] <a href="http://twitter.com/filename_len">@filename_len</a> = 11<br>        [.] <a href="http://twitter.com/body_ofs">@body_ofs</a> = 555<br>        [.] <a href="http://twitter.com/body_len">@body_len</a> = 10971<br>        [.] <a href="http://twitter.com/unknown5">@unknown5</a> = 0<br>        [-] filename = &quot;system.ykg\x00&quot;<br>        [-] body = 59 4b 47 30 30 30 00 00 40 00 00 00…<br>      [-]   2<br>        [.] <a href="http://twitter.com/filename_ofs">@filename_ofs</a> = 8382316<br>        [.] <a href="http://twitter.com/filename_len">@filename_len</a> = 17<br>        [.] <a href="http://twitter.com/body_ofs">@body_ofs</a> = 11526<br>        [.] <a href="http://twitter.com/body_len">@body_len</a> = 5778<br>        [.] <a href="http://twitter.com/unknown5">@unknown5</a> = 0<br>        [-] filename = &quot;SYSTEM\\black.PNG\x00&quot;<br>        [-] body = 89 50 4e 47 0d 0a 1a 0a 00 00 00 0d…</pre><p>Now, isn’t that nice? Looks like a job well done for me. You can even select individual file bodies, press “w” in the visualizer, type some name and export these binary blocks as local files. But this is tiresome and that’s not exactly what we wanted: we wanted to extract all the files at once, keeping their original filenames.</p><h3>Showdown time</h3><p>Let’s make a script for that. What do we do to transform our format description into code? Now that’s where Kaitai Struct shines: <strong>you don’t need to retype all that type specifications into code manually</strong>. You just get the ksc compiler and run:</p><pre>ksc -t ruby ykc.ksy</pre><p>and you’ve got yourself a nice and shiny “ykc.rb” file in your current folder, which is a library that you can plug in and use straight away. Ok, but how do we do that? Let’s start with something simple, like listing files to the screen:</p><pre>require_relative &#39;ykc&#39;<br>Ykc.from_file(&#39;data01.ykc&#39;).header.entries.each { |f|<br>  puts f.filename<br>}</pre><p>Cool, huh? Here we go — two lines of code (four, if you count in “require” and block termination) — and we’ve got that huge listing pumping:</p><pre>start.yks<br>system.ykg<br>SYSTEM\black.PNG<br>SYSTEM\bt_click.ogg<br>SYSTEM\bt_select.ogg<br>SYSTEM\config.yks<br>SYSTEM\Confirmation.yks<br>SYSTEM\confirmation_load.png<br>SYSTEM\confirmation_no.ykg<br>SYSTEM\confirmation_no_load.ykg<br>...</pre><p>Let’s go through what’s going on here step-by-step:</p><ul><li>Ykc.from_file(…) — creates a new object of Ykc class (which is generated from our .ksy description), parsing a file from local filesystem; fields of this object would be filled with whatever’s describe in .ksy</li><li>.header — selects “header” field in Ykc, thus returning instance of Ykc::Header class, which corresponds to “header” type in .ksy</li><li>.entries — selects “entries” field in the header, returns an array of instances of Ykc::FileEntry class</li><li>.each { |f| … } —a typical Ruby way to do something with each element of a collection</li><li>puts f.filename — just outputs string in “filename” field of a FileEntry to the stdout, that is the screen</li></ul><p>It shouldn’t be very hard to write mass extraction script, but I just want to note a couple of things before that:</p><ol><li>There are path specifications in the “filename” field, and it uses “\” (backslash) as a folder separator due to the fact that archive was originally created on Windows system. If we’ll attempt to create such a path on UNIX system, it will obediently create us a directory with backslashes in its name, so it’s good idea to convert these “\” into “/” for calls like mkdir_p.</li><li>File names are actually zero-terminated (yeah, it looks like C, alright). It’s invisible when you just dump it on screen, but it may become a problem when you’ll try to create a file with a “\0” in the name.</li><li>If you’ll look a bit further into the listing, you’ll encounter stuff like that:</li></ol><pre>&quot;SE\\00050_\x93d\x98b\x82P.ogg\x00&quot;<br>&quot;SE\\00080_\x83J\x81[\x83e\x83\x93.ogg\x00&quot;<br>&quot;SE\\00090_\x83`\x83\x83\x83C\x83\x80.ogg\x00&quot;<br>&quot;SE\\00130_\x83h\x83\x93\x83K\x83`\x83\x83\x82Q.ogg\x00&quot;<br>&quot;SE\\00160_\x91\x96\x82\xE8\x8B\x8E\x82\xE9\x82Q.ogg\x00&quot;</pre><p>Do you remember the beginning of the article, when I said that crazy Japanese programmers use Shift-JIS? That’s exactly it. They use files with Japanese characters in it. Let’s change “encoding: ASCII” to “encoding: SJIS” in our filename type description for that. Don’t forget to recompile ksy → rb, and, voila:</p><pre>SE\00050_電話１.ogg<br>SE\00080_カーテン.ogg<br>SE\00090_チャイム.ogg<br>SE\00130_ドンガチャ２.ogg<br>SE\00160_走り去る２.ogg</pre><p>Even if you don’t read Japanese, you can check out something like Google Translator to see that 電話 is actually “phone”, so chances are “SE\00050” is a sound of phone ringing.</p><p>Ultimately, our extraction script will look like this:</p><pre>require &#39;fileutils&#39;<br>require_relative &#39;ykc&#39;</pre><pre>EXTRACT_PATH = &#39;extracted&#39;</pre><pre>ARGV.each { |ykc_fn|<br>  Ykc.from_file(ykc_fn).header.entries.each { |f|<br>    filename = f.filename.strip.encode(&#39;UTF-8&#39;).gsub(&quot;\\&quot;, &#39;/&#39;)<br>    dirname = File.dirname(filename)<br>    FileUtils::mkdir_p(&quot;#{EXTRACT_PATH}/#{dirname}&quot;)<br>    File.write(&quot;#{EXTRACT_PATH}/#{filename}&quot;, f.body)<br>  }<br>}</pre><p>That’s a bit more than 2 lines, but nothing fancy goes on here either. We grab a list of command line arguments (this way, you can run it using something like ./extract-ykc *.ykc), and, again, for every container file we’re iterating over all file entries. We clean up the file name (stripping trailing zero, encoding it to UTF-8 and replacing backslashes with forward slashes), derive directory name (dirname), create the folder if it doesn’t exist (mkdir_p) and, finally, we dump the `f.body` contents there to a file.</p><p>Our job is complete. You can run the script to see what we’ll get. As we’ve predicted, images are really in .png format (and you can view them with any image viewer), and music and sounds are in .ogg (so you can listen to them with any player). For example, here’s the backgrounds that we’ve got in BG folder:</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/962/1*aLD7q59SRgZjsJv8qdOJ9g.png" /><figcaption>BG folder unpacked: backgrounds</figcaption></figure><p>And TA folder contains sprites which are overlaid over these backgrounds. For example, Mika looks like that:</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/941/1*xzYwbo23hQTo3tWrz9Svmg.png" /><figcaption>TA/MIKA folder unpacked: sprites for Mika character</figcaption></figure><p>I can give out a little secret: in many Japanese VNs, “standing” sprites are named “ta” or “tati” / “tachi” / “tatsu” / “tatte”. That’s because Japanese word for “standing” is 立って (tatte) or “to stand up” is 立ち上がる (tachi ageru). That usually contrasts with “fa” or “face” sprites, which are actually used for avatar portraits in the dialogue text box, which show only character’s face.</p><p>That’s it for today. The two major things left to reverse engineer here are “yks” and “ykg” files — probably “yks” is the script of the game, and “ykg” are some aux graphics or animations. Let’s try to tackle them next time.</p><p>A few conclusions I’d like to share:</p><ul><li>Kaitai Struct is a really nice tool and seems to match closely whatever’s you were doing without it, thus saving you lots of time. If you’re doing this in plain Ruby (or Python, or PHP, or whatever), at the very least you’ll have to do the whole thing twice: first, you write a script that outputs dumps to the screen, then you rewrite it to actually extract the data. If you’re employing “advanced” hex editors like Hexinator or 010 Editor — chances are you’d actually do this work thrice (yet another time you’ll have to write a template in your editor).</li><li>Kaitai Struct visualizer is very bare bones tool, it might be ugly and slow, but it’s still the best thing for the job I’ve encountered so far. Hope someday it will get a facelift :)</li><li>Actually you don’t even need a hex editor / viewer, after you’ve done the first rough sketch in .ksy. Walking through the tree in visualizer beats manual calculation of offsets anyway. But it’s still useful to have one for preliminary analysis + quick searches in .exe.</li><li>.ksy is a very expressive language (it beats “advanced” hex editor templates, hands down), but the documentation, is, well, somewhat lacking. I must confess that I kept pestering KS author with endless stream of questions for a week for writing this article. That trick with “io: _root._io” is nothing like you’ll come up with by yourself. I can just hope that documentation will become better as Kaitai Struct will be approaching v1.0.</li></ul><p>A few useful links:</p><ul><li>Kaitai Struct — <a href="http://kaitai.io/">http://kaitai.io/</a></li><li>PeasSoft — <a href="http://peassoft.com/">http://peassoft.com/</a> (warning, NSFW!)</li><li>One can find specifications and tools for a few visual novel engines (in .ksy format too) at <a href="https://github.com/mnakamura1337/">my GitHub projects</a>.</li><li>You can also read this article <a href="https://habrahabr.ru/post/281595/">in Russian</a>.</li></ul><figure><a href="http://bit.ly/HackernoonFB"><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*0hqOaABQ7XGPT-OYNgiUBg.png" /></a></figure><figure><a href="https://goo.gl/k7XYbx"><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*Vgw1jkA6hgnvwzTsfMlnpg.png" /></a></figure><figure><a href="https://goo.gl/4ofytp"><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*gKBpq1ruUi0FVK2UM_I4tQ.png" /></a></figure><blockquote><a href="http://bit.ly/Hackernoon">Hacker Noon</a> is how hackers start their afternoons. We’re a part of the <a href="http://bit.ly/atAMIatAMI">@AMI</a> family. We are now <a href="http://bit.ly/hackernoonsubmission">accepting submissions</a> and happy to <a href="/service/mailto:partners@amipublications.com">discuss advertising &amp; sponsorship</a> opportunities.</blockquote><blockquote>If you enjoyed this story, we recommend reading our <a href="http://bit.ly/hackernoonlatestt">latest tech stories</a> and <a href="https://hackernoon.com/trending">trending tech stories</a>. Until next time, don’t take the realities of the world for granted!</blockquote><figure><a href="https://goo.gl/Ahtev1"><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*35tCjoPcvq6LbB3I6Wegqw.jpeg" /></a></figure><img src="https://medium.com/_/stat?event=post.clientViewed&referrerSource=full_rss&postId=d0bc3bf7ab8" width="1" height="1" alt=""><hr><p><a href="https://medium.com/hackernoon/reverse-engineering-visual-novels-101-d0bc3bf7ab8">Reverse engineering visual novels 101</a> was originally published in <a href="https://medium.com/hackernoon">HackerNoon.com</a> on Medium, where people are continuing the conversation by highlighting and responding to this story.</p>]]></content:encoded>
        </item>
    </channel>
</rss>