1
0
mirror of https://github.com/libssh2/libssh2.git synced 2025-11-21 14:00:51 +03:00

kex.c: kex_agree_instr() improve string reading (#552)

* kex.c: kex_agree_instr() improve string reading

file: kex.c
notes: if haystack isn't null terminated we should use memchr() not strchar(). We should also make sure we don't walk off the end of the buffer.
credit: 
Will Cosgrove, reviewed by Michael Buckley
This commit is contained in:
Will Cosgrove
2021-02-02 10:11:14 -08:00
committed by GitHub
parent c69f1f27dc
commit cde13f6201

View File

@@ -3286,24 +3286,40 @@ kex_agree_instr(unsigned char *haystack, unsigned long haystack_len,
const unsigned char *needle, unsigned long needle_len) const unsigned char *needle, unsigned long needle_len)
{ {
unsigned char *s; unsigned char *s;
unsigned char *end_haystack;
unsigned long left;
/* Haystack too short to bother trying */ if(haystack == NULL || needle == NULL) {
if(haystack_len < needle_len) {
return NULL; return NULL;
} }
/* Haystack too short to bother trying */
if(haystack_len < needle_len || needle_len == 0) {
return NULL;
}
s = haystack;
end_haystack = &haystack[haystack_len];
left = end_haystack - s;
/* Needle at start of haystack */ /* Needle at start of haystack */
if((strncmp((char *) haystack, (char *) needle, needle_len) == 0) && if((strncmp((char *) haystack, (char *) needle, needle_len) == 0) &&
(needle_len == haystack_len || haystack[needle_len] == ',')) { (needle_len == haystack_len || haystack[needle_len] == ',')) {
return haystack; return haystack;
} }
s = haystack;
/* Search until we run out of comas or we run out of haystack, /* Search until we run out of comas or we run out of haystack,
whichever comes first */ whichever comes first */
while((s = (unsigned char *) strchr((char *) s, ',')) while((s = (unsigned char *) memchr((char *) s, ',', left))) {
&& ((haystack_len - (s - haystack)) > needle_len)) { /* Advance buffer past coma if we can */
left = end_haystack - s;
if((left >= 1) && (left <= haystack_len) && (left > needle_len)) {
s++; s++;
}
else {
return NULL;
}
/* Needle at X position */ /* Needle at X position */
if((strncmp((char *) s, (char *) needle, needle_len) == 0) && if((strncmp((char *) s, (char *) needle, needle_len) == 0) &&
(((s - haystack) + needle_len) == haystack_len (((s - haystack) + needle_len) == haystack_len