From mboxrd@z Thu Jan 1 00:00:00 1970 Return-Path: Received: from simark.ca by simark.ca with LMTP id 0RpZAtNjAGuPeSQAWB0awg (envelope-from ) for ; Fri, 20 Nov 2026 10:14:27 -0500 Authentication-Results: simark.ca; dkim=pass (1024-bit key; unprotected) header.d=redhat.com header.i=@redhat.com header.a=rsa-sha256 header.s=mimecast20190719 header.b=g7vRotCk; dkim-atps=neutral Received: by simark.ca (Postfix, from userid 112) id F2D7B1E023; Fri, 20 Nov 2026 10:14:26 -0500 (EST) X-Spam-Checker-Version: SpamAssassin 4.0.1 (2024-03-25) on simark.ca X-Spam-Level: X-Spam-Status: No, score=-3.4 required=5.0 tests=ARC_SIGNED,ARC_VALID,BAYES_00, DKIMWL_WL_HIGH,DKIM_SIGNED,DKIM_VALID,DKIM_VALID_AU,MAILING_LIST_MULTI, RCVD_IN_DNSWL_MED,RCVD_IN_VALIDITY_CERTIFIED_BLOCKED, RCVD_IN_VALIDITY_RPBL_BLOCKED,RCVD_IN_VALIDITY_SAFE_BLOCKED autolearn=ham autolearn_force=no version=4.0.1 Received: from vm01.sourceware.org (vm01.sourceware.org [38.145.34.32]) (using TLSv1.3 with cipher TLS_AES_256_GCM_SHA384 (256/256 bits) key-exchange x25519 server-signature ECDSA (prime256v1) server-digest SHA256) (No client certificate requested) by simark.ca (Postfix) with ESMTPS id 9B7981E023 for ; Fri, 20 Nov 2026 10:14:25 -0500 (EST) Received: from vm01.sourceware.org (localhost [IPv6:::1]) by sourceware.org (Postfix) with ESMTP id 6295F42F9B99 for ; Fri, 20 Nov 2026 15:14:24 +0000 (GMT) DKIM-Filter: OpenDKIM Filter v2.11.0 sourceware.org 6295F42F9B99 Authentication-Results: sourceware.org; dkim=pass (1024-bit key, unprotected) header.d=redhat.com header.i=@redhat.com header.a=rsa-sha256 header.s=mimecast20190719 header.b=g7vRotCk Received: from us-smtp-delivery-124.mimecast.com (us-smtp-delivery-124.mimecast.com [170.10.133.124]) by sourceware.org (Postfix) with ESMTP id E70C44BC054C for ; Fri, 20 Nov 2026 15:13:10 +0000 (GMT) DMARC-Filter: OpenDMARC Filter v1.4.2 sourceware.org E70C44BC054C Authentication-Results: sourceware.org; dmarc=pass (p=quarantine dis=none) header.from=redhat.com Authentication-Results: sourceware.org; spf=pass smtp.mailfrom=redhat.com ARC-Filter: OpenARC Filter v1.0.0 sourceware.org E70C44BC054C Authentication-Results: sourceware.org; arc=none smtp.remote-ip=170.10.133.124 ARC-Seal: i=1; a=rsa-sha256; d=sourceware.org; s=key; t=1795187591; cv=none; b=hhGO+FdWDhybYzQIyUODHZacvFsTdhYb8/gX3wWin8CfHIBVUlAsRdTj04wLtJGvUlWRDURv71N+ubzdEhWGgI7JDenTm/hBmUbKgi1xCWnymigSOT0vy3rPxR+HiKLp80yUzxDexEQxHtStmCYLCKjWtM3f9UvGyqG5TyE92cY= ARC-Message-Signature: i=1; a=rsa-sha256; d=sourceware.org; s=key; t=1795187591; c=relaxed/simple; bh=lRPLjdgm6gaFiu8MSDxKMgKqeUJW15RCmE275rUv16w=; h=DKIM-Signature:From:To:Subject:Date:Message-ID:MIME-Version; b=KpxD3FDWtxjqEHyx3ttCXXKGNgz66SA2i/Bk29/IUnuuzD8zK/bkkGBZ+Pauc5+nphWqL5nXurPoMb6HUv61mJRWOuCIVhE3OzvSv6UNzfKlhnPKYihr81sgs1IDMxiOvFfky2AYZhFhDWWH1Dvx1LEdrkr8GBacQ3nXjlf49F4= ARC-Authentication-Results: i=1; sourceware.org; dkim=pass (1024-bit key, unprotected) header.d=redhat.com header.i=@redhat.com header.a=rsa-sha256 header.s=mimecast20190719 header.b=g7vRotCk DKIM-Filter: OpenDKIM Filter v2.11.0 sourceware.org E70C44BC054C DKIM-Signature: v=1; a=rsa-sha256; c=relaxed/relaxed; d=redhat.com; s=mimecast20190719; t=1795187590; h=from:from:reply-to:subject:subject:date:date:message-id:message-id: to:to:cc:cc:mime-version:mime-version:content-type:content-type: content-transfer-encoding:content-transfer-encoding: in-reply-to:in-reply-to:references:references; bh=PhFkj6lW1alqvGTEJcaS20aM4bqKEYC/Be0ZuAkiv/g=; b=g7vRotCkNakZBB492fpb/eKXRoQmK80JvQWc+Ras0IHqT54cwiJquz9lPoadFn5VdjEuRc TEcFyWkEfU2PxmZmIO0beYYWblCFzvLyWTfCr8xDX43fTe0XATuE7Qkkl9sC54pTk+tVEN Sfxpk5VqsU9BYc3M7MY6+aAnDYz0Jak= Received: from mail-wr1-f72.google.com (mail-wr1-f72.google.com [209.85.221.72]) by relay.mimecast.com with ESMTP with STARTTLS (version=TLSv1.3, cipher=TLS_AES_256_GCM_SHA384) id us-mta-210-ZXXJXrBDObCg6MIAkgb5og-1; Fri, 20 Nov 2026 15:13:07 +0000 X-MC-Unique: ZXXJXrBDObCg6MIAkgb5og-1 X-Mimecast-MFC-AGG-ID: ZXXJXrBDObCg6MIAkgb5og_1795187586 Received: by mail-wr1-f72.google.com with SMTP id ffacd0b85a97d-4a7c864000eso573987f8f.0 for ; Fri, 20 Nov 2026 07:13:06 -0800 (PST) X-Google-DKIM-Signature: v=1; a=rsa-sha256; c=relaxed/relaxed; d=1e100.net; s=20260707; t=1795187586; x=1795792386; h=content-transfer-encoding:mime-version:references:in-reply-to :message-id:date:subject:cc:to:from:x-gm-gg:x-gm-message-state:from :to:cc:subject:date:message-id:reply-to:content-type; bh=PhFkj6lW1alqvGTEJcaS20aM4bqKEYC/Be0ZuAkiv/g=; b=CU9ySuIV9uAUB1QtvpAyM6PTkclASTR6YBdiRJDOE+iAgnMUPX8hVBLTP94eXg+iWh O2NHcasMarb4O2DdqGZYBnlqc56jZTAi6nrGwgb0GNSBEm29FVUIJFolyPLB0e5VWvGB YLcaOICAbqMnaemFJyNTBEP11ANxp3JpYTMd2ayqAQcFK/X0RxusuUXIuk9Yci5EDkzu 2+2RXP9EA286HbaN60QJAMczKPkAew0jo+2O/YhGZ82LEJOUZ+FL44uzpafkiib2xE0d OHKzX4hZgCSv+6TnvPZ8BbPZIv7La82NErPABqotQl4UgQuSCXfxvUph3aat3oRv4+Xe +Uxw== X-Gm-Message-State: APuU4Z8I1RLn7AAg2eHTIw78WUTap3OHMFUIEndY0Z0VhC46jaLjjVMk dA5oZfq/vYO3S27q4bO+yemWg6X2CbY9b48iONFJEYK4+HgqCM1LjXWLTT1igI6PdnzzWGoYL1E UpEqCB56U7sioWgbLkhv+sC9StU/6w7XsELe8NLTO1pQ4MnwNIU/de5eJMcgm0tgFtGGO6GVxVB Ime0liFhSz05C7pdBDz5Ah4xhaE0QsGl1NlmgOlCcfcCcOryo= X-Gm-Gg: AZFdTZd5F5AuyK9ZKF63dwus274L6mD3NoqAGXo/1f06ug9XoxFrH3KX+melpmpC+9a dc141J9oCjXK8MWqv/SUaDLuYHQs+Cc2GKNKZRk3jncuuTfuAjLtWv7aiS3FV6fXz9d4SjgAEPj SZkrFfvbU7iNlC5zq4WCKTvbQvs3X1dd+mvlSzYVh9ZsXZ5HqxIeB7mRSgzEkcloUKoLVU6eCvD tX3rj0KTODPS/UUecjZvWol9Jm+4Syh4Fg0ZjbfRQVUxcRUTWYe1NXC7DSstZ6J7NKIzQC1QOdj PNqjRVVhShXXtd3N3JjbpyQaCzCWaL0mzxLHQUneQH2KN2ncaD58wxVM6ECz28LoyPOOFn6Opr1 1eX9KMcNrvTcCgrk+qhEM4gjRCrWSbtdJMHmmpoCTzo6YtA== X-Received: by 2002:a05:6000:4812:b0:4a6:bc53:247f with SMTP id ffacd0b85a97d-4abb7d45e6cmr6020453f8f.48.1795187585395; Fri, 20 Nov 2026 07:13:05 -0800 (PST) X-Received: by 2002:a05:6000:4812:b0:4a6:bc53:247f with SMTP id ffacd0b85a97d-4abb7d45e6cmr6020373f8f.48.1795187584631; Fri, 20 Nov 2026 07:13:04 -0800 (PST) Received: from localhost ([83.216.138.189]) by smtp.gmail.com with ESMTPSA id ffacd0b85a97d-4ab658e2e6dsm6352211f8f.6.2026.11.20.07.13.03 (version=TLS1_3 cipher=TLS_AES_256_GCM_SHA384 bits=256/256); Fri, 20 Nov 2026 07:13:04 -0800 (PST) From: Andrew Burgess To: gdb-patches@sourceware.org Cc: Andrew Burgess Subject: [PATCH 1/5] gdbserver: avoid buffer overflow from 'm' and 'x' packets Date: Fri, 20 Nov 2026 15:12:46 +0000 Message-ID: <742c0f2f772ecb9365d3411aef9acad9f7e2ef6d.1795186852.git.aburgess@redhat.com> X-Mailer: git-send-email 2.56.1 In-Reply-To: References: MIME-Version: 1.0 X-Mimecast-Spam-Score: 0 X-Mimecast-MFC-PROC-ID: 6paaGDV3LOn-RF7jcMz7kL1nheuCViKmX9VQkdNTBZ0_1795187586 X-Mimecast-Originator: redhat.com Content-Transfer-Encoding: 8bit content-type: text/plain; charset="US-ASCII"; x-default=true X-BeenThere: gdb-patches@sourceware.org X-Mailman-Version: 2.1.30 Precedence: list List-Id: Gdb-patches mailing list List-Unsubscribe: , List-Archive: List-Post: List-Help: List-Subscribe: , Errors-To: gdb-patches-bounces~public-inbox=simark.ca@sourceware.org In the process_serial_event function (gdbserver/server.cc), the 'm' and 'x' packets, which both read inferior memory, take a length from the incoming packet and read that much data into a fixed-size buffer. This read can overflow the buffer. Cap the length to avoid this overflow. For 'm', the length is capped at half the buffer size, as the result of the read is passed through bin2hex, which encodes each byte as two hex characters, doubling the space required for the result. For 'x' the raw binary data is returned, so the full buffer size is available. The binary data reply places a 'b' at the front; however, the outbound result buffer is actually sized to 'PBUFSIZ + 1'. The '+1' in this case allows for the 'b', as a binary data packet does not need a trailing '\0' character. I've added a new test gdb.server/mx-packet-overflow.exp which tests a number of different read request sizes with the 'm' and 'x' packets. --- gdb/doc/gdb.texinfo | 16 ++ gdb/testsuite/gdb.server/mx-packet-overflow.c | 63 ++++++ .../gdb.server/mx-packet-overflow.exp | 179 ++++++++++++++++++ gdbserver/server.cc | 15 ++ 4 files changed, 273 insertions(+) create mode 100644 gdb/testsuite/gdb.server/mx-packet-overflow.c create mode 100644 gdb/testsuite/gdb.server/mx-packet-overflow.exp diff --git a/gdb/doc/gdb.texinfo b/gdb/doc/gdb.texinfo index 7998dfb58c8..69f649f2e68 100644 --- a/gdb/doc/gdb.texinfo +++ b/gdb/doc/gdb.texinfo @@ -43926,6 +43926,13 @@ Packets of the region of memory. @end table +The maximum requestable @var{length} is limited by the maximum +supported packet size, which is currently 131104 bytes. Each byte +read is returned as two hex characters, so any @var{length} over 65552 +will fail because the reply would exceed the current maximum packet +length. The maximum packet length could change in future releases of +@value{GDBN} and should not be relied on. + Unlike most packets, this packet does not support @samp{E.@var{errtext}}-style textual error replies (@pxref{textual error reply}) by default. Stubs should be careful to only send such a @@ -44312,6 +44319,15 @@ Packets for an error @end table +The maximum requestable @var{length} is limited by the maximum +supported packet size, which is currently 131104 bytes. Any read over +this length will return an error. Shorter reads can also fail due to +added escape bytes (@pxref{Binary Data}). Worst case is that every +byte read needs an additional escape byte, which halves the number of +data bytes that can be returned; any read over 65552 bytes might +return an error. The maximum packet length could change in future +releases of @value{GDBN} and should not be relied on. + @item X @var{addr},@var{length}:@var{XX@dots{}} @anchor{X packet} @cindex @samp{X} packet diff --git a/gdb/testsuite/gdb.server/mx-packet-overflow.c b/gdb/testsuite/gdb.server/mx-packet-overflow.c new file mode 100644 index 00000000000..dc3a92d8031 --- /dev/null +++ b/gdb/testsuite/gdb.server/mx-packet-overflow.c @@ -0,0 +1,63 @@ +/* This testcase is part of GDB, the GNU debugger. + + Copyright 2026 Free Software Foundation, Inc. + + This program is free software; you can redistribute it and/or modify + it under the terms of the GNU General Public License as published by + the Free Software Foundation; either version 3 of the License, or + (at your option) any later version. + + This program is distributed in the hope that it will be useful, + but WITHOUT ANY WARRANTY; without even the implied warranty of + MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the + GNU General Public License for more details. + + You should have received a copy of the GNU General Public License + along with this program. If not, see . */ + +#include +#include +#include + +unsigned char *buffer = NULL; +size_t buffer_length = 1024 * 1024 * 100; +volatile int global_var = 0; + +/* Is C a byte that must be escaped in a reply from gdbserver to + GDB? Return 1 if it is, otherwise, return 0. */ +static int +is_escapable_byte (unsigned char c) +{ + switch (c) + { + case 0x23: + case 0x24: + case 0x7d: + case 0x2a: + return 1; + default: + return 0; + } +} + +int +main () +{ + buffer = malloc ( buffer_length ); + assert (buffer != NULL); + + unsigned char val = 0; + for (size_t i = 0; i < buffer_length; ++i) + { + buffer[i] = val; + do + { + val = (val + 1) % UCHAR_MAX; + } + while (is_escapable_byte (val)); + } + + global_var = 42; /* Break here. */ + + return 0; +} diff --git a/gdb/testsuite/gdb.server/mx-packet-overflow.exp b/gdb/testsuite/gdb.server/mx-packet-overflow.exp new file mode 100644 index 00000000000..09cb4a4cb83 --- /dev/null +++ b/gdb/testsuite/gdb.server/mx-packet-overflow.exp @@ -0,0 +1,179 @@ +# This testcase is part of GDB, the GNU debugger. +# +# Copyright 2026 Free Software Foundation, Inc. +# +# This program is free software; you can redistribute it and/or modify +# it under the terms of the GNU General Public License as published by +# the Free Software Foundation; either version 3 of the License, or +# (at your option) any later version. +# +# This program is distributed in the hope that it will be useful, +# but WITHOUT ANY WARRANTY; without even the implied warranty of +# MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the +# GNU General Public License for more details. +# +# You should have received a copy of the GNU General Public License +# along with this program. If not, see . + +# Test that the 'm' and 'x' packets protect against buffer overflow. + +load_lib gdbserver-support.exp + +require allow_gdbserver_tests + +standard_testfile + +save_vars { GDBFLAGS } { + # If GDB and GDBserver are both running locally, set the sysroot to avoid + # reading files via the remote protocol (the `is_remote target` check is + # already done above). + if { ![is_remote host] } { + set GDBFLAGS "$GDBFLAGS -ex \"set sysroot\"" + } + if {[prepare_for_testing "failed to prepare" $testfile $srcfile]} { + return + } +} + +# Make sure we're disconnected, in case we're testing with an +# extended-remote board, therefore already connected. +gdb_test "disconnect" ".*" + +# Start gdbserver and connect. +set res [gdbserver_spawn ""] +set gdbserver_protocol [lindex $res 0] +set gdbserver_gdbport [lindex $res 1] +set res [gdb_target_cmd $gdbserver_protocol $gdbserver_gdbport] +if {![gdb_assert {$res == 0} "connect"]} { + return +} + +# Get into position for the test. +gdb_breakpoint [gdb_get_line_number "/* Break here. */"] +gdb_continue_to_breakpoint "test position" + +# Send PACKET, a full 'm' or 'x' packet, to the server using 'maint +# packet ...'. EXPECTED is one of 'hex', 'binary', or 'error', and +# indicates the type of reply that gdbserver should send. +# +# 'hex' -- the result should be a hex encoded data packet, as +# returned by a successful 'm' packet. +# +# 'binary' -- the result should be a binary encoded data packet, as +# returned by a successful 'x' packet. +# +# 'error' -- the result should be an error packet, the 'm' or 'x' +# packet failed. +# +# TESTNAME is used as the name for this test. +proc send_mx_packet { packet expected testname } { + set result "" + set drain_buffer false + + # Send the initial packet. Detect full error reply here, or the + # start of a hex or binary encoded result. Do not parse the GDB + # prompt pattern here. + gdb_test_multiple "maint packet ${packet}" $testname { + -re "\r\nreceived: \"E01\"" { + set result "error" + } + + -re "\r\nreceived: \"b\[^\r\n\]*" { + set drain_buffer true + set result "binary" + } + + -re "\r\nreceived: \"00\[^\r\n\]*" { + set drain_buffer true + set result "hex" + } + } + + # If the previous gdb_test_multiple found the start of a data + # packet then consume the input now. This avoids having to read + # the entire result into the expect buffer; there could be a lot + # of output. Again, we don't parse the GDB prompt here. + if { $drain_buffer } { + gdb_test_multiple "" "" { + -re "^\[^\r\n\]+" { + exp_continue + } + + -re "^(?=\r\n)" { + } + } + } + + # Finally, consume the GDB prompt. Check that the RESULT matches + # EXPECTED. + gdb_test_multiple "" "" { + -re "\r\n$::gdb_prompt $" { + gdb_assert { $result eq $expected } $testname + } + } + + return $result +} + +# Send 'm' and 'x' packets to gdbserver with various requested +# lengths, check that gdbserver handles the packets as we expect, +# rejecting those that are too long. +proc run_mx_packet_tests {} { + # The size of the buffer allocated within gdbserver. See PBUFSIZ in + # gdbserver/server.h. + set pbufsiz 0x20020 + + # The address of 'buffer' within the inferior, without the leading '0x'. + set addr [get_hexadecimal_valueof buffer 0x0 "get buffer address"] + set addr [string range $addr 2 end] + + # The size of buffer. Leave this as hex with 0x prefix for now. + set buffer_len [get_hexadecimal_valueof buffer_length 0x0 "get buffer length"] + + # If we ask GDB to read the entire buffer from the inferior, GDB will + # perform many 4-byte reads. This does a good job of protecting + # gdbserver from buffer overflows, but it hides the bug that this test + # is trying to expose. + # + # Manually send 'm' or 'x' packets so we can control the contents. + # + # Try different sizes, BUFFER_LEN is huge, far bigger than the + # allocated buffer. PBUFSIZ is the exact size of the buffer within + # gdbserver used to build the result packet. Test various sizes based + # on PBUFSIZ as well as the full BUFFER_LEN. + # + # This test works best when gdbserver is built with the address + # sanitizers, as out-of-bounds writes will trigger the sanitizer. + set test_lengths [list $pbufsiz \ + [expr { $pbufsiz + 1 }] \ + [expr { $pbufsiz / 2 }] \ + [expr { $pbufsiz / 2 + 1 }] \ + $buffer_len] + foreach_with_prefix req_len $test_lengths { + # Make LEN be REQ_LEN in hex, without the '0x' prefix. + set len [string range [format "0x%x" $req_len] 2 end] + + # Set M_RESULT and X_RESULT to 'hex', 'binary', or 'error' + # depending on what the packet result should be. See + # send_mx_packet for more details. + set m_result "hex" + set x_result "binary" + + if { $req_len > $pbufsiz } { + set x_result "error" + } + + if { $req_len > $pbufsiz / 2 } { + set m_result "error" + } + + # Send the packets. + send_mx_packet "m${addr},${len}" $m_result \ + "test 'm' packet, expect $m_result" + send_mx_packet "x${addr},${len}" $x_result \ + "test 'x' packet, expect $x_result" + } +} + +# Run the m/x packet tests. +run_mx_packet_tests diff --git a/gdbserver/server.cc b/gdbserver/server.cc index 74774fcde7c..7ad40e8e2b2 100644 --- a/gdbserver/server.cc +++ b/gdbserver/server.cc @@ -4945,6 +4945,15 @@ process_serial_event (void) { require_running_or_break (cs.own_buf); decode_m_packet (&cs.own_buf[1], &mem_addr, &len); + /* The bin2hex call converts each byte in MEM_BUF into two hex + characters, doubling the number of bytes required. We can + therefore only read half a packet's worth of bytes from the + inferior memory. */ + if (len > PBUFSIZ / 2) + { + write_enn (cs.own_buf); + break; + } int res = gdb_read_memory (mem_addr, mem_buf, len); if (res < 0) write_enn (cs.own_buf); @@ -4964,6 +4973,12 @@ process_serial_event (void) { require_running_or_break (cs.own_buf); decode_x_packet (&cs.own_buf[1], &mem_addr, &len); + /* Ensure we don't overflow MEM_BUF. */ + if (len > PBUFSIZ) + { + write_enn (cs.own_buf); + break; + } int res = gdb_read_memory (mem_addr, mem_buf, len); if (res < 0) write_enn (cs.own_buf); -- 2.56.0