LipiLee / ToyShark

Packet Analyzer for Android
Apache License 2.0
74 stars 35 forks source link

UDP Port out of range: -7915 #7

Closed pimterry closed 4 years ago

pimterry commented 4 years ago

Hi, I'm building an app that uses some of the VPN logic from this codebase (https://github.com/httptoolkit/httptoolkit-android), and I've been seeing this error intermittently. The error looks like this:

    java.lang.IllegalArgumentException: port out of range:-7915
        at java.net.InetSocketAddress.checkPort(InetSocketAddress.java:144)
        at java.net.InetSocketAddress.<init>(InetSocketAddress.java:239)
        at com.lipisoft.toyshark.SessionManager.createNewUDPSession(SessionManager.java:199)
        at com.lipisoft.toyshark.SessionHandler.handleUDPPacket(SessionHandler.java:65)
        at com.lipisoft.toyshark.SessionHandler.handlePacket(SessionHandler.java:195)

The error is always the same port: -7915, and it's always a UDP packet. I've made some small changes, but only related to TCP, so I don't think they're related.

Any ideas what might cause this? I can simply drop those packets myself for now, but it would be nice to know why its happening and maybe fix the issue properly. Any clues would be very helpful!

pimterry commented 4 years ago

Ah, I've found it! -7915 converted from a signed short to an unsigned short is 57621. That's the UDP port used by Spotify to communicate with networked clients (and Spotify is indeed running on this phone right now).

That suggests that somewhere here we're decoding UDP ports as signed shorts instead of unsigned, so any UDP requests to ports above 32767 will crash the VPN.

I'll dig into it and let you know once I find the problem.

pimterry commented 4 years ago

All done, the fix is here: https://github.com/httptoolkit/httptoolkit-android/commit/59fee532351a11bf6d7256171b9aa8f885bac2e0

I can't easily directly PR it, since I'm just wrapping some of the code here rather than fully forking the app, but you should be able to apply the above directly fairly easily.

Thanks for this project by the way, it's been super useful in getting my VPN set up and transparently forwarding properly :+1:.

LipiLee commented 4 years ago

Thanks for your report and fix. I will apply it.

pimterry commented 4 years ago

No problem @LipiLee, hope it's useful!

You might also be interested in https://github.com/httptoolkit/httptoolkit-android/commit/f961bdaad748b45dac947beec42b6514f0e6718f. Right now, this code loops very intensely in SocketNIODataService, which uses a lot of CPU & battery. It doesn't need to: that commit makes sure it always waits for new data to send or receive before waking up, and fixes a couple of potential race conditions around selection keys too.