mirror of
https://github.com/D-Modem/app.git
synced 2026-11-28 17:38:05 -08:00
Phone-to-phone line: an optional PIN, as a challenge and response
With a PIN set, the phone called answers RING with CHALLENGE <nonce>
(16 random octets), the caller AUTH <md5("DMODEM/1:" nonce ":" PIN)>:
the PIN never goes on the connection. A wrong PIN (or none) gets DENIED
before the phone rings, the caller's modem NO CARRIER (FAILED 403), and
each failure in a row a longer wait (1 s doubling, up to a minute) before
the next PIN is checked. Mobile calls have none of it.
The setting in the Wi-Fi and Bluetooth line's fields; secureRandomBytes
in the shared io (SecureRandom, /dev/urandom natively); tests in common
Kotlin and with the real modems (peer_host).
Co-Authored-By: Claude Opus 5.5 <noreply@anthropic.com>
Claude-Session: https://claude.ai/code/session_0172Hejd12i4aYikYW9vgpZs
This commit is contained in:
10 files changed
+185
-5
No files matched your search
@@ -78,6 +78,8 @@ object Peers {
|
||||
}
|
||||
},
|
||||
log = { log("line: $it") },
|
||||
// (a mobile call has the phone network's own: none of ours)
|
||||
pin = if (cell) "" else s.peerPin.trim(),
|
||||
_state = _state,
|
||||
_lastError = _error,
|
||||
)
|
||||
|
||||
@@ -41,6 +41,8 @@ data class ModemSettings(
|
||||
val peerName: String = "",
|
||||
/** the TCP port phones call each other on */
|
||||
val peerPort: Int = 5070,
|
||||
/** the PIN between the two phones (empty: none): callers must know this phone's, ours answers the other's */
|
||||
val peerPin: String = "",
|
||||
/** the modem's speaker on the phone's: the dialling and the handshake heard (as ATM and ATL have it) */
|
||||
val speaker: Boolean = true,
|
||||
/** the modulation on mobile calls (+MS): V21 (300 bit/s, what a speech codec carries), V22, V22B */
|
||||
@@ -106,6 +108,7 @@ class SettingsStore(private val context: Context) {
|
||||
val peerAddress = stringPreferencesKey("peer_address")
|
||||
val peerName = stringPreferencesKey("peer_name")
|
||||
val peerPort = intPreferencesKey("peer_port")
|
||||
val peerPin = stringPreferencesKey("peer_pin")
|
||||
val speaker = booleanPreferencesKey("speaker")
|
||||
val cellSpeed = stringPreferencesKey("cell_speed")
|
||||
}
|
||||
@@ -127,6 +130,7 @@ class SettingsStore(private val context: Context) {
|
||||
peerAddress = p[Keys.peerAddress] ?: d.peerAddress,
|
||||
peerName = p[Keys.peerName] ?: d.peerName,
|
||||
peerPort = p[Keys.peerPort] ?: d.peerPort,
|
||||
peerPin = p[Keys.peerPin] ?: d.peerPin,
|
||||
speaker = p[Keys.speaker] ?: d.speaker,
|
||||
cellSpeed = p[Keys.cellSpeed] ?: d.cellSpeed,
|
||||
)
|
||||
@@ -150,6 +154,7 @@ class SettingsStore(private val context: Context) {
|
||||
p[Keys.peerAddress] = s.peerAddress.trim()
|
||||
p[Keys.peerName] = s.peerName
|
||||
p[Keys.peerPort] = s.peerPort
|
||||
p[Keys.peerPin] = s.peerPin.trim()
|
||||
p[Keys.speaker] = s.speaker
|
||||
p[Keys.cellSpeed] = s.cellSpeed
|
||||
}
|
||||
|
||||
@@ -86,6 +86,21 @@ fun PeerLineFields(s: ModemSettings, onChange: (ModemSettings) -> Unit) {
|
||||
androidx.compose.material3.Switch(checked = s.listen, onCheckedChange = { onChange(s.copy(listen = it)) })
|
||||
}
|
||||
if (wifi) WifiPeer(s, onChange) else BluetoothPeer(s, onChange, context)
|
||||
OutlinedTextField(
|
||||
value = s.peerPin,
|
||||
onValueChange = { v -> onChange(s.copy(peerPin = v.filter { it in '!'..'~' }.take(32))) },
|
||||
label = { Text("PIN (optional)") },
|
||||
supportingText = {
|
||||
Text(
|
||||
"Set the same PIN on both phones: calls without it are turned down. " +
|
||||
"Without one, anyone " + (if (wifi) "on this network" else "paired with this phone") + " can call while calls are taken.",
|
||||
)
|
||||
},
|
||||
singleLine = true,
|
||||
visualTransformation = androidx.compose.ui.text.input.PasswordVisualTransformation(),
|
||||
keyboardOptions = KeyboardOptions(keyboardType = KeyboardType.Password),
|
||||
modifier = Modifier.fillMaxWidth(),
|
||||
)
|
||||
}
|
||||
}
|
||||
|
||||
|
||||
@@ -34,8 +34,8 @@ class PeerLineTest {
|
||||
fun tearDown() = closers.asReversed().forEach { runCatching { it() } }
|
||||
|
||||
/** a phone: its modem (peer_host), its DTE, its line on TCP */
|
||||
private inner class Phone(name: String, listen: Boolean, leadMs: Int = 100, var callTo: String = "") :
|
||||
TestModem(name, TcpPeerTransport(0, InetAddress.getLoopbackAddress()), listen, leadMs, closers) {
|
||||
private inner class Phone(name: String, listen: Boolean, leadMs: Int = 100, var callTo: String = "", pin: String = "") :
|
||||
TestModem(name, TcpPeerTransport(0, InetAddress.getLoopbackAddress()), listen, leadMs, closers, pin) {
|
||||
override fun target(dial: String) = PeerLine.wifiTarget(dial, callTo)
|
||||
val port: Int get() = (transport as TcpPeerTransport).localPort
|
||||
}
|
||||
@@ -158,6 +158,25 @@ class PeerLineTest {
|
||||
b.expect("still here")
|
||||
}
|
||||
|
||||
@Test
|
||||
fun aPinToCall() {
|
||||
val b = Phone("B", listen = true, pin = "2468")
|
||||
val w = Phone("W", listen = false, callTo = "127.0.0.1:${b.port}", pin = "1357")
|
||||
b.command("ATE0S0=1")
|
||||
// the wrong PIN: the modem's NO CARRIER, B never rang
|
||||
w.send("ATD1\r")
|
||||
w.expect("NO CARRIER", 20)
|
||||
assertTrue(w.events.contains("FAILED 403"))
|
||||
assertTrue(b.events.none { it == "RING" })
|
||||
// the right one: connected
|
||||
val a = Phone("A", listen = false, callTo = "127.0.0.1:${b.port}", pin = "2468")
|
||||
a.send("ATD1\r")
|
||||
connectLine(a)
|
||||
connectLine(b)
|
||||
a.send("let me in\r\n")
|
||||
b.expect("let me in")
|
||||
}
|
||||
|
||||
@Test
|
||||
fun nobodyThereAndNoAnswer() {
|
||||
// nothing listening: NO ANSWER
|
||||
|
||||
@@ -21,6 +21,7 @@ open class TestModem(
|
||||
listen: Boolean,
|
||||
leadMs: Int,
|
||||
closers: MutableList<() -> Unit>,
|
||||
pin: String = "",
|
||||
) {
|
||||
val out = LinkedBlockingQueue<String>()
|
||||
val log = CopyOnWriteArrayList<String>()
|
||||
@@ -63,6 +64,7 @@ open class TestModem(
|
||||
target = { dial -> target(dial) },
|
||||
log = { log.add(it) },
|
||||
ringMs = 1000,
|
||||
pin = pin,
|
||||
)
|
||||
line.start(listen)
|
||||
closers.add { line.stop() }
|
||||
|
||||
@@ -111,6 +111,9 @@ fun sleepMs(ms: Long) {
|
||||
/** the local time zone's offset from UTC at [epochSec] (seconds) */
|
||||
expect fun localOffsetSeconds(epochSec: Long): Int
|
||||
|
||||
/** [n] bytes from the system's secure random source */
|
||||
expect fun secureRandomBytes(n: Int): ByteArray
|
||||
|
||||
/** a byte from the source (0-255), -1 at its end */
|
||||
fun Source.read(): Int {
|
||||
val b = ByteArray(1)
|
||||
|
||||
@@ -42,6 +42,13 @@ interface PeerTransport : AutoCloseable {
|
||||
* `ANSWER`; from then on both carry the modems' samples as they are,
|
||||
* each way. Hanging up is closing it. The samples' pace is the modems':
|
||||
* each answers every sample with one of its own (the native side).
|
||||
*
|
||||
* With a [pin], the phone called first answers the RING with
|
||||
* `CHALLENGE <nonce>` (random hex), the caller `AUTH <md5 of
|
||||
* "DMODEM/1:" nonce ":" PIN, hex>`: the PIN itself never on the
|
||||
* connection. A wrong one (or none) gets `DENIED` (and the line closed)
|
||||
* and, failure after failure, the next call a longer wait first; the
|
||||
* right one rings as before. A caller's own [pin] answers a challenge.
|
||||
*/
|
||||
class PeerLine(
|
||||
private val transport: PeerTransport,
|
||||
@@ -50,6 +57,8 @@ class PeerLine(
|
||||
private val target: (String) -> String?,
|
||||
private val log: (String) -> Unit = {},
|
||||
private val ringMs: Long = 3000,
|
||||
/** the PIN a caller must know (and ours to give when we call); empty: none */
|
||||
private val pin: String = "",
|
||||
/** where the state and the last failure go (the app's, kept across lines) */
|
||||
private val _state: MutableStateFlow<State> = MutableStateFlow(State.Off),
|
||||
private val _lastError: MutableStateFlow<String?> = MutableStateFlow(null),
|
||||
@@ -75,6 +84,9 @@ class PeerLine(
|
||||
private var pending: Call? = null
|
||||
/** the call on the line (ours dialled, or answered) */
|
||||
private var call: Call? = null
|
||||
/** wrong PINs in a row, and no PIN checked again before this (monotonicMs) */
|
||||
private var failures = 0
|
||||
private var blockedUntil = 0L
|
||||
|
||||
fun start(listen: Boolean) {
|
||||
running = true
|
||||
@@ -265,6 +277,7 @@ class PeerLine(
|
||||
runCatching { conn.close() }
|
||||
return
|
||||
}
|
||||
if (pin.isNotEmpty() && !authenticate(conn)) return
|
||||
val c = Call(caller = false, conn = conn)
|
||||
val busy = synchronized(lock) {
|
||||
if (!running || pending != null || call != null) true else { pending = c; false }
|
||||
@@ -286,6 +299,40 @@ class PeerLine(
|
||||
c.connToLine()
|
||||
}
|
||||
|
||||
/** the caller challenged for the PIN: true if it knows it; else told DENIED, closed */
|
||||
private fun authenticate(conn: Duplex): Boolean {
|
||||
val nonce = secureRandomBytes(16).toHex()
|
||||
val reply = try {
|
||||
conn.output.write("CHALLENGE $nonce\n".encodeToByteArray())
|
||||
conn.output.flush()
|
||||
readLine(conn.input)
|
||||
} catch (_: IOException) {
|
||||
null
|
||||
}
|
||||
if (reply == null) {
|
||||
runCatching { conn.close() }
|
||||
return false
|
||||
}
|
||||
val wait = synchronized(lock) { blockedUntil - monotonicMs() }
|
||||
// (after wrong PINs: no answer, right or wrong, until the wait is over)
|
||||
if (wait > 0) sleepMs(wait)
|
||||
val ok = reply.startsWith("AUTH ") && constantTimeEquals(reply.substring(5).trim().lowercase(), pinProof(nonce, pin))
|
||||
synchronized(lock) {
|
||||
if (ok) {
|
||||
failures = 0
|
||||
} else {
|
||||
failures++
|
||||
blockedUntil = monotonicMs() + minOf(BLOCK_MAX_MS, 1000L shl minOf(failures - 1, 10))
|
||||
}
|
||||
}
|
||||
if (ok) return true
|
||||
log("call from ${conn.name}: ${if (reply.startsWith("AUTH ")) "the wrong PIN" else "no PIN"}, denied")
|
||||
_lastError.value = "a call from ${conn.name} with the wrong PIN"
|
||||
runCatching { conn.output.write("DENIED\n".encodeToByteArray()); conn.output.flush() }
|
||||
runCatching { conn.close() }
|
||||
return false
|
||||
}
|
||||
|
||||
/**
|
||||
* The modem off hook: [caller] dialling [dial] (the call made), or
|
||||
* answering the call that rings; [line] its samples (ours to close).
|
||||
@@ -355,7 +402,17 @@ class PeerLine(
|
||||
conn.output.write("DMODEM/1 RING ${dial.filter { it in ' '..'~' }.take(100)}\n".encodeToByteArray())
|
||||
conn.output.flush()
|
||||
c.ringing = true
|
||||
readLine(conn.input)
|
||||
var r = readLine(conn.input)
|
||||
if (r != null && r.startsWith("CHALLENGE ")) {
|
||||
if (pin.isEmpty()) {
|
||||
fail(c, 403, "${conn.name} wants a PIN: set the other phone's in the settings")
|
||||
return
|
||||
}
|
||||
conn.output.write("AUTH ${pinProof(r.substring(10).trim(), pin)}\n".encodeToByteArray())
|
||||
conn.output.flush()
|
||||
r = readLine(conn.input)
|
||||
}
|
||||
r
|
||||
} catch (_: IOException) {
|
||||
null
|
||||
}
|
||||
@@ -373,6 +430,7 @@ class PeerLine(
|
||||
c.connToLine()
|
||||
}
|
||||
"BUSY" -> fail(c, 486, "${conn.name} is busy")
|
||||
"DENIED" -> fail(c, 403, "${conn.name} turned the call down: the wrong PIN")
|
||||
else -> if (!c.ended.value) fail(c, 503, "${conn.name} didn't answer the call")
|
||||
}
|
||||
}
|
||||
@@ -397,6 +455,21 @@ class PeerLine(
|
||||
private const val TONE = 5000.0
|
||||
/** the line's octets before an answer kept at most */
|
||||
private const val EARLY_MAX = 256 * 1024
|
||||
/** the longest wait after wrong PINs */
|
||||
private const val BLOCK_MAX_MS = 60_000L
|
||||
|
||||
/** what proves the PIN for a challenge's [nonce] */
|
||||
fun pinProof(nonce: String, pin: String): String =
|
||||
Md5.digest("DMODEM/1:$nonce:$pin".encodeToByteArray()).toHex()
|
||||
|
||||
private fun ByteArray.toHex() = joinToString("") { (it.toInt() and 0xff).toString(16).padStart(2, '0') }
|
||||
|
||||
private fun constantTimeEquals(a: String, b: String): Boolean {
|
||||
if (a.length != b.length) return false
|
||||
var d = 0
|
||||
for (i in a.indices) d = d or (a[i].code xor b[i].code)
|
||||
return d == 0
|
||||
}
|
||||
|
||||
/** a line of up to [max] octets, without its newline; null at the end */
|
||||
fun readLine(input: Source, max: Int = 300): String? {
|
||||
|
||||
@@ -82,13 +82,13 @@ class PeerLoopbackTest {
|
||||
}
|
||||
|
||||
/** a phone: its line, its "modem" answering each sample with [mark], what it heard and was told */
|
||||
private inner class Phone(val name: String, exchange: Exchange, listen: Boolean, val mark: Byte) {
|
||||
private inner class Phone(val name: String, exchange: Exchange, listen: Boolean, val mark: Byte, pin: String = "") {
|
||||
val events = ArrayList<String>()
|
||||
val lock = SynchronizedObject()
|
||||
@Volatile var heardOther = 0
|
||||
@Volatile var hungUp = false
|
||||
val line = PeerLine(exchange.transport(name), events = { e -> synchronized(lock) { events.add(e) } },
|
||||
target = { it }, ringMs = 300)
|
||||
target = { it }, ringMs = 300, pin = pin)
|
||||
|
||||
init { line.start(listen) }
|
||||
|
||||
@@ -154,4 +154,41 @@ class PeerLoopbackTest {
|
||||
a.line.stop(); b.line.stop(); c.line.stop()
|
||||
}
|
||||
}
|
||||
|
||||
@Test
|
||||
fun aPinToCall() {
|
||||
val ex = Exchange().apply { pipeOf = { a, b -> pipe(a, b) } }
|
||||
val b = Phone("B", ex, listen = true, mark = 2, pin = "4321")
|
||||
val wrong = Phone("W", ex, listen = false, mark = 3, pin = "1234")
|
||||
val none = Phone("N", ex, listen = false, mark = 4)
|
||||
val a = Phone("A", ex, listen = false, mark = 1, pin = "4321")
|
||||
try {
|
||||
// the wrong PIN: turned down (NO CARRIER for the modem), B never rang
|
||||
wrong.offHook(caller = true, dial = "B")
|
||||
waitFor("W's denial") { "FAILED 403" in wrong.events() }
|
||||
assertTrue(wrong.line.lastError.value!!.contains("PIN"))
|
||||
// no PIN: the same
|
||||
none.offHook(caller = true, dial = "B")
|
||||
waitFor("N's denial") { "FAILED 403" in none.events() }
|
||||
assertTrue(none.line.lastError.value!!.contains("wants a PIN"))
|
||||
assertTrue("RING" !in b.events())
|
||||
assertTrue(b.line.lastError.value!!.contains("wrong PIN"))
|
||||
// the right one (after the wait the wrong one earned): rung, answered
|
||||
a.offHook(caller = true, dial = "B")
|
||||
waitFor("RING at B") { "RING" in b.events() }
|
||||
b.offHook(caller = false, dial = "")
|
||||
waitFor("ANSWERED at A") { "ANSWERED" in a.events() }
|
||||
waitFor("B's samples at A") { a.heardOther > 1000 }
|
||||
} finally {
|
||||
a.line.stop(); b.line.stop(); wrong.line.stop(); none.line.stop()
|
||||
}
|
||||
}
|
||||
|
||||
@Test
|
||||
fun theProof() {
|
||||
// (the PIN never on the line: md5("DMODEM/1:" nonce ":" PIN))
|
||||
assertEquals("4f977da0881b962516dbccec5ebd585d", PeerLine.pinProof("ab", "1"))
|
||||
assertTrue(PeerLine.pinProof("ab", "1") != PeerLine.pinProof("ab", "2"))
|
||||
assertTrue(PeerLine.pinProof("ab", "1") != PeerLine.pinProof("ac", "1"))
|
||||
}
|
||||
}
|
||||
@@ -31,3 +31,7 @@ fun Sink.asOutputStream(): OutputStream = object : OutputStream() {
|
||||
override fun flush() = this@asOutputStream.flush()
|
||||
override fun close() = this@asOutputStream.close()
|
||||
}
|
||||
|
||||
private val secure = java.security.SecureRandom()
|
||||
|
||||
actual fun secureRandomBytes(n: Int): ByteArray = ByteArray(n).also { secure.nextBytes(it) }
|
||||
@@ -8,6 +8,11 @@ import kotlinx.cinterop.memScoped
|
||||
import kotlinx.cinterop.convert
|
||||
import kotlinx.cinterop.ptr
|
||||
import kotlinx.cinterop.value
|
||||
import kotlinx.cinterop.addressOf
|
||||
import kotlinx.cinterop.usePinned
|
||||
import platform.posix.fclose
|
||||
import platform.posix.fopen
|
||||
import platform.posix.fread
|
||||
import platform.posix.localtime_r
|
||||
import platform.posix.time_tVar
|
||||
import platform.posix.tm
|
||||
@@ -21,3 +26,18 @@ actual fun localOffsetSeconds(epochSec: Long): Int = memScoped {
|
||||
val r = alloc<tm>()
|
||||
if (localtime_r(t.ptr, r.ptr) == null) 0 else r.tm_gmtoff.toInt()
|
||||
}
|
||||
|
||||
/** (/dev/urandom: Linux's and iOS's) */
|
||||
@OptIn(ExperimentalForeignApi::class)
|
||||
actual fun secureRandomBytes(n: Int): ByteArray {
|
||||
val out = ByteArray(n)
|
||||
if (n == 0) return out
|
||||
val f = fopen("/dev/urandom", "rb") ?: throw IOException("no /dev/urandom")
|
||||
try {
|
||||
val got = out.usePinned { fread(it.addressOf(0), 1u, n.convert(), f) }
|
||||
if (got.toInt() != n) throw IOException("/dev/urandom: short read")
|
||||
} finally {
|
||||
fclose(f)
|
||||
}
|
||||
return out
|
||||
}
|
||||
Reference in new issue
Block a user