<?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 paulsc on Medium]]></title>
        <description><![CDATA[Stories by paulsc on Medium]]></description>
        <link>https://medium.com/@paulsc?source=rss-7f1d4faef472------2</link>
        <image>
            <url>https://cdn-images-1.medium.com/fit/c/150/150/1*-UaL6v3AFAkRisrF2VsF5g.jpeg</url>
            <title>Stories by paulsc on Medium</title>
            <link>https://medium.com/@paulsc?source=rss-7f1d4faef472------2</link>
        </image>
        <generator>Medium</generator>
        <lastBuildDate>Mon, 23 Nov 2026 04:16:11 GMT</lastBuildDate>
        <atom:link href="https://medium.com/@paulsc/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[Fava: Categorizing transactions]]></title>
            <link>https://medium.com/@paulsc/fava-categorizing-transactions-3c678b676f83?source=rss-7f1d4faef472------2</link>
            <guid isPermaLink="false">https://medium.com/p/3c678b676f83</guid>
            <category><![CDATA[open-source]]></category>
            <category><![CDATA[software-development]]></category>
            <category><![CDATA[software-engineering]]></category>
            <category><![CDATA[personal-finance]]></category>
            <category><![CDATA[beancount]]></category>
            <dc:creator><![CDATA[paulsc]]></dc:creator>
            <pubDate>Mon, 01 Sep 2025 12:55:06 GMT</pubDate>
            <atom:updated>2025-09-01T13:09:20.764Z</atom:updated>
            <content:encoded><![CDATA[<p>This story is part 3 of the <a href="https://medium.com/@paulsc/list/personal-finance-with-fava-5d9caecac5e6">Fava &amp; Beancount</a> series.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*dBAPPtxRa4ykmg2ArbBTqg.png" /><figcaption>A treemap generated from categorized Fava transactions</figcaption></figure><p>I was surprised, while first reading up on Beancount, that little effort was invested in automated retrieval and categorization of transactions. In retrospect, this is probably a smart decision by the author not to waste too much time on possibly brittle and not-reusable code. Also, most people’s private finances involve a few hundred transactions a week <em>at most</em>, an amount which can be reviewed and categorized by hand in a relatively short time, given a good editor with auto-complete. This is also the author&#39;s <a href="https://beancount.github.io/docs/importing_external_data.html">preferred workflow</a>.</p><p>That being said, as a developer, the temptation was too great, so I ignored those sage insights and fired up the old IDE. Retrieving and syncing transactions was relatively easy, since luckily my bank provided well-structured data.</p><p>After that, again blatantly ignoring common SWE wisdom to just <a href="https://www.seangoedecke.com/the-simplest-thing-that-could-possibly-work/"><em>do the simplest thing that works</em></a>, I chose to <a href="https://github.com/paulsc/beancount-classifier">use machine learning</a> to automatically categorize new transactions based on past data. It was both overkill and not that effective, the perfect little side project. I first tried using Naive Bayes, then moved on to a Random Forest classifier for much better results. Still, in the best case scenario, it would only successfully classify about half of transactions, and I was completely unable to make it learn more subtle features. I could never get it to infer that a $9.99 Apple transaction was Apple TV and a $2.99 transactions was iCloud, for example.</p><p>In the back of my head, I gradually developed the idea that a “simple” rules engine, with hard-coded rules for each transformation, would be more effective. It would be “Simple” from a tech standpoint, as compared to the classifier, however it would require more manual input from the user. It got me thinking that if I could simplify the creation of rules with good UX, this would be a better approach. I also saw the need for a bulk-edit tool, which would allow me to work through the backlog of unclassified transactions in the last 4 years. Maybe there’s some overlap there?</p><p>It occurred to me that the tricky thing with these <em>bulk-editors</em> or <em>rule engines</em>, is that you want great flexibility in the kind of changes you can make to your data, i.e. be able to modify any part of the transaction, but you also want to keep the UX simple. The UX can quickly get out of hand as you need some sort of interface to let the user say <em>I want to change the date</em>, and/or <em>I want to change the description</em>, and/or<em> I want to change the 2nd posting category</em>, etc. On top of this, I was really liking the workflow with the existing slice editor built into Fava.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*b4bBAAHWSqgHEQCsSejhWg.png" /><figcaption>Autocomplete in the slice editor makes changes a breeze</figcaption></figure><p>I decided to integrate the feature by adding an <em>apply all</em> checkbox to the slice editor, which would compute a diff for the current edit and apply it to all the transactions currently visible in the Account journal. The diff is generated using the <a href="https://pypi.org/project/deepdiff/">deepdiff</a> library, and applied in a second step to a subset of transactions. The deepdiff library needed a minor patch to add support for NamedTuple, the unmutable data structure used in Fava to represent transactions. There are some limitations to this approach, e.g. there is no support for adding or removing entire postings, but this hasn’t come up in my workflow so far. The UI has a diff preview step, for the user to confirm of the changes about to be made.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*y4GXKuxiS628SA6dzumnzg.gif" /></figure><p>Although I liked that UX, this approach was doomed to fail. Anything tightly integrated in an open source project will eventually conflict with upstream changes, leaving two choices, both of them bad. Either forego updates and be constantly frozen at the current version, or be caught in a cycle of constantly merging your changes with upstream. In this case, too, my changes very quickly started conflicting with upstream changes in the main Fava repository.</p><p>The better alternative is to use whatever extension or plug-in system the codebase offers, for future compatibility. The means of integration are more limited, but having made that exact same mistake before while making some changes to <a href="https://github.com/grafana/grafana">Grafana</a>, I hoped that a little perseverance might bring a good compromise.</p><p>Extensions in Fava give you a lot of flexibility to build any UI you wish inside the extension’s page, however I wanted at all cost to avoid building a custom edit UI which would be convoluted and brittle. The compromise I came up with is to use Fava’s before_request <a href="https://fava.pythonanywhere.com/huge-example-file/help/extensions">extension hook</a> to record edits done with the slice editor, and capture a diff there. The main extension UI would focus on filtering for transactions for re-applying the diff, in short, a sort of “edit replay”.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/640/1*ZNnKudJ2oBX_U03XMM4OqQ.gif" /><figcaption>The new flow in the fava-edit-replay extension</figcaption></figure><p>The <a href="https://github.com/paulsc/fava-edit-replay/blob/4eaf897efb7db313969593bc743f3988f66a66f7/src/fava_edit_replay/__init__.py#L134C28-L134C30">excerpt</a> below shows the hook, where we grab <em>before</em> and <em>after</em> versions of the slice for the purpose of diffing them later.</p><pre>def before_request(self):<br>    if request.path.endswith(&quot;/api/source_slice&quot;) and request.method == &quot;PUT&quot;:<br>        data = request.get_json(force=True, silent=True)<br>        if data:<br>            entry_hash = data.get(&quot;entry_hash&quot;)<br>            new_source = data.get(&quot;source&quot;)<br>            if entry_hash and new_source:<br>                try:<br>                    entry = self.ledger.get_entry(entry_hash)<br>                    if not isinstance(entry, Transaction):<br>                        return<br>                    before, _ = get_entry_slice(entry)<br>                except Exception as e:<br>                    before = f&quot;[Error getting before slice: {e}]&quot;<br>                self.before_slice = before<br>                self.after_slice = new_source</pre><p>Interestingly, the new flow actually makes filtering easier. In the previous version, filtering had to be done before the edit. In this version, you edit first, then filter. This way, we can generate “filter templates” from the transaction that was edited, which are shown as light blue pills below the transaction list.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/640/1*Js9Uh-Q6FDuOwnLW4ZF3Lg.gif" /></figure><p>The next step was to add the ability to save these “replays” to disk, so that they may be re-applied later. This is done with the “Save Replay” and “List Replay” buttons. The replay list also has a button to “Apply All”, which will apply all saved filters to all the transactions in the ledger. I run this operation after importing new transactions from my bank, to automatically categorize new transactions. This can also be done from the CLI. I now have about 50 “replays” stored which automatically categorize transactions with about 80% coverage every time, significantly better than my original attempts with machine learning.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/640/1*nOh_7f12z8B29HI0chhMOw.gif" /><figcaption>Using “saved replays” to store transaction transformation rules</figcaption></figure><p>That’s all for now! If you find this useful, you can grab the extension <a href="https://github.com/paulsc/fava-edit-replay">on Github</a>, or checkout the <a href="https://medium.com/@paulsc/list/personal-finance-with-fava-5d9caecac5e6">Fava &amp; Beancount</a> list for more stories on this topic.</p><img src="https://medium.com/_/stat?event=post.clientViewed&referrerSource=full_rss&postId=3c678b676f83" width="1" height="1" alt="">]]></content:encoded>
        </item>
        <item>
            <title><![CDATA[Fava: the weird parts]]></title>
            <link>https://medium.com/@paulsc/fava-the-weird-parts-fb318f1486ae?source=rss-7f1d4faef472------2</link>
            <guid isPermaLink="false">https://medium.com/p/fb318f1486ae</guid>
            <category><![CDATA[personal-finance]]></category>
            <category><![CDATA[software]]></category>
            <category><![CDATA[beancount]]></category>
            <dc:creator><![CDATA[paulsc]]></dc:creator>
            <pubDate>Mon, 01 Sep 2025 12:53:35 GMT</pubDate>
            <atom:updated>2025-09-01T12:53:35.849Z</atom:updated>
            <content:encoded><![CDATA[<p>This story is part 2 of the <a href="https://medium.com/@paulsc/list/personal-finance-with-fava-5d9caecac5e6">Fava &amp; Beancount</a> series. In this story, I will explore the parts of Fava &amp; Beancount that were somewhat confusing at first.</p><p>Let’s open the ledger for the Beancount personal finance tool from the <a href="https://medium.com/@paulsc/beancount-is-personal-finance-for-developers-182c5f49c335">previous post</a> and dig a little deeper using its web front-end <a href="https://github.com/beancount/fava">Fava</a>.</p><pre>option &quot;title&quot; &quot;Example Beancount file&quot;  ; Name your ledger<br>option &quot;operating_currency&quot; &quot;USD&quot;        ; The default currency<br><br>1980-05-12 open Equity:Opening-Balances  ; Initial balance comes from here.<br>1980-05-12 open Expenses:Restaurant      ; This account is used as a<br>;                                        ; category to track expenses.<br>2023-01-01 open Assets:Checking USD      ; Your checking account, in USD.<br><br>;                                        ; A first transaction:<br>2023-01-01 * &quot;Opening Balance&quot;           ; [Date] [Flag] [Description]<br>  Assets:Checking           4043.21 USD  ; First &quot;posting&quot; or &quot;leg&quot;<br>  Equity:Opening-Balances  -4043.21 USD  ; 2nd posting<br><br>2023-01-01 * &quot;Eating out with Nick&quot;      ; &quot;*&quot; is default for transactions<br>  Assets:Checking          -104.21 USD   ; Take 104 USD from checking...<br>  Expenses:Restaurant       104.21 USD   ; And credit the &quot;restaurant&quot;<br>                                         ; account.</pre><h3>Account View</h3><p>If we open this ledger using fava ledger.bean, and use the “Go to account” menu item in the sidebar to navigate to the <em>Checking</em> account, we are greeted with something like this.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*BUiBbpomKBjEQTVTpGaVvg.png" /><figcaption>The Account view for Assets:Checking</figcaption></figure><p>This is the account view, a classic journal of transactions that credit or debit money from an account. I use this view to make sure no fraudulent transactions are posted to my credit card. Most of this is pretty self-explanatory, so let’s look into the not-so-obvious parts.</p><p>The bar full of buttons above the list of transactions can seem a bit daunting at first. Each button is an on/off toggle for a specific kind of transaction. These will gradually make more sense as you get more familiar with the different transaction types. The last two buttons enable more transaction details, by showing their metadata or postings.</p><p>Another thing I found odd at first is the <em>Cost/Change</em> column. Also, it’s not immediately obvious where the money is moving <em>to</em> or coming <em>from</em>. This seems a bit cumbersome, since I am viewing the checking account here, I might expect to see that “Eating out with Nick” is going to the Expenses:Restaurant account. However, this doesn’t generalize, because one transaction can move money <em>to</em> or <em>from</em> more than one account. Fava chooses by default to shows the transactions from the perspective of the current account, and the <em>Cost/Change </em>column is the impact that this transaction has on this account’s balance. However, if you expand the transaction by clicking the two gray circles, all the individual postings become visible.</p><p>For another way to solve this conundrum, see GnuCash. Transactions with exactly two postings, a.k.a. <em>splits</em>, are displayed differently than the ones with more than two. For the first transaction in the screenshot, GnuCash shows the other account Expenses:Auto:Gas, but if there are more than two postings, we get — Split Transaction — , which can be expanded. This works well in the case where a majority of transactions have two postings, which is typical of checking accounts.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/908/1*S1udcBVOr0le43Gg36TEgQ.png" /><figcaption>Note: “Gas” has two postings and shows the other account, whereas “Salary” doesn’t since it has more than two postings (or “splits” in GnuCash talk).</figcaption></figure><p>Fava instead opts for a more consistent UI, which is the same regardless of the number of postings. In practice, I keep the transactions mostly collapsed and gather meaning from the description of the transaction, which works well enough. An alternative Fava Account view following the GnuCash model would be intriguing to explore, though.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*8e7X_RULPeNQm8c_9Ok1yw.png" /><figcaption>The Journal View: No amounts visible without expanding the transactions.</figcaption></figure><p>This is also why the Journal view, which shows transactions from all accounts, amounts are not visible at all without expanding. A “summarizing” top level amount for a transaction only makes sense in the context of a specific account.</p><p>The last thing I found to be initially confusing in this view is the <em>At Cost</em> button in the top right of the view. More on this now.</p><h3>Stock Trading</h3><p>The <em>At Cost</em> button can be happily ignored until you start trading stock. Let’s add some trades to our ledger and see what happens.</p><pre>2023-01-01 open Assets:Stocks:IBM IBM    ; Open the IBM Stock account<br><br>2023-02-01 * &quot;Buying 10 IBM&quot;             ; Initial stock purchase<br>  Assets:Stocks:IBM 10 IBM {100.00 USD}  ; we bought 10 @ 100 USD<br>  Assets:Checking                        ; let beancount calculate amount<br><br>2023-03-01 * &quot;Buying 10 more IBM&quot;        ; 2nd stock purchase 10 @ 200 USD<br>  Assets:Stocks:IBM 10 IBM {200.00 USD}<br>  Assets:Checking<br><br>2023-04-01 * &quot;Buying again 10 more IBM&quot;  ; 3rd stock purchase 10 @ 300 USD<br>  Assets:Stocks:IBM 10 IBM {300.00 USD}<br>  Assets:Checking</pre><p>Note the new curly brackets syntax 10 IBM {100.00 USD}, which allows us to specify the price point at which the stock was bought. Also note that we left the Assets:Checking posting without a USD amount. This is a feature of Beancount. If one posting has no amount specified, Beancount will automatically calculate the amount that balances the transaction, so that the sum of all postings equals zero. If we add those lines to our existing ledger file, we get something like below in the Assets:Stocks:IBM Account view.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*MqAhO-vfxsWpeSkt6eT3mw.png" /><figcaption>The Account page for a stock account using the “Units” view</figcaption></figure><p>We can now toggle between the <em>At Cost</em> and the <em>Units</em> view using the button on the top right. In the context of stock purchases, <em>At Cost</em> shows all amounts based on the purchase price of the stock. <em>Units</em>, however, shows you the number of stocks purchased.</p><p>For the other two views <em>At Market Value</em> and <em>Convert To USD</em> to be useful, we need one more thing: stock prices (or “quotes”) in our ledger. Let’s add the following lines.</p><pre>2023-02-01 price IBM 100.00 USD          ; Track stock price updates<br>2023-03-01 price IBM 200.00 USD<br>2023-04-01 price IBM 300.00 USD<br>2023-05-01 price IBM 400.00 USD<br>2023-06-01 price IBM 500.00 USD</pre><p>We now can use the <em>At Market Value</em> option to see that our balance on the account on April 1st is $9000, since at that point we own 30 units of IBM stock worth $300 each.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*VSUHRr2UBsCtDln_QJWMgA.png" /><figcaption>The Account view is not a good way to look at the market value of a stock account</figcaption></figure><p>One odd thing about this, you can’t (easily) use the account view to see how a particular stock is performing. You’ll notice that even though we added two more price quotes for IBM of $400 and $500 in May and June, these increases are nowhere to be seen above. The Account view stops at the last transaction on that account. The fact that our IBM stock is now worth $15k (30 units at $500) remains hidden.<br>Moreover, even if we added an IBM price quote at mid-March, it wouldn’t show in the graph. This view generates data points for every transaction, using the closest available price quote for the <em>Market Value</em> calculation. But if a price quote is in between two transactions, you won’t see a change in the graph.<br>The <em>commodities</em> entry in the sidebar gives you a graph of the evolution of a stock, but ignores your transactions. The <em>holdings</em> view lets you see the current market value of your stock account, but it won’t do historical. The closest there is to a “Stock Account Worth” graph is the <em>Balances</em> option in the Account view, which will list monthly or weekly balances, taking price quotes into account. Unfortunately, this data is not available in a graph format as of version 1.30.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*2AZM3zv3seb9o-HwekyzFw.png" /><figcaption>“Balances” in the Account view, scroll right for more data points.</figcaption></figure><p>Ultimately, the answer to this problem is to use the <a href="https://github.com/andreasgerstmayr/fava-portfolio-returns">Portfolio Returns extension</a>. This will give detailed graphs and breakdowns, as well as multiple metrics for performance calculation.</p><p>That sums up the initial oddities in my Fava &amp; Beancount interactions. Check out my <a href="https://medium.com/@paulsc/list/personal-finance-with-fava-5d9caecac5e6">Fava &amp; Beancount</a> list for more stories on this topic.</p><img src="https://medium.com/_/stat?event=post.clientViewed&referrerSource=full_rss&postId=fb318f1486ae" width="1" height="1" alt="">]]></content:encoded>
        </item>
        <item>
            <title><![CDATA[Beancount is Personal Finance for Developers]]></title>
            <link>https://medium.com/@paulsc/beancount-is-personal-finance-for-developers-182c5f49c335?source=rss-7f1d4faef472------2</link>
            <guid isPermaLink="false">https://medium.com/p/182c5f49c335</guid>
            <dc:creator><![CDATA[paulsc]]></dc:creator>
            <pubDate>Tue, 26 Aug 2025 09:59:10 GMT</pubDate>
            <atom:updated>2025-09-01T12:46:50.643Z</atom:updated>
            <content:encoded><![CDATA[<p>This story is part 1 of the <a href="https://medium.com/@paulsc/list/personal-finance-with-fava-5d9caecac5e6">Fava &amp; Beancount</a> series.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*NwYmJVLqAeNw9pa_GfLPLg.png" /><figcaption>The <a href="https://github.com/beancount/fava">Fava</a> web frontend for Beancount</figcaption></figure><p>Over the years, I have made multiple attempts at using software for tracking household finances, each one abandoned after an initial period of excitement.</p><p>About 13 years ago, I <a href="https://github.com/paulsc/chase/">was scrapping</a> the Chase Bank mobile website to display a running total of monthly expenses and estimated available “discretionary cash” at the end of the month. I ran this periodically to display a status line on the lock screen of my jailbroken iPhone. I was aiming to get almost instant feedback on my budget, while spending, and to avoid that <em>where did the money go?!</em> feeling at the end of the month. This was quite handy for a little while, I’m not even sure what killed it, probably the brittle scrapping code, or I just gave up on jailbreaking.</p><p>I tried mint.com for a little while after this, and I remember being pleased with their automatic categorization of transactions, but giving away my personal financial data always made me uneasy. There’s the privacy but also that feeling of lack of control, of not owning the data. What happens if they go bust?</p><p>Next, perhaps predictable for a developer, came a home-grown finance webapp. The project is now in good company in my Bitbucket graveyard. All in all, a decent effort of about 3k lines of code written over the course of 10 months in 2020. It was scrapping my different banks and feeding a SQLite ORM, to show a simple ledger with filters in the front-end. Looking at it now, it was doomed by the lack of double-entry accounting. It did however have basic graphs &amp; pies, and a rules engine to clean up the data. As always, the most interesting thing in the repo is the TODO file, which tells a story of chasing the same goal I had 10 years prior: using current spending and upcoming recurring expenses to show a running estimate of the extra cash left at the end of the month, to “close the loop”.</p><p>Fast-forward a few more years, in 2024 I decided it was time to tackle the home finance project again. Now a bit older, the family financial situation is a little more layered, so the goals changed as well. I wanted to replace a series of random spreadsheets with a dashboard that could keep me updated on “macro” level questions. Answering things like “was this mortgage a good idea?” or “how’s that ETF performing?”. The nice thing about the macro level is that there are way fewer transactions, which means manually tracking them with an update every few months or so is way more doable. This got me thinking I might “succeed” this time around.</p><p>I started with GnuCash, assuming that “<em>something that has been around for so long will be around for a lot longer</em>”. That might be true, but not a good criteria in retrospect. It did however introduce me to double-entry accounting, and some basics like the accounting equation. Double-entry accounting forces you to record every transaction as being attached to at least 2 accounts, one being credited and one being debited. This tracks your money as a flow from A to B, instead of transactions in a ledger floating in the ether and unconnected to each other. This goes a long way to make sure you are painting an accurate picture, as the credits and debits have to balance.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*t0HScxYYFMghwKfKG1ZpPg.png" /><figcaption>Tracking stock purchases in GnuCash</figcaption></figure><p>While tracking stock purchases, I also learned about the concept of <em>lots</em>. Lots are used to answer the following question: “<em>if I bought the same stock at 2 different times at different prices, and I later sell some of it, which buy price am I taking into account to calculate profit?”. </em>This requires tracking “bunches” of stock units by their <em>buy date</em> and <em>buy price</em>, so-called <em>lots</em>. This can be useful for tax math, but in the end not so important in the day-to-day, as your bank usually does the math for you.</p><p>Even though I enjoyed the “retro open-source” charm of GnuCash’s GUI, all my hopes and dreams came crashing down when I tried to make some custom reports, which was my original goal. I was initially delighted to see a Lisp used as the scripting language, thinking this would give me some practice with the lambda and let me wield it’s functional power to generate quick and succinct reports. Many hours and two hundred lines of code later, all I had to show for my efforts was a report with a basic list of transactions.</p><h3>Beancount</h3><p>I don’t remember exactly how I stumbled on <a href="https://github.com/beancount/beancount">Beancount</a>. It’s very good at being financial software <em>for software developers</em>. The key selling point, which granted seemed odd at first, is that the database is just a <em>text file</em>. It looks like this:</p><pre>2023-06-22 * &quot;Wine-Tarner Cable&quot; &quot;&quot;<br>  Assets:US:BofA:Checking                          -80.09 USD<br>  Expenses:Home:Internet                            80.09 USD<br><br>2023-07-04 * &quot;BANK FEES&quot; &quot;Monthly bank fees&quot;<br>  Assets:US:BofA:Checking                           -4.00 USD<br>  Expenses:Financial:Fees                            4.00 USD<br><br>2023-07-05 * &quot;RiverBank Properties&quot; &quot;Paying the rent&quot;<br>  Assets:US:BofA:Checking                        -2400.00 USD<br>  Expenses:Home:Rent                              2400.00 USD</pre><p>This “Text-File-As-a-DB” approach has some nice consequences, notably:</p><ul><li>Ownership: the syntax is clear and legible, inspiring confidence that the data will remain accessible after carefully constructing a financial model over many years. Hypothetically speaking, you could just whip up a script from scratch in the language of your choice and start doing basic reports fairly quickly. In practice, this would likely never happen since the existing tooling is plenty adequate (and maybe that barrier of entry is not <em>so</em> low?), but it serves to give that extra peace of mind. Text is in a sense the most self-documenting of data formats, so the most likely to survive a long time.</li><li>All your existing developer tooling is valid. Working with text files in your favorite IDE is a well-known process. Source-control is great to track changes and revert mistakes. It’s just another repository.</li></ul><p>A simple but fully working example of a ledger file might look like this:</p><pre>option &quot;title&quot; &quot;Example Beancount file&quot;  ; Name your ledger<br>option &quot;operating_currency&quot; &quot;USD&quot;        ; The default currency<br><br>1980-05-12 open Equity:Opening-Balances  ; Initial balance comes from here.<br>1980-05-12 open Expenses:Restaurant      ; This account is used as<br>;                                        ; category to track expenses.<br>2023-01-01 open Assets:Checking USD      ; Your checking account.<br><br>;                                        ; A first transaction:<br>2023-01-01 * &quot;Opening Balance&quot;           ; [Date] [Flag] [Description]<br>  Assets:Checking           4043.21 USD  ; First &quot;posting&quot; or &quot;leg&quot;<br>  Equity:Opening-Balances  -4043.21 USD  ; 2nd posting<br><br>2023-01-01 * &quot;Eating out with Nick&quot;      ; &quot;*&quot; is default for transactions<br>  Assets:Checking          -104.21 USD   ; Take 104 USD from checking...<br>  Expenses:Restaurant       104.21 USD   ; And credit the &quot;restaurant&quot;<br>                                         ; account.</pre><h3>Fava</h3><p>Originally, this Beancount <em>ledger</em> (as your database text file is called) was meant to be processed using command line tools, optionally spitting out some HTML reports when required. My preferred form of interaction however is with the web front-end, called <a href="https://github.com/beancount/fava">Fava</a>. It’s also an easy way to get started, after installing python and the pip package manager, these commands will get you started:</p><pre>python -m venv venv           # optionally use a venv to keep it neat<br>source venv/bin/activate      # only if you created a venv above<br>pip3 install fava             # install fava and beancount<br>bean-example &gt; sample.ledger  # generate a sample ledger<br>fava sample.ledger            # start fava</pre><p>You can now navigate to <a href="http://localhost:5000/">http://localhost:5000</a> to try Fava, or go ahead and try the <a href="https://fava.pythonanywhere.com/">online demo</a>.</p><p>That’s it for now for some Beancount &amp; Fava basics. So far I’ve been sticking with it for a bit over a year, let’s see if this one can go the long run or if it goes the way of countless other personal projects: bust 🤷‍♂️.</p><img src="https://medium.com/_/stat?event=post.clientViewed&referrerSource=full_rss&postId=182c5f49c335" width="1" height="1" alt="">]]></content:encoded>
        </item>
        <item>
            <title><![CDATA[Mass Surveillance in Consideration in the EU Council]]></title>
            <link>https://medium.com/@paulsc/we-are-on-the-brink-of-mass-surveillance-in-the-eu-2a8c717aaff7?source=rss-7f1d4faef472------2</link>
            <guid isPermaLink="false">https://medium.com/p/2a8c717aaff7</guid>
            <category><![CDATA[politics]]></category>
            <category><![CDATA[technology]]></category>
            <category><![CDATA[human-rights]]></category>
            <category><![CDATA[european-union]]></category>
            <category><![CDATA[messaging]]></category>
            <dc:creator><![CDATA[paulsc]]></dc:creator>
            <pubDate>Thu, 21 Aug 2025 17:54:08 GMT</pubDate>
            <atom:updated>2025-10-21T13:44:56.331Z</atom:updated>
            <content:encoded><![CDATA[<p>A <a href="https://www.lemonde.fr/en/les-decodeurs/article/2023/09/26/the-eu-fight-against-child-pornography-stokes-fears-of-widespread-online-surveillance_6140055_8.html">dangerous precedent</a> is about to be set with a law that’s currently being negotiated in the European Union. This law would mandate surveillance of private communications at a level comparable only to China.</p><p>The CSA (Combat Child Sexual Abuse) Regulation proposal, known as Chatcontrol by its critics, is a misguided attempt to address a serious issue.</p><p>If Chatcontrol comes to pass, it will force providers of all communication and messaging services such as WhatsApp, Signal, or Telegram to scan every single message in the EU to identify <em>known</em> and <em>unknown</em> abusive content, using a technique known as <em>client side scanning</em>.</p><p>Such a system cannot be implemented without great potential for misuse and abuse. It would signify the end of private online communication as we know it, and has even been <a href="https://www.techradar.com/computing/cyber-security/illegal-to-break-encryption-the-european-court-of-human-rights-rules">ruled</a> <a href="https://netzpolitik.org/2025/internes-protokoll-eu-juristen-kritisieren-daenischen-vorschlag-zur-chatkontrolle/#2025-07-15_St%C3%A4V_RAGS_CSA-VO">illegal</a> by the European Court of Human Rights.</p><p>This is why end-to-end encryption has long been hailed by technologists as the only viable option to ensure privacy with our online communications comparable to what we enjoy in the offline world.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*urp1DKajsKYsKB979jESPQ.png" /></figure><p>The CSAR proposal envisions a central European authority which would manage a database of known CSAM (Child Sexual Abuse Material), in the form of fingerprints (hashes), which would be used by the scanning technology as a reference to scan and flag messages. This is highly problematic for the following reasons.</p><p>First, it creates a chain of third parties involved in scanning your message, each of which with a number of members and employees, each additional party introduces risk, whether through malice or incompetence. What used to be an end-to-end encrypted message only visible to the sender and the receiver will now be accessed by:</p><ul><li>Messaging platform employees (e.g. WhatsApp)</li><li>Private scanning company (e.g. Ashton Kutcher’s Thorn)</li><li>European CSAR Agency staff</li><li>Europol or other law enforcement agencies that will handle flagged content, including false positives</li></ul><p>Any technologist knows these vulnerabilities compound, making a reliable system virtually impossible to build, which will in turn lead to further leaks.</p><p>Second, false positives are a significant problem. Automated systems cannot reliably flag content, and will trigger a number of false positives, from teenagers sexting, to innocent family photos, or simply because a person’s age can be hard to estimate. This problem is exacerbated even further when trying to detect new, previously unknown sexual abuse material. The law has a provision for this, and regardless of promises made by private companies with a vested commercial interest such as Thorn, it is clear that today’s AI’s cannot reliably detect such content without generating swaths of false positives.</p><p>Which brings us to the third issue: what happens to someone that has been flagged in this system through a false positive? Can we trust the designers and actors in this system to permanently discard the alert after review, without any consequences for the people chatting? Or will they end up flagged in some internal Europol database, never to be cleared? Will there be oversight on data retention? Government databases of suspicious citizens are notoriously ripe for abuse, as seen for example in the USA when tracking alleged <a href="https://www.independent.org/news-release/2025/01/23/guilt-by-association-how-californias-calgang-database-and-state-gang-laws-jeopardize-civil-liberties/">gang member</a> <a href="https://bclawreview.bc.edu/articles/10.70167/KBXI2438">affiliations</a>.</p><p>Child sexual abuse material serves as a powerful rhetorical tool for lobbyists in support of this law, which have already invested a staggering $24 million in this fight since the law was introduced by the EU commission in 2022. <a href="https://balkaninsight.com/2023/09/25/who-benefits-inside-the-eus-fight-over-scanning-for-child-sex-content/">A story by Balkan Insights</a> uncovers significant conflicts of interests and a lack of consideration for agencies with technical or domain expertise.</p><p>After many failed deliberations in the Council of the EU due to the highly controversial nature of this law, it was again thrust forward by the Danish presidency in July 2025. Many countries have changed their stance since the last deliberation in December, most notably France, who has the weight to flip the balance in an upcoming decision on October 14th, 2025.</p><p>The EU parliament has agreed on a significantly curtailed (but not problem-free) version of the law, thanks to the hard work of <a href="https://www.patrick-breyer.de/en/posts/chat-control/">Patrick Breyer</a> and others. Parliament directly represents EU citizens, whereas the Council speaks on behalf of member state governments. We are currently at the stage of parallel internal negotiations in the Parliament and Council. Next, the Parliament, Council and Commission will enter “Trilogue<em>” </em>talks where the necessary restrictions introduced in Parliament are at great risk of being watered down.</p><p>What can we do? A <a href="https://www.patrick-breyer.de/en/poll-72-of-citizens-oppose-eu-plans-to-search-all-private-messages-for-allegedly-illegal-material-and-report-to-the-police/">poll</a> seems to indicate that this law is generally unpopular with citizens, but there is danger of it slipping under the radar. <a href="https://chat-kontrolle.eu/">Follow</a> <a href="https://www.patrick-breyer.de/en/posts/chat-control/#WhatYouCanDo">these</a> <a href="https://fightchatcontrol.eu/">resources</a> to reach out to MEPs or the relevant ministries of your government. Phone calls should be prioritized here, as e-mails tend to be ignored.</p><p>Further reading:</p><ul><li>Briefs by <a href="https://www.patrick-breyer.de/en/posts/chat-control/">Patrick Breyer</a>, <a href="https://fightchatcontrol.eu/">Fightchatcontrol.eu</a> and “<a href="https://chat-kontrolle.eu/">Chatkontrolle STOPPEN!</a>”</li><li>EDRi’s <a href="https://edri.org/our-work/csa-regulation-document-pool/">document pool</a> and <a href="https://edri.org/our-work/most-criticised-eu-law-of-all-time/">collection of criticisms</a>.</li><li><a href="https://www.youtube.com/watch?v=E-EwKysAKSA">A talk</a> at CCC’s conference 37C3</li></ul><img src="https://medium.com/_/stat?event=post.clientViewed&referrerSource=full_rss&postId=2a8c717aaff7" width="1" height="1" alt="">]]></content:encoded>
        </item>
        <item>
            <title><![CDATA[Completing SICP Chapter 1]]></title>
            <link>https://medium.com/@paulsc/completing-sicp-chapter-1-f18162f4a148?source=rss-7f1d4faef472------2</link>
            <guid isPermaLink="false">https://medium.com/p/f18162f4a148</guid>
            <category><![CDATA[learning-to-code]]></category>
            <category><![CDATA[programming]]></category>
            <category><![CDATA[lisp]]></category>
            <dc:creator><![CDATA[paulsc]]></dc:creator>
            <pubDate>Mon, 19 May 2025 13:50:15 GMT</pubDate>
            <atom:updated>2025-05-20T12:08:34.705Z</atom:updated>
            <content:encoded><![CDATA[<p>I got interested in Clojure again after watching one of Rich Hickey’s <a href="https://www.youtube.com/watch?v=SxdOUGdseq4">great talks</a>. Going down the Lisp rabbit hole, I decided to take another shot at <em>Structure and Interpretation of Computer Programs</em>. Definitely an important Computer Science book, one that I always wanted to properly work through.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/500/1*29slJOMHAavKmPcpaAzeBA.gif" /></figure><p>The book uses a dialect of Lisp called <em>Scheme</em> and introduces some advanced programming concepts, which makes it all the more impressive that this is MIT’s <em>introductory</em> course to Computer Science. While a Lisp might seem like an odd choice to introduce someone to programming, I’m guessing that it’s the only language that can cover such a wide range of concepts.</p><p>Lisp is unusual at first glance. It has very little syntax, everything you write is lists containing other lists, which are delimited by round brackets, also known as parentheses. Function calls are lists where the first element is the function, and the following elements are the arguments. Basic math and logic operators also follow this rule, so that <em>x + 2</em> becomes <em>(+ x 2)</em>.</p><pre>javascript                           |  lisp<br>===================================================================<br>factorial(5);                        |  (factorial 5)<br>x + 2                                |  (+ x 2)<br>(a &lt; 3) &amp;&amp; (b &gt; 4)                   |  (and (&lt; a 3) (&gt; b 4))<br>function square(x) { return x * x }  |  (define (square x) (* x x))<br>if (x == 3) { a } else { b }         |  (if (= x 3) a b)<br></pre><p>This odd syntax is actually one of the great strengths of the language. Since everything is a list, it makes it much easier to write programs that write programs, which opens up a world of possibilities.</p><p>On my last attempt 7 years ago, I only completed 5 (!) exercises of the book. I got a little further this time around, I’ve just <a href="https://github.com/paulsc/SICP/tree/master/1.%20Building%20Abstractions%20with%20Procedures">finished</a> the first chapter. Programming languages are described as having three mechanisms for combining simple ideas to form complex ones:</p><ol><li>Primitive expressions, i.e. integers: “1”</li><li>Means of combinations, i.e. applying functions “(+ 2 2)”</li><li>Means of abstractions, i.e. defining functions “(define (inc x) (+ x 1))”</li></ol><p>The first chapter <em>(Building Abstractions with Procedures)</em>, focuses on 1 &amp; 2 and starts diving into 3. Most of the concepts introduced might not be novel to someone with programming experience, though a few things will be new to a Lisp novice. This is to say, I was able to read through chapter 1 fairly quickly, but completing all the exercises did take some “elbow grease”.</p><p>My impression is that the exercises are mental gymnastics to get you used to visualizing the flow of a program in your head, and to think at different levels of abstraction. There is a lot of recursion (A classic characteristic of Lisps), a section on orders of growth, and just a tad too much math for my taste ¯\_(ツ)_/¯.</p><p>One section goes into iterative vs. recursive behavior, a take-away is that there is a distinction between a recursive <em>procedure</em> and a recursive <em>process</em>. In the factorial example below, both are recursive <em>procedures</em>, but only the second defines an <em>iterative process</em>.</p><pre>(define (factorial n)<br>  (if (= n 1) <br>      1 <br>      (* n (factorial (- n 1)))))<br><br>(define (fact-iter n)<br>  (define (loop product counter)<br>      (if (&gt; counter n)<br>          product<br>          (loop (* counter product) (+ counter 1))))<br>    (loop 1 1))</pre><p>The book tells us that we can differentiate between both types of processes by running the code <em>by hand</em>. We pick a value (say n=5) and substitute step by step. For recursive processes, the substitutions get longer before they shrink again, an indication that memory use increases at first. With an iterative process however, the substitutions do not get longer, which tells us that memory usage is constant.</p><p>You can also tell that a process is iterative by looking at what surrounds the recursive call. For <em>fact-iter</em>, <em>(loop (* counter…)</em> happens at the “top-level”, meaning, there is no additional operation above it in that branch of the <em>if</em> clause. This is contrasted with the first example, where the <em>(factorial …)</em> call has a <em>(* n …)</em> call placed above it.</p><p>These types of <em>recursive procedures</em> that describe an <em>iterative process</em> are interesting in Lisps, because an implementation detail of those languages make this recursive procedure run without any additional memory costs, as you might have in other languages where each function call pushes a stack frame onto the call stack.</p><p>Also worth noting is that we are able to mimic the behavior of various control flow statements (e.g. for, while, do…while), just with a recursive function call and an <em>if</em> statement. This is interesting because it keeps the syntax of Lisp-languages nice and clean, i.e. just brackets wrapped in brackets. This clean structure will make it very easy later on to write programs that write programs.</p><p>The second procedure <em>fact-iter</em> describes a template for writing iterative processes, and could be one-for-one swapped with a for loop, a more traditional concept from non-functional programming languages. The pattern is:</p><ol><li>Define a function inside your function, to be called recursively.</li><li>All variables used in the iterative process are arguments to this function.</li><li>Start by defining an exit condition, to stop the iteration.</li><li>Do the recursive call, updating the variables as required.</li><li>Call loop from the main body of your function with initial values.</li></ol><p>The function above describes the same process as this for loop:</p><pre>function factorial(n) {<br>    product = 1; <br>    for (counter = 1; counter &lt;= n; counter++) { <br>        product = product * counter; <br>    }<br>    return product;<br>}</pre><p>This might seem more readable… though I suspect that this is just a matter of habit.</p><p>Finally, the chapter closes on first-class functions, where you will write a procedure that takes a procedure to return another procedure (Inception???).</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*NqMJNOoDqi1rT0ev4-JXrA.png" /><figcaption>According to the book’s cover, we are learning <em>magic! Great!</em></figcaption></figure><p>A quick word on setting up an environment: on Mac, I installed <a href="https://racket-lang.org/">Racket</a> to get a Scheme Runtime. It comes with its own IDE, but instead I opted for the <em>Magic Racket</em> extension for VS Code, just to stay in familiar territory. The workflow is not quite as polished as with Calva &amp; Clojure, but it covers the basics: you can highlight a block of code, press alt+enter, and evaluate it inside the REPL.</p><p>The default dialect of Racket actually differs slightly from the one used in the book, at one point the book uses an <em>if</em> clause that doesn’t have an <em>else</em> block (the equivalent of <em>when</em> in racket or Clojure). You can install a package in Racket for proper SICP dialect support, then run the REPL with:</p><pre>$ racket -il sicp<br>Welcome to Racket v8.16 [cs].<br>&gt;</pre><p>However, this issue came up only once, I might as well have added a dummy <em>else</em> block and stuck with the racket dialect. The other thing not really mentioned in the book that is useful is to sprinkle some <em>printf</em> statements on your code for debugging (a more compact version of “display” and “newline”).</p><pre>(printf “x:~a y:~a z:~a\n” x y z) </pre><p>On to the next chapter!</p><img src="https://medium.com/_/stat?event=post.clientViewed&referrerSource=full_rss&postId=f18162f4a148" width="1" height="1" alt="">]]></content:encoded>
        </item>
        <item>
            <title><![CDATA[Ideas for Melodic Interval Training]]></title>
            <link>https://medium.com/@paulsc/ideas-for-melodic-interval-training-b2d8a51b228e?source=rss-7f1d4faef472------2</link>
            <guid isPermaLink="false">https://medium.com/p/b2d8a51b228e</guid>
            <dc:creator><![CDATA[paulsc]]></dc:creator>
            <pubDate>Tue, 28 Nov 2023 09:31:30 GMT</pubDate>
            <atom:updated>2023-11-28T10:02:38.871Z</atom:updated>
            <content:encoded><![CDATA[<p>Here are some random ideas that came from doing daily melodic interval ear training over the past 8 weeks. I haven’t found those mentioned anywhere else so far.</p><ul><li>The first one is obvious, but use an interval trainer like <a href="https://tonedear.com/">tonedear.com</a> or similar, and practice regularly.</li><li>Build your own personal list of songs that start with that interval. (Star Wars: ascending perfect 5th, Hey Jude: descending minor 3rd, etc…). The goal is to get to a full list, with 12 ascending and 12 descending, that’s 24 songs you need. Update the list as you go along, maybe some songs don’t end up working so well. My list so far:</li></ul><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*ar57T4YQa2btuUF09bAXwA.png" /></figure><ul><li>Focus on recognizing the interval with a song reference, instead of trying to sing up or down a scale. The goal should be instant recognition, and singing up &amp; down a scale probably won’t get you there. It might be fine at the very beginning to sing the scale, just to get started, but really you should switch as soon as possible to “direct recognition” by recognizing the song that this interval evokes.</li><li>I think an exception to the rule above can be made for very small intervals, like minor &amp; major 2nds, since singing the beginning of a chromatic scale or a major scale is essentially the same as using a song for instant recognition.</li><li>The songs and melodies you choose should have the interval <em>at the beginning.</em> The goal is to hear the interval, and have the melody or song play in your head instantly, at least the first few notes. This is unlikely to work if the interval is at the middle of the melody.</li><li>Know how to sing all the songs on the list very well, so that you can easily transpose it to whatever first note you are hearing right now. I sometimes found I needed to practice playing and singing some melodies to make sure I can accurately recall them.</li><li>Sometimes we hear an interval, and we might recall a song from our list, but we are not 100% sure. Or maybe we don’t hear any song at all. In that case, the process is to verify our guesses by singing them, starting at the note we heard in the interval trainer. It is very important to sing at least 3–4 notes of the melody after the starting interval, so we can determine if it “feels right”, and if it really does match our guess. This is why the previous point of being very familiar with the songs from the list is important. It’s the only way to avoid the classic trap where we are just singing the guessed melody wrong, because we are being influenced by the interval we just heard.</li></ul><img src="https://medium.com/_/stat?event=post.clientViewed&referrerSource=full_rss&postId=b2d8a51b228e" width="1" height="1" alt="">]]></content:encoded>
        </item>
        <item>
            <title><![CDATA[Hacking Google EP05CH2: Bleichenbacher]]></title>
            <link>https://medium.com/@paulsc/hacking-google-ep05ch2-bleichenbacher-82f231830928?source=rss-7f1d4faef472------2</link>
            <guid isPermaLink="false">https://medium.com/p/82f231830928</guid>
            <dc:creator><![CDATA[paulsc]]></dc:creator>
            <pubDate>Sun, 23 Oct 2022 10:06:38 GMT</pubDate>
            <atom:updated>2022-10-23T10:06:38.609Z</atom:updated>
            <content:encoded><![CDATA[<h3>The Game</h3><p>This was undoubtedly the hardest challenge of <a href="https://h4ck1ng.google/home">the series</a>. We are provided with the URL and source to a game and told we need to score less than zero. The game is a side-scroller with a classic arcade-style high-score board that is shown when the player loses.</p><iframe src="https://cdn.embedly.com/widgets/media.html?src=https%3A%2F%2Fimgur.com%2Fa%2FEwn3JqF%2Fembed%3Fpub%3Dtrue%26ref%3Dhttps%253A%252F%252Fembed.ly%26w%3D900&amp;display_name=Imgur&amp;url=https%3A%2F%2Fimgur.com%2Fa%2FEwn3JqF&amp;image=https%3A%2F%2Fi.imgur.com%2FggiEVfy.jpg%3Ffbplay&amp;key=a19fcc184b9711e1b4764040d3dc5c07&amp;type=text%2Fhtml&amp;schema=imgur" width="900" height="660" frameborder="0" scrolling="no"><a href="https://medium.com/media/e1026948b1b91f48b27be827bae892a9/href">https://medium.com/media/e1026948b1b91f48b27be827bae892a9/href</a></iframe><p>At the end of the game, you are prompted for 3 characters for your name, and then shown the highscore board.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*RYA2mDL7HLICEVwqwi5yuA.png" /></figure><p>Let’s take a look at the code. It’s a Flask python app. The game is all JavaScript front-end minimized code that’s hard to parse, but it seems we can ignore it. The python bit has a few endpoints:</p><pre>- GET  /api/highscores to retrieve the list of highscores<br>- POST /api/highscores to submit a highscore<br>- POST /api/sign to sign a highscore for later submission<br>- GET  /api/keys to retrieve the server&#39;s public key </pre><p>To submit a highscore, we post first to <em>/api/sign</em> to get a signature from the server, and then post to <em>/api/highscores</em> with that signature to save it. The first thing that stands out is the boundary conditions for both these API calls. The <em>/api/sign</em> call strictly rejects any negative highscores, the <em>/api/highscores</em> call however will accept scores down to -65535, as long as they are properly signed.</p><p>Based on this, the obvious approach is to fabricate a valid signature to post our negative score, and bypass the <em>/api/sign</em> call entirely. Looking around a bit more, we find a <em>crypto.py</em> file which seems to be doing a bunch of homemade crypto to sign and verify those calls. Odds are high this is broken somehow, we just have to figure out how.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*6Ti8ox57Wzo5F3U_FekibQ.png" /><figcaption>The series of API calls required to submit a highscore.</figcaption></figure><h3>The Vulnerability</h3><p>In order to proceed, we need to understand the crypto mechanics at play here. All the interesting stuff happens in <em>util.py</em> and <em>crypto.py</em>. The server uses RSA public key encryption to sign a JSON array that looks like this string below. The first item in the array is a fixed constant, the second one is our player name, and the third is the score.</p><pre>[&quot;pzero-adventures&quot;, &quot;pol&quot;, 14]</pre><p>The mechanism behind generating signatures is the opposite of encryption (more on this later). The content to be signed is first hashed and then passed through the decryption process (which requires the private key), then returned to the user. To verify a highscore submission, the server then puts the signature through the encryption algorithm (which requires the public key only), which then yields the original hash again. This hash can be verified against the contents of the HTTP request, and if both match, the signature is valid.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*_0H_hYld4IzrMoQjGnvvwA.png" /></figure><p>We only have access to the server’s public key, so naturally we cannot generate our own signatures just that easily. With <a href="https://blog.trailofbits.com/2019/07/08/fuck-rsa/">a little research</a> though, we can learn some ways in which RSA is vulnerable. The link above goes into more detail, and amongst other things mentions a problem with choosing a small <em>e=3</em> parameter when setting up RSA encryption.</p><blockquote>RSA signatures are equally brittle in the presence of low public exponents. In 2006, Bleichenbacher found an <a href="https://www.imperialviolet.org/2014/09/26/pkcs1.html">attack</a> which allows attackers to forge arbitrary signatures in many RSA implementations, including the ones used by <a href="https://www.imperialviolet.org/2014/09/26/pkcs1.html">Firefox and Chrome</a>.</blockquote><p>We conveniently have access to the server’s public key through an API endpoint, so let’s check the <em>e</em> exponent:</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*Va8MrFjRp0lIXzLs_6SN5w.png" /><figcaption>The weakly selected e=3 exponent is visible below</figcaption></figure><p>The encryption exponent is 3! Bingo! Time to read up on Bleichenbacher… A basic understanding of the attack helps to put things together. No need to digest all the math, but a <a href="https://landonhemsley.com/bleichenbacher-06-rsa-signature-forgery-what-they-assume-you-know/">quick</a> <a href="https://liangchengyu.com/2020/11/11/bleichenbacher/">read</a> can <a href="https://words.filippo.io/bleichenbacher-06-signature-forgery-in-python-rsa/">help</a>.</p><h3>Bleichenbacher Signature Forgery</h3><p>An RSA key pair has three basic components: the encryption exponent <em>e</em>, the decryption exponent <em>d</em> and the moduls N. The<em> (N, e)</em> pair is the public key, while the <em>(N, d) </em>pair is kept private. These values are chosen so that given a message <em>m</em>, this is always true:</p><iframe src="https://cdn.embedly.com/widgets/media.html?src=https%3A%2F%2Fmath.embed.fun%2Fembed%2FmMGpmz9VDypgUSDoTMczH&amp;display_name=Embed+Fun&amp;url=https%3A%2F%2Fmath.embed.fun%2FmMGpmz9VDypgUSDoTMczH&amp;key=a19fcc184b9711e1b4764040d3dc5c07&amp;type=text%2Fhtml&amp;schema=embed" width="200" height="136" frameborder="0" scrolling="no"><a href="https://medium.com/media/6ba6270ff3fc9e6d513d3381fac53505/href">https://medium.com/media/6ba6270ff3fc9e6d513d3381fac53505/href</a></iframe><p>This means that for any message <em>m</em>, we encrypt it by raising it to the power of <em>e (mod N)</em>, and decrypt it again by raising it to the power of <em>d (mod N)</em>. Signatures are the opposite. The signature is generated by raising the message hash to the power of <em>d</em> (the private key), and verified with the <em>e</em> (public) exponent.</p><p>To generate a forged signature with an exponent <em>e</em> of 3, we need to find a value <em>sig</em> such that:</p><iframe src="https://cdn.embedly.com/widgets/media.html?src=https%3A%2F%2Fmath.embed.fun%2Fembed%2Ff85zntN9rA4hmZUKgwEYZ2&amp;display_name=Embed+Fun&amp;url=https%3A%2F%2Fmath.embed.fun%2Ff85zntN9rA4hmZUKgwEYZ2&amp;key=a19fcc184b9711e1b4764040d3dc5c07&amp;type=text%2Fhtml&amp;schema=embed" width="200" height="136" frameborder="0" scrolling="no"><a href="https://medium.com/media/e6bbadc9959f0730abfb546c27e68d46/href">https://medium.com/media/e6bbadc9959f0730abfb546c27e68d46/href</a></iframe><p>In this case <em>m</em> is the “clear-text” signature, which is a hash of the content, in a special standardized format that we will describe next. In other words, we should generate a hash for our malicious content, and then calculate the cube-root of this hash to find a valid signature.</p><p>Bleichenbacher relies on the fact that since the exponent <em>e</em> is small, our signature raised to the power of 3 will never wrap around the modulus. This makes it easy to try and calculate the cube root. It would be hard or impossible if <em>sig³</em> did wrap around the modulus. Our calculation will remain an approximation however because our malicious content is very unlikely to be a perfect cube. Also, due to the nature of the attack, we don’t actually need it to be exact.</p><p>Because our cube root is an approximation, when the server raises it to the power of 3 to verify it, the right-most (least significant) bytes will be mangled and contain garbage. So, what we need to run this attack is to be able to place some garbage in our signature without breaking the server’s message parsing code. Lets take a closer look at the signature now.</p><h3>The Signature Format</h3><p>The crux of the attack revolves around inserting carefully crafted “garbage data” into the message so that we can calculate a signature for it. This only works if there are some weaknesses in the server-side parser that ignore our garbage data. In this case the code follows the PKCS 1.5 standard, whose basic structure is like this:</p><pre>00 01 FF FF FF ... FF 00  ASN.1  HASH</pre><p>We have fixed 0x00 and 0x01 prefix bytes, followed by a number of 0xFF bytes for padding and a 0x00 separator byte. The last section contains our hash along with some metadata, formatted with something called <em>ASN.1</em>. The exact format can be read from the spec, deducted from the code, or we can use an online parser to verify what happens in our web app. Let’s try this last option.</p><p>We start by dumping out the signature in clear text before it goes through the RSA exponantiation. We add a print statement, in the <em>sign()</em> function of <em>crypto.py</em>.</p><p>We then run the app locally with python app.py and submit a score. Make sure to create local key files before you run the app, like so:</p><pre>$ mkdir keys &amp;&amp; cd keys<br>$ openssl genrsa -out pzero-adventures.priv -3 2048<br>$ cp pzero-adventures.priv pzero-adventures.pub</pre><p>Note the -3 argument to the <em>openssl</em> command, which specifies we want a vulnerable key with a public exponent of 3. We can then extract the clear text version of our signature below.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*mKjTvmoTZMJXiSL5qDVNMA.png" /><figcaption>Extracting the signature in clear text</figcaption></figure><p>We can recognize the format described above in the terminal output. Our 2 fixed bytes, a lot of 0xFF padding, 0x00, and then the ASN.1 payload. Let’s decode that payload by pasting it into an <a href="https://lapo.it/asn1js/#MDEwDQYJYIZIAWUDBAIBBQAEIKfi_FqO0jnG5VsWHED2Rauidhfwx7Zr6eYgnobDOlih">online parser</a>.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*mejqoufI8if0-2ThEVCJqw.png" /></figure><p>The ASN.1 structure is a sequence containing two elements. The first element of that sequence is in turn another sequence, containing an identifier describing the hashing algorithm in use (a fancy string that means “SHA256”), as well as a NULL object. The second element of the top-level sequence is the actual hash of our message. We can verify this in the terminal. In this example, I chose a player name of “aaa” and a score of -1 so the message and hash are below, matching our ASN.1 payload above.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*c_CzvpZPCqsfYULeDfVnIQ.png" /></figure><p>Now that we have a basic understanding of the structure, let’s try our attack.</p><h3>First attempt</h3><p>Thankfully we don’t have to start from scratch as there is a <a href="https://github.com/maximmasiutin/rsa-bleichenbacher-signature">tool available</a>. Let’s craft a forged signature now:</p><pre>python Forge.py -of hex -k 2048 -va 1 -ha SHA-256 \<br>  -m &quot;[\&quot;pzero-adventures\&quot;, \&quot;aaa\&quot;, -1]&quot;</pre><p>Check -help for more information about the arguments. We will get back to the -va argument later.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*LkI_KGvT1tjzQn4Igah1kA.png" /></figure><p>We can use this freshly forged signature, but first we need to pad it with zeroes to pass the length check inside <em>crypto.py</em> <em>verify()</em>. The signature should be 256 bytes, since this is hex encoded with 2 characters per bytes the total string length should be 512 characters. The easiest way to do this is to add a <em>zfill()</em> call at the <a href="https://github.com/maximmasiutin/rsa-bleichenbacher-signature/blob/1a2dc22ab8d31ab751068047ee2ae2cafc1de9df/Forge.py#L86">right line</a> inside Forge.py like so:</p><pre>    print(binary_data.decode(&quot;ascii&quot;).zfill(512))</pre><p>Using <em>httpie</em> to make our request, we end up with the following command:</p><pre>http POST <a href="http://localhost:1337/api/highscores">http://localhost:1337/api/highscores</a> name=aaa score:=-1 signature=00000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000032c38624845911817bf125c3cf15343cee1389f8cf02da307d8ca2e605f2d6db459fa83828f365fe06af9f20ddfaf42ee2635a39aaa60b400000000000000000000000000000000000000000000000000000000000</pre><p>And here it is in action:</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*6SqA1rFb14jOPptVomsW2A.png" /></figure><p>Our server crashes and throws a “invalid padding length” error. This might seem discouraging at first, but it’s a great first step, since we have managed to get past the <a href="https://github.com/paulsc/pzero-adventures/blob/c3fc6abe69a946a23c377d93fbe11eac92e452b6/crypto.py#L21">header bytes verification</a> inside crypto.py’s <em>verify()</em> function. This means we successfully generated a signature that turned into our targeted plain text on the server. Now we can focus on generating the right plain text to get past the remaining format verifications in <em>verify()</em>.</p><h3>Molding our signature</h3><p>Now that we are able to generate a signature for our chosen plain text, let’s tweak it further to see if we can get past the remaining validations.</p><p>We just faced a <em>invalid padding length</em> error. Checking <a href="https://github.com/paulsc/pzero-adventures/blob/c3fc6abe69a946a23c377d93fbe11eac92e452b6/crypto.py#L28">the code</a>, we can see that the code expects at least 8 0xFF padding bytes in the message. This is an easy fix since our python tool has an option for this. We generate another signature, adding -F 8 this time.</p><pre>python Forge.py -q -of hex -k 2048 -va 1 -ha SHA-256 -F 8 -m &quot;[\&quot;pzero-adventures\&quot;, \&quot;aaa\&quot;, -1]&quot;</pre><p>We try again and get:</p><pre>ValueError: Unexpected extra data after the DER structure</pre><p>The stack trace shows the program failed on <a href="https://github.com/paulsc/pzero-adventures/blob/c3fc6abe69a946a23c377d93fbe11eac92e452b6/crypto.py#L34"><em>sequence.decode()</em></a>. Let’s look at our generated signature in plain text by adding print(“\nCLEARTEXT\n” + k.hex()) <a href="https://github.com/paulsc/pzero-adventures/blob/c3fc6abe69a946a23c377d93fbe11eac92e452b6/crypto.py#L20">after the decryption</a> in verify(). Here it is:</p><pre>0001ffffffffffffffff003031300d060960864801650304020105000420a7e2fc5a8ed239c6e55b161c40f645aba27617f0c7b66be9e6209e86c33a58a100000000000000000000000000000000000000000000000004d6912287fb6e5bd5d86db35131734e2ce8ed7d44ebedfdc13d6cca6546469643fd096510c745c583f865982707b6896be346df1549080383b93617e0b8315a3675bac2cdcdaee7b5b495b543fbca3da3ced8a76c39c1f0be36730b7819a1a145fc36c8d6c8a09d6f65aa1bd6f686810749920ae4a86b34e424ee4db3ad1424ed33c37be45a7dd786234d6de2ee00d07fecd3c758cddd06d139efff7cfe6fb0273ce4522843f0380ecf</pre><p>We can see our 2 header bytes, our 8 0xFF padding bytes, and our ASN.1 formatted signature followed by a bunch of 0x00’s and finally our magic “garbage” bytes. What happens here is that the ASN.1 parsing library on the server is not happy just ignoring our garbage bytes at the end of the message. Thankfully, there’s another plance to hide our garbage.</p><h3>The Valsorda Variant</h3><p><a href="https://words.filippo.io/bleichenbacher-06-signature-forgery-in-python-rsa/">Filippo Valsorda</a> found a variant of Bleichenbacher’s attack where the garbage bytes are placed in the middle of the message instead of at the end. Our tool actual has support for this with the -va 2 argument. Re-running our attack with this argument leads to a <em>invalid padding content</em> error.</p><p>The -va 2 argument generated the following clear text for our signature:</p><pre>0001ffffffffffffffff815a074e97a92f7d5f4481c83ca67f87579675c0d77e1bc01af164eb69acb0bce15e020e6f5d1843206d0aa408d0bffabaab9d1527336635a5f0857886a93b6a7b40c852a76165ec5c5baba981ea62a4f25cf1909398d9331a0846f3f35464440e3e72796f4fcf1733e535610aea2072ddb8a15d7e1afc2f478baa180157ebd7e9c992d59df7cc1e1eea9c949719eda7fc53dfce1d1e0bfaafe725b8a703ef028290b0168fe81d27a567baac44410b3b8c1df9a5048ba670367fc188895883222428003031300d060960864801650304020105000420a7e2fc5a8ed239c6e55b161c40f645aba27617f0c7b66be9e6209e86c33a58a1</pre><p>We can still see our 2 prefix bytes followed by our 8 0xFF padding bytes. The “garbage” bytes are next, and our ASN.1 hash is at the end, starting with the 0x00 separator and followed by 0x30, the ASN.1 <em>sequence</em> type byte.</p><p>This attack essentially moved the “garbage” bytes inside the padding, but unfortunately our server code <a href="https://github.com/paulsc/pzero-adventures/blob/c3fc6abe69a946a23c377d93fbe11eac92e452b6/crypto.py#L30">checks</a> that all padding bytes equal 0xFF, and this is what triggers the error. Still things look promising, because the padding length is only checked up to 8 bytes, which means we can probably hide our bytes somewhere else.</p><p>Let’s have another look at the beginning of <em>verify()</em>:</p><iframe src="" width="0" height="0" frameborder="0" scrolling="no"><a href="https://medium.com/media/be4f9e861c38c7495057f5b01faca494/href">https://medium.com/media/be4f9e861c38c7495057f5b01faca494/href</a></iframe><p>Looking at this, it’s clear that we can’t hide anything in the padding. The prefix is verified and stripped and the message is split on the first 0x00 byte. Whatever comes before 0x00 is verified to be at least 8 bytes long and it <em>has</em> to be all 0xFF’s. That leaves only <em>digest_info</em> for us to hide anything in, which is the ASN.1 payload.</p><p>Let’s try to understand this payload a little better. This is what we are looking at:</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*mejqoufI8if0-2ThEVCJqw.png" /></figure><p>The general format is to have one byte for the type of object, followed by one or two bytes for the length of the object. Here’s how the structure above maps to our bytes, dumped from the web app before:</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*3LolyGkF7Sd49-snP41c7g.png" /></figure><p>Where can we add something in here in a way that the server won’t get angry ? My first intuition was to extend the top-level ASN.1 sequence to add a third element at the end. The third element could simply have a type of <em>octet string</em>, and contain the “garbage” data. To do this we can just add these bytes to the end:</p><pre>04 [length of garbage] [garbage]</pre><p>And modify the second byte (0x31) to match the new length. Unfortunately this breaks on <a href="https://github.com/paulsc/pzero-adventures/blob/c3fc6abe69a946a23c377d93fbe11eac92e452b6/crypto.py#L35">this line</a>, which uses destructuring to retrieve two elements from the <em>decode()</em> call. If the right side returns three elements, we get an error.</p><p>However the second sequence is not assigned using destructuring, but with indexing instead, as visible in lines 3 &amp; 11 below:</p><iframe src="" width="0" height="0" frameborder="0" scrolling="no"><a href="https://medium.com/media/82a799841ebdcdf4d716c5a1c2acbec4/href">https://medium.com/media/82a799841ebdcdf4d716c5a1c2acbec4/href</a></iframe><p>This means we can have our 2nd (inner) sequence have a third element, and include our garbage “magic” bytes in there. Putthing this all togther, we end up with the following structure:</p><pre>00 01 ff ff ff ff ff ff ff ff 00 30 81 f2 30 81 <br>cd 06 09 60 86 48 01 65 03 04 02 01 05 00 04 81 <br>bd </pre><pre>[ .. 192 bytes of garbage &quot;magic&quot; data ..  ]</pre><pre>04 20 a7 e2 fc 5a 8e d2 39 c6 e5 5b 16 1c 40 f6 <br>45 ab a2 76 17 f0 c7 b6 6b e9 e6 20 9e 86 c3 3a <br>58 a1</pre><p>What changed here ?</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*n-5OxSOQISo1uNdVZGU_bw.png" /></figure><p>This will work… Unfortunately our python tool doesn’t support this type of format directly, so we’ll need to make some changes to get it to produce a valid signature for this.</p><h3>Modifying the Tool</h3><p>The <a href="https://github.com/maximmasiutin/rsa-bleichenbacher-signature">python tool</a> supports Valsorda’s variant with the following format, where the payload is inserted in place of the FF bytes.</p><pre>00 01 XX XX ... XX XX 00 ASN.1 HASH</pre><p>Our variation is similar, but has an intact 8 bytes long 0xFF padding, and the payload comes in the middle of the ASN.1 data like so:</p><pre>00 01 FF FF FF FF FF FF FF FF 00 ASN.1 XX XX ... XX XX HASH</pre><p>So we have to modify the script to use a longer prefix that includes the padding and the ASN.1 data, and has a shorter suffix that has only the hash octet string portion of the ASN.1 data. The suffix is generated in <a href="https://github.com/maximmasiutin/rsa-bleichenbacher-signature/blob/1a2dc22ab8d31ab751068047ee2ae2cafc1de9df/SignatureForger.py#L87">this part</a> of SignatureForge.py:</p><iframe src="" width="0" height="0" frameborder="0" scrolling="no"><a href="https://medium.com/media/5cf0ce5cee18f7a9d6aac24b06209a8c/href">https://medium.com/media/5cf0ce5cee18f7a9d6aac24b06209a8c/href</a></iframe><p>This can be modified to the line below to remove the NULL separation byte (which is now in the prefix) and the digestInfo. We replace it with the ASN.1 header for a 32-byte long octet string as well as the hash:</p><pre>  suffix = bytes([0x04, 0x20]) + messageHash</pre><p>The prefix is generated in <a href="https://github.com/maximmasiutin/rsa-bleichenbacher-signature/blob/master/SignatureForger.py#L110"><em>addPrefixToSignature()</em></a> where we add the following two lines before the while loop:</p><pre>  bytes_to_append = &quot;003081f23081cd060960864801650304020105000481bd&quot;  <br>  prefix = prefix + bytes.fromhex(bytes_to_append)</pre><p>The header bytes and the padding are already generated in the lines above, we just need to add the NULL separation byte as well as the first half of the ASN.1 payload, including our 0481bd <em>ASN.1 octet string header</em> to hide our “magic bytes”.</p><p>When we try to run our tool now we get the following output:</p><pre>$ python Forge.py -of hex -k 2048 -va 2 -ha SHA-256 -F 8 \<br>    -m &quot;[\&quot;pzero-adventures\&quot;, \&quot;aaa\&quot;, -1]&quot;</pre><pre>Generating the signature...................................................................................................................................................................................................................................................................................................<br>Cannot generate the signature. (Key size is too small?)</pre><p>I first thought this approach had failed but after taking a closer look at the code we can see that something is up with the exit clause of the while loop:</p><iframe src="" width="0" height="0" frameborder="0" scrolling="no"><a href="https://medium.com/media/a5dbca147023ed554e2899563f6efb82/href">https://medium.com/media/a5dbca147023ed554e2899563f6efb82/href</a></iframe><p>This code was a bit intimidating at first, but in fact is very nicely explained on <a href="https://words.filippo.io/bleichenbacher-06-signature-forgery-in-python-rsa/">Filippo’s website</a>. Why the odd exit condition?</p><pre>if 0 not in toCheck[: -len(signatureSuffix)]:</pre><p>The python library that Filippo was exploiting checks for a NULL byte while parsing the signature, so his payload could not contain one. We do not have this constraint here. However, in my attempts, the higher bits of the signature could still end up mangled, likely due to the cube root estimation, so the loop above would not yield a correct result immediately. To fix this, we change the exit condition to verify that our “decrypted” signature has the expected prefix:</p><pre>  toCheck = toBytes(p, 256)<br>  if toCheck[:len(prefix)] == prefix:<br>    return signatureCandidate</pre><p>All that’s left to do is run the script, paste the signature into our POST request, and check that it works.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*JhD3NkMKzW0DM-8cL-ctyg.png" /></figure><p>Finally, just point your request to the hosted server to get the flag, and you’re done!</p><img src="https://medium.com/_/stat?event=post.clientViewed&referrerSource=full_rss&postId=82f231830928" width="1" height="1" alt="">]]></content:encoded>
        </item>
        <item>
            <title><![CDATA[Hacking Google EP05CH01: 2BPP]]></title>
            <link>https://medium.com/@paulsc/hacking-google-ep04ch01-2bpp-af2c42f134a0?source=rss-7f1d4faef472------2</link>
            <guid isPermaLink="false">https://medium.com/p/af2c42f134a0</guid>
            <dc:creator><![CDATA[paulsc]]></dc:creator>
            <pubDate>Wed, 19 Oct 2022 12:31:14 GMT</pubDate>
            <atom:updated>2022-11-23T12:49:57.694Z</atom:updated>
            <content:encoded><![CDATA[<p>This challenge has a single binary payload. All our efforts to find a data format with the usual tools are in vain, <em>file</em>, <em>binwalk</em>, <em>trid</em>, and <em>scalpel</em> all return no useful information.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*fQIe69G-l2QuJAc8rCxZBA.png" /></figure><p>Taking a look inside with <em>hexedit</em> also reveals an odd format as we see very sparse data, a lot of 00’s and not that many variations in the bytes that are not null. This leads to think that this is not a standard “computer-parsable” encoding at all, as these formats are generally more information-dense. The challenge description describes images, maybe something is simply drawn with the bytes, ascii-art style ?</p><p>I tried arranging the output in different column widths and squinting at it for a while, no luck… Eventually, it dawned on me to try the same with the binary version of the file.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*9boJz_7SDsyeRHbAIOxYVg.png" /></figure><p>After writing a python script to get binary output, I tried finding the right wrapping width by resizing the terminal:</p><iframe src="https://cdn.embedly.com/widgets/media.html?src=https%3A%2F%2Fimgur.com%2Fa%2FHhQ2IGU%2Fembed%3Fpub%3Dtrue%26ref%3Dhttps%253A%252F%252Fembed.ly%26w%3D900&amp;display_name=Imgur&amp;url=https%3A%2F%2Fimgur.com%2Fa%2FHhQ2IGU&amp;image=https%3A%2F%2Fi.imgur.com%2ForoO8Ad.jpg%3Ffbplay&amp;key=a19fcc184b9711e1b4764040d3dc5c07&amp;type=text%2Fhtml&amp;schema=imgur" width="900" height="660" frameborder="0" scrolling="no"><a href="https://medium.com/media/d8aa68b63e42723b2950fc0fae8b9601/href">https://medium.com/media/d8aa68b63e42723b2950fc0fae8b9601/href</a></iframe><p>And lo and behold… something appears !! Squinting is advised ;) We can just make out parts of the flag URL and a “2bpp” keyword. Turns out that’s an ancient sprite encoding format and stands for 2 bits per pixels. There probably is a way to get a cleaner image out of this, but I was able to just figure out the flag URL from these bits.</p><img src="https://medium.com/_/stat?event=post.clientViewed&referrerSource=full_rss&postId=af2c42f134a0" width="1" height="1" alt="">]]></content:encoded>
        </item>
        <item>
            <title><![CDATA[Hacking Google EP04CH3: git hooks]]></title>
            <link>https://medium.com/@paulsc/hacking-google-ep04ch3-fc08514f2739?source=rss-7f1d4faef472------2</link>
            <guid isPermaLink="false">https://medium.com/p/fc08514f2739</guid>
            <dc:creator><![CDATA[paulsc]]></dc:creator>
            <pubDate>Wed, 19 Oct 2022 11:45:13 GMT</pubDate>
            <atom:updated>2022-10-19T11:46:01.387Z</atom:updated>
            <content:encoded><![CDATA[<p>In the third challenge of <a href="https://h4ck1ng.google/home">this series</a>, we are still working with the same web app, and told to find a way to contribute. While poking around initially, I was scanning all the endpoints marked <em>adminsOnly</em> in app.js for something interesting and stumbled upon /contributing. That page contains the following two lines close to the top:</p><pre>$ git clone git://dont-trust-your-sources.h4ck.ctfcompetition.com:1337/tmp/vrp_repo<br>$ git checkout -b my-feature</pre><p>We check out that repository and examine the code within, finding the go app with the import and export endpoints from the previous challenge, a build script, but otherwise nothing very interesting.</p><p>The challenge description prompts us to <em>contribute</em>, so we try pushing some changes to the repo and are greeted with the lines below.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*AImgQA0UCTyUOB23V6BcFw.png" /></figure><p>Our push fails with a mention that a presubmit hook was skipped and needs an option. Maybe the vulnerability is in git this time ? This could be imaginable if git is set up with custom code and hooks on the server side. Let’s look for that option in the <em>git push</em> <a href="https://git-scm.com/docs/git-push">docs</a>.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*bX5WgiJl5ntWZQHM7LraPg.png" /></figure><p>This looks promising, so we try, and interestingly we see new output from the remote that looks a lot like the remote is trying to run the build.sh script inside our repo.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*cy62gMkmzje24cwQfusX7Q.png" /></figure><p>The next logical step is to try and modify some of these scripts to get the remote to run some malicious code. I first tried the obvious things, modifying <em>build.sh</em> and <em>configure_flags.sh</em> directly and adding some custom commands on top, but the remote output remained unchanged. Somehow, the remote does not seem to be running the full script directly from the HEAD of the repository.</p><p>However, when changing the version in configure_flags.sh, we do see the updated version in the remote output.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*HumbsutL4m9Wse_TdpgS3Q.png" /></figure><p>From there, it’s a small step to add a command expansion $() inside the version string to print our flag file. And we’re done!</p><img src="https://medium.com/_/stat?event=post.clientViewed&referrerSource=full_rss&postId=fc08514f2739" width="1" height="1" alt="">]]></content:encoded>
        </item>
        <item>
            <title><![CDATA[Hacking Google EP04CH02: notSoSafeEqual()]]></title>
            <link>https://medium.com/@paulsc/hacking-google-ep04ch02-notsosafeequal-e92143778340?source=rss-7f1d4faef472------2</link>
            <guid isPermaLink="false">https://medium.com/p/e92143778340</guid>
            <dc:creator><![CDATA[paulsc]]></dc:creator>
            <pubDate>Wed, 19 Oct 2022 10:32:53 GMT</pubDate>
            <atom:updated>2022-10-19T10:32:53.172Z</atom:updated>
            <content:encoded><![CDATA[<p>In this challenge, we are given the source code of the site from the previous challenge for analysis. The hint is that we should log in as the user <em>tin</em>.</p><p>The tarball reveals a node.js app. The app is an <em>express.js</em> node web application, and a look at app.js reveals that <em>users.getUserByUsernameAndPassword()</em> is the function that checks for a correct password. We also see two hard-coded users at the top of that module, along with their <em>sha1</em> encrypted passwords.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*evaFcsdzdV5lcqtTLc4MKA.png" /><figcaption>The log in code modified to allow any password.</figcaption></figure><p>If we add a <em>return user</em> statement to the log in function, we can make the website accept any password. We run the app locally with <em>npm run dev</em> and are greeted with the following page for the user <em>tin</em>.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*HyXQvtv190mjtGXrH2FgBw.png" /></figure><p>The flag has been removed from the source, or this would be too easy. But we can assume that it is present on the server and that we should find a way to log in there to fetch the flag. Initially, I had actually completely forgotten that there was an online version of this same app, so I wasted quite a bit of time in confusion. A massive <em>duh</em> moment followed after I was given the right pointers on discord.</p><p>We have again two approaches here, either crack the sha1 or look further into the log in code. I opted for the latter, as cracking the hash could take a long time and is not guaranteed to work if the password is solid. Also, we have a suspicious-looking custom-built<em> safeEqual()</em> function. Custom crypto code is pretty much always broken, especially so in a CTF.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*sWhZw2ZfkK71d2i4qeI5Tg.png" /></figure><p>If we take a close look at the main for loop in <em>safeEquals()</em>, we see that the match condition is broken. The intention was to compare characters one-by-one in both strings. But instead of fetching the characters with something like <em>a[i]</em>, the function uses <em>a.indexOf(i)</em>, which instead does a search and looks for the number <em>i</em> inside <em>a</em>. It then returns the index of that number inside the string.</p><p>So in effect <em>safeEquals()</em> will return true if</p><ul><li>Both strings have the same length, and</li><li>if there are numbers inside these strings, the numbers are located at the same position inside the string.</li></ul><p>If there are no numbers inside the strings, <em>safeEquals()</em> will return true if the strings have the same length only.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*akA1EvDJ9EwNCYITqezBvg.png" /><figcaption>Some inputs for which safeEqual() fails</figcaption></figure><p>This is the first part of the equation, but at this point it’s still not clear how to take advantage of this bug. If <em>tin’s</em> password on the server is the same as the hash provided in our users.js file, it contains only one number, at index 15:</p><pre>XtBEoWAkAF/UKax1SDdIHeCJbtE=</pre><p>We could try to generate a bunch of hashes until we find one that follows the same pattern, but the issue we have is with the password reset functionality of the site. The password might have been reset by someone else, so we have no idea what tin’s password might be and where numbers are contained in the new hash.</p><p>So instead, we try a “reverse” brute-force. We generate a password with a hash that we like, and keep resetting <em>tin’s</em> password on the server until <em>safeEqual()</em> matches the password <em>we</em> are trying to log in with.</p><p>We should generate a password locally that maximizes our changes of finding a match on the other end. The intuition here is that the more different numbers we have in our hash, the smaller the number of possible matches, because all these other hashes need to have those numbers in the exact same place.</p><p>Knowing this, we can write a quick script that will try to find hashes with little numbers in them, like the one below. We quickly get hits for hashes with no numbers at all.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*dw60vSduffuwpnD2dIILsw.png" /></figure><p>We can then patch together a few scripts and try our attack on localhost first. One <em>login.sh</em> script to attempt the login, one <em>reset.sh</em> script to reset the password, and one <em>pwn.sh</em> script to continually run both until a successful login is detected. We grep the output for “Found”, since we saw the app print this out when login succeeds.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*U57yo2Y-DfnANDQJD8UBmA.png" /></figure><p>It only takes a few seconds to find a match. All that’s left to do is to point the script to the server, wait for a match, and then try to log in with our chosen password on the website. That’s it!</p><img src="https://medium.com/_/stat?event=post.clientViewed&referrerSource=full_rss&postId=e92143778340" width="1" height="1" alt="">]]></content:encoded>
        </item>
    </channel>
</rss>