// Work around CVE-2018-6485 and CVE-2018-6551 by imposing a limit
// on the incoming $bytes parameter.  If it's too close to SIZE_MAX,
// pre-CVE code could overflow.  With this band-aid, (a) the size will
// be reduced, to a number beneath the overflow range, but high
// enough that we are confident the subsequent malloc will still fail
// and/or (b) the process is killed

global hitcount
global misscount
global kill_p = 0
global fix_p = 0
global notify_p = 1

probe process("/lib*/libc.so.6").function("_int_malloc"),
      process("/lib*/libc.so.6").function("_int_memalign") {
  MALLOC_ALIGNMENT = 65536; /* over-estimate */
  MINSIZE = 64 + MALLOC_ALIGNMENT; /* way over-estimate */
  MAXSIZE = (probing_32bit_app() ? 4294967295 : 18446744073709551615) - MINSIZE*2;
  /* compare as numbers as if unsigned */
  if ((MAXSIZE > 0 && $bytes > 0 && $bytes > MAXSIZE) || 
      (MAXSIZE < 0 && $bytes < 0 && MAXSIZE < $bytes)) {
    hitcount <<< 1;
    if (notify_p)
      printf("cve-2018-6485 bandaid %s[%d] %d>%d kill?%d fix?%d\n",
	     execname(), tid(),
             $bytes, MAXSIZE,
	     kill_p, fix_p)
    if (kill_p)
      raise (9);
    if (fix_p)
      $bytes = MAXSIZE;
  }
  else
  misscount <<< 1;
}


probe timer.s(60) if (notify_p) {
  printf("cve-2018-6485 bandaid miss#%d hit#%d kill?%d fix?%d\n",
	 @count(misscount), @count(hitcount), kill_p, fix_p)
}
