From ed418551cdb76a72c1323fd32cb3ef6f58e697d5 Mon Sep 17 00:00:00 2001
From: Peter Wu
Date: Mon, 21 Jul 2014 11:09:21 +0200
Subject: Better x and y validation, report 400 on errors

Report 400 Bad Request on query errors instead of reporting 200 OK
(which can be cached).

Add some additional validation for the 'x' and 'y' parameters, to catch
underflow (test with `x=-10` for example). Also fix a typo in the error
message and include more details (the actual error).
---
 graph.php             | 22 +++++++++++++++-------
 inc/functions.inc.php |  2 +-
 2 files changed, 16 insertions(+), 8 deletions(-)

diff --git a/graph.php b/graph.php
index 3e33b92..2d62d92 100644
--- a/graph.php
+++ b/graph.php
@@ -6,16 +6,24 @@ require_once 'inc/collectd.inc.php';
 
 $plugin = validate_get(GET('p'), 'plugin');
 $type = validate_get(GET('t'), 'type');
-$width = empty($_GET['x']) ? $CONFIG['width'] : $_GET['x'];
-$height = empty($_GET['y']) ? $CONFIG['height'] : $_GET['y'];
-
-if (validate_get(GET('h'), 'host') === NULL) {
-	error_log('CGP Error: plugin contains unknown characters');
+$width = GET('x') ? filter_input(INPUT_GET, 'x', FILTER_VALIDATE_INT, array(
+	'min_range' => 10,
+	'max_range' => $CONFIG['max-width']
+)) : $CONFIG['width'];
+$height = GET('y') ? filter_input(INPUT_GET, 'y', FILTER_VALIDATE_INT, array(
+	'min_range' => 10,
+	'max_range' => $CONFIG['max-height']
+)) : $CONFIG['height'];
+
+if ($width === NULL || $height === NULL) {
+	error_log(sprintf('Invalid image dimension, x="%s", y="%s"',
+		urlencode(GET('x')),
+		urlencode(GET('y'))));
 	error_image();
 }
 
-if ($width > $CONFIG['max-width'] || $height > $CONFIG['max-height']) {
-	error_log('Resquested image is too large. Please configure max-width and max-height.');
+if (validate_get(GET('h'), 'host') === NULL) {
+	error_log('Invalid host: "' . urlencode(GET('h')) . '"');
 	error_image();
 }
 
diff --git a/inc/functions.inc.php b/inc/functions.inc.php
index c32b3ef..3664d78 100644
--- a/inc/functions.inc.php
+++ b/inc/functions.inc.php
@@ -55,7 +55,7 @@ function crc32hex($str) {
 }
 
 function error_image() {
-	header("Content-Type: image/png");
+	header("Content-Type: image/png", true, 400);
 	readfile('layout/error.png');
 	exit;
 }
-- 
cgit v1.1