Categories
Programming Taiwan

Taiwan Bank SSL Continuous Monitoring

My previous post, titled SSL status of Taiwanese banks: a sad affair sparked a lot of visits and lot of discussion, clearly touching on something important. It was great to bring to light how well (or badly, in this case) these organizations are doing, as internet security should be one of their key focus.

Many of the organizations improved their setup since then, and it became quite troublesome to manually check each bank and each change, update the table and so on. It’s also good to have not just a snapshot in time, but a continuous record of how they were doing.

Thus I’ve hacked together some monitoring scripts, put the results online, and here’s the Taiwan Financial Institute SSL Status page.

TaiwanBankSSL
Click to check the current results

Page features include:

This is quite a bit more than “minimal features”, but wanted to make something that is actually useful.

Categories
Maker Programming

Navspark: Arduino for GPS, GLONASS, and Beidou

I’m very much into satellite navigation as previous projects might show (my IT travel pack, StartupBus tracking, GPS satellite tracking). Because of this I was very excited to see an Indiegogo project for Navspark, an Arduino compatible GPS, GLONASS, and Beidou receiver. I guess everyone knows GPS, GLONASS is the equivalent Russian satellite network, and Beidou is the same for China.

I have signed up to support it for two main reasons: it’s a Taiwanese project (Skytraq, the company behind Navspark is in in Hsinchu city in Taiwan), and I haven’t seen anything about Beidou before.

They barely made the campaign, but it’s not for the lack of quality. There were a lot of updates during and afterwards as well as the project was developing. Those were good behind the scenes information, got to see what parts of hardware development are more troublesome than others.

The Navspark board

Navspark unboxing: board, antenna, pins
Navspark unboxing: board, antenna, pins

The rewards just shipped this week, and since for this campaign I’m a “local”, I got it pretty early. I got my Navspark GPS/Beidou (BD) version in a big envelope, together with an antenna, some pin and a jumper.

Categories
Programming

Making a Bitcoin service: web hierarchical deterministic wallet

It looks like Bitcoin is developing really fast these days, both on the usage and on the technical side. There are a lot of usability issues, and ideas for bitcoin services that look great on paper but don’t exist yet. Many of those ideas will be created with time, some of them though it’s better to go ahead and make as soon as possible, to let people use and see the advantages and disadvantages.

One of the most interesting ideas I’ve read so far is the creation of the Hierarchical Deterministic Wallet, or Bitcoin Improvement Proposal (BIP) 32. It is trying to solve the problem that currently the standard Bitcoin clients need generate independent new Bitcoin addresses to the user, and store a piece of secret in a wallet file for every Bitcoin address a person has. If that file is gone and not backed up, the person will lose access to those coins permanently.

Others tried to fix this too, like Armory and Electrum, two clients that can generate a whole chain of addresses, though have their own limitations that I don’t go into (though at the moment I’m using Electrum for most my coins).

BIP32 on the other hand can generate infinite number of new address from a master secret, and all of that arranged in a hierarchy that one can create well separated accounts and addresses very easily. One example is creating a separate wallet for each of the branches of a store, or for different websites a person is working on.

BIP32 key derivation scheme (click for full size)
BIP32 key derivation scheme (click for full size)

One practical problem with BIP32 was that I couldn’t find any wallet management software for it. Electrum has that in the works (I think for the 2.0 version) but they are not there yet. Had to make one myself to try it out.

Design choices

I wanted to make something easy to use (as much as possible given the hairy details), secure, and powerful enough.

For ease of use, it’s a single web page that does all the work with Javascript and HTML; try to have as few moving pieces as possible; make sensible default choices, e.g. for the structure of the hierarchy.

For security the keys entered in the page are never transmitted over the network; the created transactions can be checked independently by a 3rd party (can decode it with Blockchain.info); the single page can be saved

