nats-io / nats.c

A C client for NATS
Apache License 2.0
382 stars 132 forks source link

[FIXED] Fix heap buffer overflow in _fetch #749

Closed tyler92 closed 3 months ago

tyler92 commented 4 months ago

The req->Batch is changing inside the _fetch routine which led to an incorrect loop condition while (... && count != req.Batch && ...) and as a result heap buffer overflow in the expression msgs[count++] = msg; at line 1921.

Address sanitizer report:

==4065175==ERROR: AddressSanitizer: heap-buffer-overflow on address 0x51500002bc00 at pc 0x555555c073c5 bp 0x7fffe6a60c00 sp 0x7fffe6a60bf8
WRITE of size 8 at 0x51500002bc00 thread T1070
    #0 0x555555c073c4 in _fetch /src/nats.c-3.8.0/src/js.c:1953:31
    #1 0x555555c07a95 in natsSubscription_Fetch /src/nats.c-3.8.0/src/js.c:2028:9
    ...

0x51500002bc00 is located 0 bytes after 512-byte region [0x51500002ba00,0x51500002bc00)
allocated by thread T1070 here:
    #0 0x5555556e2ae8 in calloc (/src/nats_test+0x18eae8) (BuildId: c1afc37aee3e3a5c3fe6972fa3bd8b45c242e287)
    #1 0x555555c0645d in _fetch /src/nats.c-3.8.0/src/js.c:1834:24
    #2 0x555555c07a95 in natsSubscription_Fetch /src/nats.c-3.8.0/src/js.c:2028:9
    ...

Shadow bytes around the buggy address:
  0x51500002b980: fa fa fa fa fa fa fa fa fa fa fa fa fa fa fa fa
  0x51500002ba00: 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00
  0x51500002ba80: 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00
  0x51500002bb00: 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00
  0x51500002bb80: 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00
=>0x51500002bc00:[fa]fa fa fa fa fa fa fa fa fa fa fa fa fa fa fa
  0x51500002bc80: fa fa fa fa fa fa fa fa fa fa fa fa fa fa fa fa
  0x51500002bd00: fa fa fa fa fa fa fa fa fa fa fa fa fa fa fa fa
  0x51500002bd80: fa fa fa fa fa fa fa fa fa fa fa fa fa fa fa fa
  0x51500002be00: fa fa fa fa fa fa fa fa fa fa fa fa fa fa fa fa
  0x51500002be80: fa fa fa fa fa fa fa fa fa fa fa fa fa fa fa fa
Shadow byte legend (one shadow byte represents 8 application bytes):
  Addressable:           00
  Partially addressable: 01 02 03 04 05 06 07 
  Heap left redzone:       fa
  Freed heap region:       fd
  Stack left redzone:      f1
  Stack mid redzone:       f2
  Stack right redzone:     f3
  Stack after return:      f5
  Stack use after scope:   f8
  Global redzone:          f9
  Global init order:       f6
  Poisoned by user:        f7
  Container overflow:      fc
  Array cookie:            ac
  Intra object redzone:    bb
  ASan internal:           fe
  Left alloca redzone:     ca
  Right alloca redzone:    cb
==4065175==ABORTING
kozlovic commented 3 months ago

@levb I reviewed and I think the changes are good. Let me know if you want to merge or want me to.