mirror of
				https://review.coreboot.org/flashrom.git
				synced 2025-11-04 07:00:39 +01:00 
			
		
		
		
	helpers.c: Fix undefined behavior in strndup()
Using strlen() or strdup() inside strndup() is problematic: if the input string is not null-terminated, these functions can read past the end of the buffer, which triggers undefined behavior. Rewrite the function to never read past the provided `maxlen` bound. Change-Id: Id34127024085879228626fbad59af03268ec5255 Signed-off-by: Xiang Wang <merle@hardenedliux.org> Reviewed-on: https://review.coreboot.org/c/flashrom/+/49741 Reviewed-by: Angel Pons <th3fanbus@gmail.com> Reviewed-by: Edward O'Callaghan <quasisec@chromium.org> Tested-by: build bot (Jenkins) <no-reply@coreboot.org> Reviewed-on: https://review.coreboot.org/c/flashrom/+/67870 Reviewed-by: Felix Singer <felixsinger@posteo.net>
This commit is contained in:
		
							
								
								
									
										17
									
								
								helpers.c
									
									
									
									
									
								
							
							
						
						
									
										17
									
								
								helpers.c
									
									
									
									
									
								
							@@ -106,15 +106,16 @@ char* strtok_r(char *str, const char *delim, char **nextp)
 | 
				
			|||||||
/* strndup is a POSIX function not present in MinGW */
 | 
					/* strndup is a POSIX function not present in MinGW */
 | 
				
			||||||
char *strndup(const char *src, size_t maxlen)
 | 
					char *strndup(const char *src, size_t maxlen)
 | 
				
			||||||
{
 | 
					{
 | 
				
			||||||
	if (strlen(src) > maxlen) {
 | 
						char *retbuf;
 | 
				
			||||||
		char *retbuf;
 | 
						size_t len;
 | 
				
			||||||
		if ((retbuf = malloc(1 + maxlen)) != NULL) {
 | 
						for (len = 0; len < maxlen; len++)
 | 
				
			||||||
			memcpy(retbuf, src, maxlen);
 | 
							if (src[len] == '\0')
 | 
				
			||||||
			retbuf[maxlen] = '\0';
 | 
								break;
 | 
				
			||||||
		}
 | 
						if ((retbuf = malloc(1 + len)) != NULL) {
 | 
				
			||||||
		return retbuf;
 | 
							memcpy(retbuf, src, len);
 | 
				
			||||||
 | 
							retbuf[len] = '\0';
 | 
				
			||||||
	}
 | 
						}
 | 
				
			||||||
	return strdup(src);
 | 
						return retbuf;
 | 
				
			||||||
}
 | 
					}
 | 
				
			||||||
#endif
 | 
					#endif
 | 
				
			||||||
 | 
					
 | 
				
			||||||
 
 | 
				
			|||||||
		Reference in New Issue
	
	Block a user