For power it can use both public keys for querying balance, and private keys for actually preparing transactions; it generates addresses automatically; it has everything needed for transactions within one page, with very little external dependency; have access to advanced functions if needed.

WebHDWallet main screen
WebHDWallet main screen

Implementation

It took a few day, it it was too bad to get to a working prototype: it is hosted on http://webhdwallet.github.io/, but can be downloaded with all the code to makei it a stand-alone application.

I didn’t want to implement the BIP32 extended public/private keys generation because someone better than me already did it at BIP32.org, and it is also a good way to separate responsibilities. Two independent crooked website is much less likely than one, isn’t it?

The Bitcoin functions, including using the BIP32 keys, are delegated to the bitcoinjs library. Apparently there are a bunch of forks of the original one at various stage of advancement, and incompatible added features. I have chosen the fork one that looked the most active, by BitGo, to import into this project. So far so good, maybe will do some porting of features between the forks later.

The “standard” way of creating addresses from here is creating two chains: an external that the user is supposed to share with whoever wants to pay him or her, and an internal chain for change addresses (to eliminate address reuse as payments are sent). The site creates the bunch of these addresses starting from the 0th one (as computer programming so often start to count from 0).

All of these addresses are checked with the Blockchain.info JSON API whether they ever had any transactions. If they did, then check for the spendable coins, and generate some more addresses in the chain. This tries to reduce address reuse and ensure that all addresses used so far are checked. Of course, this is one of the weaknesses of BIP32 – one can never really be sure without a lot of computation or out-of-band communication whether all the addresses ever used with the key are accounted for.

If any spendable coins are found, then the user can create a new transaction. I didn’t put in too much effort into finding a good coin-selection algorithm, just start from the oldest one and add more to the input side of the transaction until there are enough to cover the desired outgoing amount. Apparently, though, that is a good way to do it, so fair enough.

If the extended public key is used, then the page only knows enough to create an unsigned transaction. This can be checked, and hopefully later I’ll be able to implement the feature of signing such transactions  (with the same page) when being offline for security. If the private key is present, then a proper signed, spendable transaction is made, and ready to be submitted via the Blockchain.info Broadcast Transaction tool.

The receiving addresses have QR generation too. The chain addresses not, because they shouldn’t be used directly – this is just some opinionated programming.

Usage

The incoming BIP32 keys are generated as it is described in the help section of my page: choose a hard enough passphrase, and generate a child key as custom m/i’ child path (this should really be standard, by the way). It just means take the master key (m), and create the ith child in “private derivation” mode (hence the prime). Can see the original BIP32 page for some of the details.

This leaves you with an extended public key (something starting with xpub…) and an extended private key (xpriv…). Should keep the passphrase from the previous step as well, but definitely these two keys.

When one of these keys is plugged into the page, it starts to generate the appropriate keys for the two wallets, and the balance shows up. When any balance is found, a new transaction can be created, and sent off to the network with Blockchain.info.

To prove that I made this work before at least, the extended public key to generate the listed donation address of 17NWCFWo8EvFp7vtkbRH6ec3DEdxZhrhrd is xpub69i6TTB6JU2mwcQ7pKeDG8aAMnc2AZ2UdpuphoNak4nT4UTWYhkSGqpDgbGjHGbxYVK8jNF4eXMRk1aeGweLxiCWWB5EjKm3k6YMKoWN5VT (receiving address chain index 1) – go ahead, try it. Also used the page to create a small transaction – sending the from receiving address chain index 0, which also used the change chain index 0 address. When that worked, that was a relief. :)

Future

