Securing DNS Traffic in China

Overview

DNS poisoning is one of the most common cause of nuisance when accessing websites
that are outside this 1.4 billion-people Oriental country. So far, the best way to protect yourself from this trouble is to route all your DNS traffic through an encrypted channel, and the method I am going to introduce is DNSCrypt. There is not yet a standard for encrypted DNS, DNSCrypt is a project done by OpenDNS. According my experience, DNSCrypt is very reliable and robust, the cryptography of the protocol is called DNSCurve, which is a public-key crypto that employes an extremely strong elliptic-curve cryptography called Curve25519.

If you have read my previous writing, you should know my setup is a Raspberry Pi, and so the rest of this article is based on that, running Raspbian. Dnsmasq will be used as the first DNS caching proxy to serve incoming DNS queries from machines on the network. If the queried domain name is a China one, the request will be served by a China DNS. This is necessary because for some domains, answers from DNS servers in China and global ones could be different. If the requested domain does not belong to any known China domains, the request will be forwarded to dnscrypt-proxy, which will ask a DNSCrypt server for an answer.

After DNSCrypt is used, your DNS traffic will look like this:

                                             +----------------------+
                                             |   China DNS server   |
                                      +----> |                      | 
                                      |      | e.g. 114.114.114.114 |
                                    China    +----------------------+
                                   domains
                                      |
                                +-----|---------------------------------+
                                | +-------+   Other   +----------------+|
       +------+                 | |dnsmasq|---------->| dnscrypt-proxy ||
       | Host |-- DNS query --> | +-------+  domains  +----------------+|
       +------+                 |                              |        |
                                |            Raspberry Pi      |        |
                                +------------------------------|--------+
                                                               V
                                                       +---------------+
                                                       |DNSCrypt server|
                                                       +---------------+

Setting up DNSCrypt

As illustrated in the above diagram, dnscrypt-proxy is the piece of software that handles DNSCrypt, but it is not available in Raspbian’s Wheezy and Jessie releases, only in testing (currently Stretch). You can either compile it yourself, or grab the debian package I built and install it. You can find the package here. It is based on the Raspbian package in testing repo, with some modification to debian packaging files, since the one in testing depends on systemd, which had not yet been adopted when Wheezy was released.

If you really want to build the package yourself, first install the libsodium packages. The package are also not available in Wheezy repo but the ones from testing, libsodium13_1.0.3-1_armhf.deb and libsodium-dev_1.0.3-1_armhf.deb, can be installed without any problem. Download and install them, then follow these steps to build your dnscrypt-proxy package:

$ sudo apt-get install autotools-dev debhelper pkg-config
$ git clone https://github.com/anthonywong/dnscrypt-proxy-raspbian-wheezy.git
$ cd dnscrypt-proxy-raspbian-wheezy.git
$ fakeroot debian/rules binary

After dnscrypt-proxy is installed, you have to update the port it uses. Change DNSCRYPT_PROXY_LOCAL_ADDRESS in /etc/default/dnscrypt-proxy to another port other than 53 (as it will be used by dnsmasq later), like this:

DNSCRYPT_PROXY_LOCAL_ADDRESS=127.0.0.1:5353

You can also change the remote DNSCrypt server, but since the default (cisco) works well for me, I left it unchanged.

Now test it to make sure it works as expected:

$ dig @localhost -p 5353 www.facebook.com

; <<>> DiG 9.8.4-rpz2+rl005.12-P1 <<>> @localhost -p 5353 www.facebook.com
; (2 servers found)
;; global options: +cmd
;; Got answer:
;; ->>HEADER<<- opcode: QUERY, status: NOERROR, id: 9735
;; flags: qr rd ra; QUERY: 1, ANSWER: 2, AUTHORITY: 0, ADDITIONAL: 1

;; OPT PSEUDOSECTION:
; EDNS: version: 0, flags:; udp: 4096
;; QUESTION SECTION:
;www.facebook.com.      IN  A

;; ANSWER SECTION:
www.facebook.com.   2725    IN  CNAME   star-mini.c10r.facebook.com.
star-mini.c10r.facebook.com. 47 IN  A   31.13.77.36

