...how can you ensure that they do not use it for any illegal
purposes? Especially when their work is used in multiple countries?
You cannot. But if someone asks me to write a module that secretly stores keystrokes and email them somewhere, then I would probably decline the job. Use your common sense, is it a registered company, is it fairly innocuous coding, has anything raised red flags to your sense of morality. If you have any concerns, drop the client and move on.
Would it be possible to include it in an email or a contract that
"...and the client x agrees that whatever software I develop for
client x will be used only for purposes acceptable under the law of
this country and under international law..."?
Yes you could, but depending what you are being asked, this would probably not offer you any protection legally, and is a bit of a weird thing to include in a contract.
If a freelancer creates software for a client with the knowledge that
the software is going to be used for legal purposes, and if the client
uses the software for something illegal in future, then what is the
liability of the freelancer?
Well, if you know and take part, then you are a conspirator to the crime. So if you 'know' that is the case, then yes, of course you are risking a criminal charge of some description.
There is a simple rule of thumb in business IMHO (of course there are many). That is to 'play by the rules of the game'. The game here is the law of course, so put simply, do not break the law, but further than that, do not do anything you are uncomfortable with. This customer has clearly raised some concerns for you. My advice would be in that situation, drop the job and move on.
One example I have for you, a customer approached me because he saw the site I had built for his competitor. He said something like "I want a copy of that site, just change the design a bit so it looks different". He offered a fair amount of money, but I felt uncomfortable. So I turned him down politely. He then got very shirty with me, called me several times, ended in verbal abuse. Now was I right to drop him? Given the charachter he displayed when he didn't get his way, absolutely I was right. If you are in any way uncomfortable, just do not do it.
From your question, it seems to me that you are worth more than that and are better than that.