There’s a lot to do about this project and related services to make it more usable and interesting, the Issue Tracker is bursting with ideas. Here are some with higher priorities:

  • really make it offline usable (which would remove a lot of security concern, probably). Will need to think much more about the internal implementation then, how’s the most user friendly to create new transaction if you cannot go online to get data (what and how to import between online and offline)
  • make a usage video
  • generate addresses in the receive/change chain at arbitrary indexes (could be useful)
  • add QR code reading to the input field, probably via jsqrcode.
  • implement storage of retrieved data so it’s more user friendly when on non-public computer
  • talk to the bitcoin network directly, either to get the input or to send the transaction. Some groundwork is laid down in a blogpost recently about using the raw Bitcoin protocol in Python.
  • implement my own server/API for Bitcoin/Litecoin/Dogecoin that can be used with BIP32 wallets, and probably Blockchain.info compatible. Currently there are no good service for such altcoins (even if it would be pretty straightforward I think), and for the Testnet (so not risking real value to try things out)
  • implement a Point-of-Sale app (I guess on Android), that uses an extended public key to generate receive addresses for incoming transactions (totally hold-up-safe, and crooked-employee-safe payment method)
  • implement a WordPress plugin that uses extended public key to generate per-post donation addresses (for the donations themselves, as well as analytics-via-payment)

Well, at least the first step is done. All source up on Github. Would love to hear from anyone who used it, and what do you think could be improved upon.

Categories
Maker Programming

Bitcoin vending machine prototype

Since my last exploration of bitcoin, there are a lot of things happening in that topic, and the geekiness of it (among other things) didn’t let me go. There were a lot of talks about one more more Bitcoin ATMs (like Lamassu) coming here to Taiwan, but all of them are months in the future. I thought maybe it could be interesting to build my own – let’s call it – vending machine, for fiat-to-bitcoin transactions.

There were other people making similar effort, for example the Open Bitcoin ATM, but I felt they fall a bit short and unlikely that I can get the same parts over here.

Preparation

For a vending machine like this to work, there’s really only one piece of equipment is needed, the bill acceptor. I have looked around on eBay, and Alibaba for a Taiwan Dollar (TWD) bill acceptor, but there’s little to none to be found. Looks like I still got lucky that one of the big vending machine manufacturers, International Currency Technologies (ICT) is actually local (less than 1 hour on public transport from here, maybe?).

Looking around their side, they have plenty of bill acceptors (many but not all can do TWD). They don’t have any local distributor, so I got in touch with their sales directly. The first guy didn’t speak any English, but somehow after a handful of emails I got to guy with pretty good English (which is unfortunately not as common as I’d like it to be). A few weeks (yes, weeks) of emailing, and some nudging phone calls I got some useful information out of them.

I asked, what do I need if I want to use a bill acceptor for “a digital goods vending machine”, and maybe a thermal printer (that’s cool, wanted to use one for a long time)? They had some advice which parts do I need, and how much would they cost. Their recommendation:

  • XBA, the most advanced bill acceptor [US$340]
  • GP-58IV thermal printer (an advanced, not yet announced version of GP-58III) [US$150]
  • a payment system board to make it easier to use them together and with an external control board (no mention of it on the website) [US$140]

It does add up quite a bit before any housing, brains, and display – definitely more than the Open Bitcoin ATM’s supposed $165 tag. But it looked like it does worth it, I went ahead and ordered it (+5% VAT, since I’m not a company).

Parts laid out on the table
Vending machine parts: bill acceptor, control board, thermal printer.

The parts arrived quite quickly (as a reference, 3 days ago), within less than a week of the order, because they were in stock. Unpacking is fun, though soon it was obvious that not everything is smoothly on track.

The guides attached were barely scratching the surface, contained no information on how to make the units work with the computer (i.e. no protocol, no nothing), maximum referring to some software that I didn’t have access to, and would run on Windows anyways as opposed to my Linux system.