;; Query time: 140 msec
;; SERVER: 127.0.0.1#5353(127.0.0.1)
;; WHEN: Mon Jan 18 00:39:36 2016
;; MSG SIZE  rcvd: 90

$ dig @localhost -p 5353 www.sina.com.cn

; <<>> DiG 9.8.4-rpz2+rl005.12-P1 <<>> @localhost -p 5353 www.sina.com.cn
; (2 servers found)
;; global options: +cmd
;; Got answer:
;; ->>HEADER<<- opcode: QUERY, status: NOERROR, id: 22371
;; flags: qr rd ra; QUERY: 1, ANSWER: 5, AUTHORITY: 0, ADDITIONAL: 1

;; OPT PSEUDOSECTION:
; EDNS: version: 0, flags:; udp: 4096
;; QUESTION SECTION:
;www.sina.com.cn.       IN  A

;; ANSWER SECTION:
www.sina.com.cn.    2733    IN  CNAME   jupiter.sina.com.cn.
jupiter.sina.com.cn.    3580    IN  CNAME   region.sina.csglb.txcdn.cn.
region.sina.csglb.txcdn.cn. 1261 IN CNAME   n2wous.panthercdn.com.
n2wous.panthercdn.com.  20  IN  A   103.4.200.227
n2wous.panthercdn.com.  20  IN  A   103.4.200.235

;; Query time: 125 msec
;; SERVER: 127.0.0.1#5353(127.0.0.1)
;; WHEN: Mon Jan 18 00:38:25 2016
;; MSG SIZE  rcvd: 171

Setting up dnsmasq

Dnsmasq is very common and is available in Raspbian, installing it is easy:

$ sudo apt-get install dnsmasq

Now we have to do some configuration in /etc/dnsmasq.conf. These are my recommended settings. Please note that the interface option is the network interface that dnsmasq will serve, and in my case that is wlan0. You have to change it to the one that applies to your case.

domain-needed
bogus-priv
no-resolv
interface=wlan0

Now comes the interesting part. We are going to tell dnsmasq to use a China DNS server (114.114.114.114 in my example) for China domains and DNSCrypt server for all others. This is done by using the server option in /etc/dnsmasq.conf. Here is an example:

# Add other name servers here, with domain specs if they are for
# non-public domains.
server=/baidu.com/114.114.114.114
server=/sina.com/114.114.114.114
server=/ifeng.com/114.114.114.114
server=/phoenixtv.com/114.114.114.114
...
server=/deppon.com/114.114.114.114
server=127.0.0.1#5353

This is pretty straightforward. The last line tells dnsmasq to use your dnscrypt proxy if the domain you query does not match any China domains. In my config file there are 12238 lines for China domains so I'm not going to post them all here, you can get the snippet of my dnsmasq.conf here, and put it into your own dnsmasq.conf. The problem is to maintain the list for all China hosts. I am now using the list from the fqrouter project, it has been serving me well, since most common domains are already there. What's worrying is due to the abandon of the project by it's author, the list is now unmaintained. If you know a more updated list, please let me know!

