Skip to content

Commit

Permalink
Fix the byte to positive int issue.
Browse files Browse the repository at this point in the history
After masking the subnet, we convert it from int to byte and store it back to
bytearray.  Then in the matches() function, we convert the masked addr from int
to byte again, which may be converted to a negative value due to overflow.

Also adding a unit test to cover this case.
  • Loading branch information
madeye committed Jan 26, 2020
1 parent 4068891 commit e4382d9
Show file tree
Hide file tree
Showing 2 changed files with 12 additions and 2 deletions.
Original file line number Diff line number Diff line change
Expand Up @@ -28,10 +28,18 @@ class SubnetTest {
}

@Test
fun matching() {
fun matching1() {
val matcher = Subnet.fromString("1.10.11.12/25")!!.toImmutable()
Assert.assertFalse(matcher.matches(parseNumericAddress("1.10.10.12").address))
Assert.assertTrue(matcher.matches(parseNumericAddress("1.10.11.13").address))
Assert.assertFalse(matcher.matches(parseNumericAddress("1.10.11.212").address))
}

@Test
fun matching2() {
val matcher = Subnet.fromString("14.208.0.0/12")!!.toImmutable()
Assert.assertTrue(matcher.matches(parseNumericAddress("14.215.178.36").address))
Assert.assertTrue(matcher.matches(parseNumericAddress("14.215.178.37").address))
Assert.assertFalse(matcher.matches(parseNumericAddress("1.10.11.212").address))
}
}
4 changes: 3 additions & 1 deletion core/src/main/java/com/github/shadowsocks/net/Subnet.kt
Original file line number Diff line number Diff line change
Expand Up @@ -57,6 +57,8 @@ class Subnet(val address: InetAddress, val prefixSize: Int) : Comparable<Subnet>
}
}

fun Byte.toPositiveInt() = toInt() and 0xFF

fun matches(b: Immutable) = matches(b.a)
fun matches(b: ByteArray): Boolean {
if (a.size != b.size) return false
Expand All @@ -66,7 +68,7 @@ class Subnet(val address: InetAddress, val prefixSize: Int) : Comparable<Subnet>
++i
}
val mask = 256 - (1 shl i * 8 + 8 - prefixSize)
return i * 8 == prefixSize || a[i].toInt() and mask == b[i].toInt() and mask
return i * 8 == prefixSize || a[i].toPositiveInt() == b[i].toPositiveInt() and mask
}
}
fun toImmutable() = Immutable(address.address.also {
Expand Down

1 comment on commit e4382d9

@Mygod
Copy link
Contributor

@Mygod Mygod commented on e4382d9 Jan 26, 2020

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

Good catch...

Please sign in to comment.