Asking and re-asking a bunch of questions to the sales guy made it clear:

  • the thermal printer does not need the payment system board, and indeed it cannot even talk to the printer (though an attached documentation says the opposite). Need a “main” board to print to it.
  • the thermal printer on the order was 12V supply and RS232 connection, while mine is 9V and USB, and apparently the former does not even exist.  It uses wallplug instead of shared power like the bill acceptor and the payment system board.
  • the payment system board cannot control the bill acceptor with the current RS232 cable, because its single RS232 connector is for the external “main” board that I should make. If I plug in the bill acceptor in there, the payment system has to be stand-alone
  • the bill acceptor comes with a power plug which is type 172340-1, that none of the local computer part stores know, so I cannot (easily) supply power to it. They will send me another adaptor cable to improve on this.

Based on all this it seems like that even if they knew my use-case correctly, the actual parts I got do not fit together the way they represented it, and there’s plenty of confusion about the specs. I really didn’t need the payment system board, for example…

All in all, my contact was quite helpful, and pretty quick to reply, though it is still quite painful first encounter with system integration, and there’s a lot more to fix with the hardware, though was good enough to start.

Assembly

There was a lot more querying in the emails about related documentation. Got the description of the ICT-104 protocol to communicate with the bill acceptor (it’s not too bad). Got the windows printer driver for the thermal printer, though managed to use it without that (and installing Windows): it turns out that the printer implements the Epson ESC/POS protocol, for which there’s already a python library, the python-escpos. It seems to be pretty dead, but good enough for initial testing. 

Thermal printer test print showing a Dallas Clayton poem, Good/Bad
Thermal printer test print

The test prints are “okay”: the text is fine (32 char/line), barcode and qr code should be usable but there seems to be some communication problem that breaks images (like the space shuttle on the above picture), that needs to be debugged (seems like not all gifs are created equal, for example, some are more reliable). Oh, I used Dallas Clayton’s poem, “Good/Bad” for the testing.

Played with the bill acceptor as well, using some pins and a bench power supply (set to 12V, the bill acceptor eats max ~0.6V when the motor is running), and hoped that I don’t blow the circuit… So far so good.

The vending machine flow is something like this:

  1. turn on
  2. read receive address of customer
  3. accept payment
  4. calculate outgoing bitcoin
  5. send payment
  6. print receipt

I was doing the printer testing in Python, and RS232 is pretty easy in Python, so just cobbled together a command line vending machine interface in Python.

Turn on, communicate with the bill acceptor, display some initial information that I know that it’s going well.

Start running zbar in the background to read qr codes from the computer’s webcam. Using the console to exchange information, didn’t have time to fix up the python-zbar integration, though it should work as the Electrum bitcoin client uses it as well.

After an address is read, read the notes of the bill acceptor, and update the sum of received pay. This is listening on the RS232 line for specific codes, and replying to tell the bill acceptor what to do (i.e. accept/reject).

When the user is finished and signaled that to the interface, calculate the outgoing value, send the payment through a payment server. The payment server is a nodejs script that accepts payment information through a REST API. It does it very badly, insecurely, using the wrong REST model (it should be “POST” to do anything with consequence, never “GET”), but it does work. It connects to a local bitcoind instance (over SSL at least, not that it matters in this case, but at least I know SSL will work for the “real” server), which at the moment is connected to the testnet, not the real one.

After the payment is sent, print the receipt with some useful information on it, and a bitcoin logo for good measure.

The current stages of the both the bitcoin vending interface, and the payment server are open source and online. And it worked, here’s a video of it in operation.

Future

I hoped it would be in better stage before tomorrow’s Bitcoin with a Lawyer’s Eyes event in the Taipei Hackerspace, but either way it is good to think ahead further.

If I want to make it really useful, and a “real” machine (one that you can kick or pour beer over it and still keeps working, as one of my friends put it), there are some specific things I can improve:

  • enclose it in a box: metal, laser cut acrylic, …?
  • better bill acceptor: keep bills in escrow before the payment gets through, disable acceptance unless we are at that stage of the workflow, set maximum vending amount in one go.
  • designa a better interface, that can do multiple payments before needing to restart
  • price not hardcoded into the software but dynamically set
  • print relevant links embedded in qr code, eg. transaction on  blockchain.info
  • make the payment server secure and improve the overall security, eg. have a code or activation for starting up
  • hook it up to the proper bitcoin network (this is the scariest part)
  • build a few more, fund them, and put somewhere accessible