32 thoughts on “Securing DNS Traffic in China”

  1. Excellent! This has been driving me nuts here in China. I’ll be implementing this tonight on my router. I would greatly appreciate if you do find any better list for chinese domains, though to be frank the number of chinese sites I visit is limited and I’ll gladly take a slightly longer domain lookup time for those vs the dozens and dozens of foreign domains that get filtered.

  2. I have just tested this on Raspberry Pi 2, with latest Raspbian version ( I think it’s Jessie), but it doesn’t work. Here are my steps:

    1. Download you DEB file.
    2. sudo apt-get install libsodium13
    3. Install DEB file with dpkg -i.
    4. Set “DNSCRYPT_PROXY_LOCAL_ADDRESS=127.0.0.1:5353” in /etc/default/dnscrypt-proxy. (Also tried real eth0 IP address 192.168.1.1:5353)
    5. sudo /etc/init.d/dnscrypt-proxy start
    6. Run ps -ef, cannot see dnscrypt-proxy. In syslog, it shows
    RASPI2 systemd[1]: Started LSB: Start and stop dnscrypt-proxy.

    I already have dnsmasq installed which used default port 53, which is working fine.

    Any ideas? Thanks!

  3. BTW, /etc/default/dnscrypt-proxy shows the following. Is this setting being ignored because it uses systemd?
    # What local IP the daemon will listen to, with an optional port.
    # The default port is 53. If using systemd, this is not used and must be
    # specified in dnscrypt-proxy.socket.
    DNSCRYPT_PROXY_LOCAL_ADDRESS=127.0.0.1:5353

  4. Here’s a full log. Even if I stop dnsmasq, dnscrypt-proxy still won’t start.

    dnscrypt-proxy: – [cisco] does not support DNS Security Extensions
    dnscrypt-proxy: – [cisco] does not support Namecoin domains
    dnscrypt-proxy: – [cisco] logs your activity – a different provider might be better a choice if privacy is a concern
    dnscrypt-proxy[588]: Starting dnscrypt-proxy 1.6.0
    dnscrypt-proxy[588]: Generating a new session key pair
    dnscrypt-proxy[588]: Done
    dnscrypt-proxy[517]: Starting dnscrypt proxy service…: dnscrypt-proxy.
    systemd[1]: Started LSB: Start and stop dnscrypt-proxy.

  5. @anthony – FYI I ended up using https://github.com/shadowsocks/ChinaDNS despite the fact that its not as well developed anymore as I could get it onto my ubiquiti Edgerouter much easier. Seems to be working quite well as far as I can see so far, especially combined with dnsmasq to cache results. I would be interested to know if you considered it and how your current setup is working for you?

  6. 我完全不明白中国
    DNSCrypt should be baned in China but CN repos publish that.20years ago, Fuckin’ freakin’ America Empire also restrict encryption.

  7. Hello, Anthony Wong.I am a reader of the book 《Using Docker – Developing and Deploying Software with Containers》.
    I found a little bug on page 20 of the book.And maybe you can pay attention to it when the book is published next time.
    The bug is that Dockerfile’s name must be lowercase, but the Dockerfile’s name of the example include upper case. :)

  8. Muchos jugadores en Chile eligen Pin-Up Casino porque aqui siempre encuentran las tragamonedas mas buscadas, ademas de ser un sitio seguro, donde cada detalle esta disenado para que puedas divertirte sin preocupaciones.

    Desde el registro, que es rapido, sencillo y 100% gratuito, hasta el retiro de tus ganancias, todo funciona de forma segura, veloz, eficiente. Solo necesitas registrarte y acceder a Pin-Up juegos online para activar tus bonos en minutos.

    Al ingresar al catalogo de juegos descubriras ruleta online. No importa si prefieres los jackpots acumulados, siempre encontraras algo emocionante para ti.

    Miles de jugadores chilenos destacan el sistema de depositos instantaneos. Pin-Up Casino Chile ofrece soluciones adaptadas al jugador chileno, permitiendo gestionar tu saldo de forma simple y segura.

    Ademas, cuentas con equipo de asistencia capacitado, para resolver cualquier duda de forma personalizada y siempre disponible.

    Puedes jugar donde quieras, cuando quieras, ya que la plataforma esta completamente optimizada para uso movil.

    Para muchos chilenos, Pin-Up Casino se ha convertido en el mejor casino online de Chile. Gracias a promociones permanentes, cada visita es una nueva oportunidad de ganar.

    Si estas buscando un sitio fiable para jugar online, Pin-Up Casino Chile es el lugar donde la experiencia de casino alcanza otro nivel.

  9. А ты уже олучил|забрал|участвовал] в розыгрыше NFT от LoveShop? ?? “Shop1-biz” азыгрывает|дарит|предлагает] есплатные|эксклюзивные] токены всем новым участникам! Переходи по ссылке и забери свой! ??

    #loveshop #shop1 #loveshop1300-biz #shop1-biz #loveshop12 #loveshop14 #loveshop13 #loveshop15 #loveshop16 #loveshop17 #loveshop18

    предлагает] есплатные

    Подробнее
    https://blsa-at.cc/contact/

    #loveshop #shop1 #loveshop1300-biz #shop1-biz #loveshop12 #loveshop14 #loveshop13 #loveshop15 #loveshop16 #loveshop17 #loveshop18

  10. Players in Bangladesh are increasingly choosing dailydhakareport.com for online gaming and rewards. The platform provides access to popular games like slots, rummy and aviator with a welcome bonus for new users. Visit the site to download the APK and start playing today.

  11. The funds were sent according to the request, but the exchange was not carried out, although the deadline set by the regulations has already passed. What to do?

    If the exchange is made at one of the BestChange monitoring exchange offices, then you don’t have to worry: the funds will not disappear anywhere, since the presence of fraudulent sites is excluded in the rating.

    Sometimes, some exchange offices, like any organization, may have problems with the timely provision of services to customers. In such cases, we recommend following the following recommendations:

    – Wait a bit: as a rule, most exchanges are completed within an hour, unless otherwise specified in the exchange office conditions. The delay may be longer if the exchange was conducted outside of business hours, so you should pay attention to the schedule of a particular service listed on its website.
    – Contact the support service of the exchange office where the exchange was carried out. It is worth trying the different communication methods presented on the service’s website: perhaps some of them will turn out to be more efficient.
    – As a last resort, you can file a claim against the exchange office on the monitoring website (red negative review), specifying the exchange number. Exchange office administrators, having received an alert about a user’s complaint, can react faster to the problem, and upon completion, comment on it directly on the BestChange website.

  12. РедМетСплав предоставляет внушительный каталог отборных изделий из редких материалов. Не важно, какие объемы вам необходимы — от тестовых образцов до крупных поставок, мы выдерживаем быстрое выполнение вашего заказа.

    Каждая единица продукции подтверждена соответствующими документами, подтверждающими их соответствие стандартам. Дружелюбная помощь — то, чем мы гордимся — мы на связи, чтобы улаживать ваши вопросы по мере того как находить ответы под нюансы вашего бизнеса.

    Доверьте потребности вашего бизнеса команде РедМетСплав и убедитесь в гибкости нашего предложения.

    Ассортимент включает:
    Лента вольфрамовая ВИ-30 Лента вольфрамовая ВИ-30 – это высококачественный материал, идеально подходящий для различных промышленных применений. Благодаря своей высокой плотности и термостойкости, эта лента обеспечивает отличные эксплуатационные характеристики. Волфрамовая лента устойчива к коррозии и механическим повреждениям, что делает ее долгосрочным решением для вашей работы. Если вы ищете надежный и эффективный материал, купить Лента вольфрамовая ВИ-30 – это отличный выбор. Доверьтесь качеству и сделайте шаг к успешному завершению ваших проектов с этой продукцией!

  13. РедМетСплав располагает солидную линейку качественных изделий из уникальных материалов. Не важно, какие объемы вам необходимы — от тестовых образцов до обширных поставок, мы соблюдаем пунктуальность вашего заказа.

    Каждая единица номенклатуры подтверждена всеми необходимыми документами, подтверждающими их соответствие стандартам. Превосходное обслуживание — наш стандарт — мы на связи, чтобы прояснять ваши вопросы одновременно с этим адаптировать решения под специфику вашего бизнеса.

    Доверьте вашу потребность в редких металлах специалистам РедМетСплав и убедитесь в гибкости нашего предложения.

    Ассортимент включает:
    Изделия из молибдена М-МП Изделия из молибдена М-МП обладают высокой прочностью и термостойкостью, что делает их идеальными для применения в экстремальных условиях. Эти изделия устойчивы к коррозии и имеют отличные электрические свойства. Подходят для различных промышленных и исследовательских задач, включая атомную энергетику и машиностроение. Если вы ищете надежное решение для своего проекта, купить Изделия из молибдена М-МП — отличный выбор. Они помогут повысить эффективность и долговечность ваших изделий. Выберите качество, на которое можно полагаться!

Leave a Reply

Your email address will not be published.