Now back to work.

Ps: My purpose of building any such machine is to make it easier to acquire bitcoins, this spreading their usage and increasing their usefulness. If you feel like tipping, my address is 1GxSUTrw5onv9HbJhKN5PVhuyxm4j75X8d. Thanks!

Categories
Programming

Automating the hell out of it

Even before the 4-Hour Work Week made me more serious about this, I really enjoyed automating tasks, that benefit from not needing to remember to do, or would be troublesome to do otherwise. This frees up a lot of time, keeps a bunch of problems away, and it is actually quite fun when the information comes to me instead me going to it.

Now I have automated checking my bank account and credit card balance, updating dynamic IP of server, ebook sales numbers, and network clock synchronizing. There are some general ideas that I summarize, then give an intro to all of those scripts.

Banking script

Tools

Most of my scripts are written in bash, because it’s relatively straightforward to hammer out simple stuff, and it is surprisingly simple to do a lot of things once I have thought enough about a problem. The Advanced Bash-Scripting Guide is always on my reading list, but I usually get to check only the parts that are relevant to the given problem. You can get quite far with a few simple constructs.

The most common parts I seem to come across:

  • if-then-else constructs: if [ -f ‘directory ‘]; then echo “Found!”; fi
  • for loops: for f in *.png; do optipng $f; done
  • loading the results of a command into a variable: VAR=$(command)

For most other problems with a little keyword-fu there’s always an answer on StackOverflow or on the web.

Another group of scripts uses Python, when a bit more data-manipulation is needed, like web scraping or JSON parsing. Actually, all of the scripts could be rewritten in Python for consistency, and it would probably be be simpler too, which is something for the future.

As a general tip, most of these scripts need tweaking, and all of them are sort of alpha-beta quality code. To facilitate hacking and reduce heartache of mangled clever code, I keep everything in git repos. I share those repos online, so have to make sure there are no secrets checked in, ever. It helps to strategically use .gitignore, separate files for the secrets, and having an example how that secrets file should look in the inside.

Most of these scripts are run periodically by cron, so it is worth having some basic knowledge about how to schedule it.

Some scripts send me emails under specific circumstances (some after every run, some when new information appears), and for good delivery I have set up postfix to use Gmail as an SMTP relay. This way I’m sure to receive the emails and receive them quickly.

Scripts

These are the scripts I use most often and the longest. Still, many of them are under development and adjust them whenever I learn how to do things better. I list the links to all their repos, where it can be improved.

Banking account balances

My two main bank accounts are queried once a day for available balance and I’m notified by email. Both accounts needed quite a bit of web scraping (and got them done at two different OpenHack Taipei events). The banks’ websites are pretty awfully organized (iframes within iframes within iframes; not using CSS classes and id), though it doesn’t have to be good for me, it has to be good for the bank.

Cathay United Bank

The cathaycheck (click for repo) script queries the available balance at Cathay United Bank by logging in with curl, and parsing the final page with Beautiful Soup. The script can be a skeleton for any other website where on has to log in and then navigate over a series of pages to get the information. The required HTML variable names can be extracted with the help of the Inspect Element tools in Chrome.

At the moment the credentials is stored in the crontab command, which is not really ideal, should rewrite to use a secrets file, though given that it runs on a server where I’m the only user (and root), for me there’s no practical difference at the moment. I have set it up to receive an email at the end of the day with the current balance.

ANZ Taiwan credit card

The anzcheck (click for repo) script queries my spending with the ANZ Taiwan credit card. Again bash for logging in and Beautiful Soup for parsing the final page. It needs a bit more logic extracting information from a table, because the websites developers added no classes or ids to the items to make it easier to understand – or for them to style, but that’s not my problem.

Just recently updated that it extracts the spending items added to my balance on a given day, so I can will never be caught by surprise again (hopefully). Since many of my charges go to companies that have Chinese names, I quickly run into the problem of having to tell my Heirloom Mailx (that I use to send emails on my ArchLinux box)  that the text I want to mail is plain text, not an attachment. With some hacking the solution was to add a few more commands to “mail” so it knows that the text is UTF-8. From “sendthatmail.sh” in the repo, the parameters needed are:

-S sendcharsets=utf-8 -S ttycharset=utf-8 -S encoding=8bit

I could still extract some more information from the bank’s website, though nothing really urgent.

No-IP address updater

At the Taipei Hackerspace we have a handful of servers running, but the residential internet connection is provided by Chunghwa Telecom only gives us a dynamic IP address. Applying for a static IP seems to be pretty troublesome, so in the meantime I’m using a script on one of the servers to update the IP address associated with our dynamic tpehack.no-ip.biz address.

The no-ip-bash-updater (click for repo) script is forked originally from elsewhere, but I have rewritten it quite a bit so that it

  • needs no extra file to store the current IP address, but compares external IP with a DNS query
  • stores no secrets in the file

It uses a pretty straightforward API call with HTTP authentication, the only real logic in there is to check when that call actually needs to be made.

E-book sales

Recently I have helped a friend to publish an ebook version of How to Start a Business in Taiwan on Leanpub, and of course I want to know when there are any sales are made (disclaimer: I don’t get a cut of the sales, all goes to the author). The leanpubsales (click for repo) script is written in Python, because using JSON there is easier than it would be with bash. The call otherwise is quite simple, just keep an external file around to check if the sales number have increased or not, if yes then send an email. To send an email conditional on the output the the script the “ifne” command from moreutils is very useful (meaning: “if input is not empty”).

The query is run periodically, and lovely to receive the results. I will surely set up a script when I get my own book ideas published on Leanpub.

RTC correction

As a physicist in atomic physics, which is the area of science very much concerned about keeping precise time, keep all my servers’ times synchronized with network time protocol (NTP) using chrony. One difficulty is that the real-time clock (RTC) of those computers is pretty crappy and drifts away. Wouldn’t be a problem if I never restart them, but a pain if I do: after restart it can be tens of seconds away until the time is synchronized again.

Chrony can sync NTP and the RTC, but it doesn’t do that automatically, I have to trigger it manually. Instead I have written up an rtccorrect (click for repo) script that is run every 2 hours or so (could be done just once a day, actually), and eliminates the drift of the RTC.

Server backup

For backing up data between servers rsync has proven invaluable. I have a couple of scripts that do just that, though those are among my oldest ones and at that time I haven’t separated out personal information (way too easy to inline every credential, email, login, and all that), so I need to sanitize that. A couple of  ideas about these backup scripts:

  • sometimes higher transfer speed can be achieved by messing with the ssh algorithms, eg. passing “-e ‘ssh -c arcfour'” to rsync
  • more often there’s even better performance when there’s an rsync daemon running on the remote computer (though with Raspberry Pi, both cases are still frustratingly slow)
  • can exclude some files if no need to transfer them, eg: “–filter=’- *.part'”
  • using rsync not just to transfer but to mirror, the “–delete” (delete at target if doesn’t exist at origin) and “–archive” are pretty useful

For these backups I also use the Dead Man’s Snitch to know when things didn’t work out, e.g having a similar command in the cron list, where backup.sh is my script’s name, xxxxxxxx is the snitch ID from my account:

backup.sh && curl -s https://nosnch.in/xxxxxxx > /dev/null

This way I got to know when my backup server was dying all the time because of bad heatsink, or my host server by flaky hosting company….

Afterword

I guess there will be just more automation in the future, and maybe many of these scripts can be ported onto a common base so new ones are made much easier. What else do you guys automate?