Project

General

Profile

Download (13.4 KB) Statistics
| Branch: | Tag: | Revision:
1 91bf75df Scott Ullrich
<?php
2 2900e518 Scott Ullrich
/*
3 c5d81585 Renato Botelho
 * diag_command.php
4 cb41dd63 Renato Botelho
 *
5 c5d81585 Renato Botelho
 * part of pfSense (https://www.pfsense.org)
6 81299b5c Renato Botelho
 * Copyright (c) 2004-2016 Rubicon Communications, LLC (Netgate)
7 c5d81585 Renato Botelho
 * All rights reserved.
8 fd9ebcd5 Stephen Beaver
 *
9 c5d81585 Renato Botelho
 * Exec+ v1.02-000 - Copyright 2001-2003, All rights reserved
10
 * Created by technologEase (http://www.technologEase.com)
11
 * (modified for m0n0wall by Manuel Kasper <mk@neon1.net>)\
12 9da2cf1c Stephen Beaver
 *
13 c5d81585 Renato Botelho
 * originally based on m0n0wall (http://m0n0.ch/wall)
14
 * Copyright (c) 2003-2004 Manuel Kasper <mk@neon1.net>.
15
 * All rights reserved.
16 fd9ebcd5 Stephen Beaver
 *
17 b12ea3fb Renato Botelho
 * Licensed under the Apache License, Version 2.0 (the "License");
18
 * you may not use this file except in compliance with the License.
19
 * You may obtain a copy of the License at
20 fd9ebcd5 Stephen Beaver
 *
21 b12ea3fb Renato Botelho
 * http://www.apache.org/licenses/LICENSE-2.0
22 fd9ebcd5 Stephen Beaver
 *
23 b12ea3fb Renato Botelho
 * Unless required by applicable law or agreed to in writing, software
24
 * distributed under the License is distributed on an "AS IS" BASIS,
25
 * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
26
 * See the License for the specific language governing permissions and
27
 * limitations under the License.
28 fd9ebcd5 Stephen Beaver
 */
29 2900e518 Scott Ullrich
30 6b07c15a Matthew Grooms
##|+PRIV
31
##|*IDENT=page-diagnostics-command
32 5230f468 jim-p
##|*NAME=Diagnostics: Command
33 6b07c15a Matthew Grooms
##|*DESCR=Allow access to the 'Diagnostics: Command' page.
34 57188e47 Phil Davis
##|*WARN=standard-warning-root
35 36a844df Stephen Beaver
##|*MATCH=diag_command.php*
36 6b07c15a Matthew Grooms
##|-PRIV
37
38 7c9a30c8 jim-p
$allowautocomplete = true;
39
40 c81ef6e2 Phil Davis
require_once("guiconfig.inc");
41 458e0e0b Scott Ullrich
42 59255714 NewEraCracker
if ($_POST['submit'] == "DOWNLOAD" && file_exists($_POST['dlPath'])) {
43 5b237745 Scott Ullrich
	session_cache_limiter('public');
44
	$fd = fopen($_POST['dlPath'], "rb");
45
	header("Content-Type: application/octet-stream");
46
	header("Content-Length: " . filesize($_POST['dlPath']));
47 be4b8e72 Scott Ullrich
	header("Content-Disposition: attachment; filename=\"" .
48 5b237745 Scott Ullrich
		trim(htmlentities(basename($_POST['dlPath']))) . "\"");
49 2d181b70 jim-p
	if (isset($_SERVER['HTTPS'])) {
50
		header('Pragma: ');
51
		header('Cache-Control: ');
52
	} else {
53
		header("Pragma: private");
54
		header("Cache-Control: private, must-revalidate");
55
	}
56 be4b8e72 Scott Ullrich
57 5b237745 Scott Ullrich
	fpassthru($fd);
58
	exit;
59 59255714 NewEraCracker
} else if ($_POST['submit'] == "UPLOAD" && is_uploaded_file($_FILES['ulfile']['tmp_name'])) {
60 5db70796 Phil Davis
	move_uploaded_file($_FILES['ulfile']['tmp_name'], $g["tmp_path"] . "/" . $_FILES['ulfile']['name']);
61
	$ulmsg = sprintf(gettext('Uploaded file to %s.'), $g["tmp_path"] . "/" . htmlentities($_FILES['ulfile']['name']));
62 5b237745 Scott Ullrich
}
63 2900e518 Scott Ullrich
64 5b237745 Scott Ullrich
// Function: is Blank
65
// Returns true or false depending on blankness of argument.
66
67 41b1ff89 Phil Davis
function isBlank($arg) {
68 6c07db48 Phil Davis
	return preg_match("/^\s*$/", $arg);
69 41b1ff89 Phil Davis
}
70 5b237745 Scott Ullrich
71
// Function: Puts
72
// Put string, Ruby-style.
73
74 41b1ff89 Phil Davis
function puts($arg) {
75
	echo "$arg\n";
76
}
77 5b237745 Scott Ullrich
78 a6a6ee00 k-paulius
$pgtitle = array(gettext("Diagnostics"), gettext("Command Prompt"));
79 998abf60 Bill Marquette
include("head.inc");
80 5b237745 Scott Ullrich
?>
81 8fd9052f Colin Fleming
<script type="text/javascript">
82
//<![CDATA[
83 45d6ada5 Sjon Hortensius
	// Create recall buffer array (of encoded strings).
84 5b237745 Scott Ullrich
<?php
85
86 6c07db48 Phil Davis
if (isBlank($_POST['txtRecallBuffer'])) {
87 6aef15f8 Stephen Beaver
	puts("	 var arrRecallBuffer = new Array;");
88 5b237745 Scott Ullrich
} else {
89 6aef15f8 Stephen Beaver
	puts("	 var arrRecallBuffer = new Array(");
90 6c07db48 Phil Davis
	$arrBuffer = explode("&", $_POST['txtRecallBuffer']);
91
	for ($i = 0; $i < (count($arrBuffer) - 1); $i++) {
92 6aef15f8 Stephen Beaver
		puts("		'" . htmlspecialchars($arrBuffer[$i], ENT_QUOTES | ENT_HTML401) . "',");
93 41b1ff89 Phil Davis
	}
94 6aef15f8 Stephen Beaver
	puts("		'" . htmlspecialchars($arrBuffer[count($arrBuffer) - 1], ENT_QUOTES | ENT_HTML401) . "'");
95
	puts("	 );");
96 5b237745 Scott Ullrich
}
97
?>
98 45d6ada5 Sjon Hortensius
99 41b1ff89 Phil Davis
	// Set pointer to end of recall buffer.
100
	var intRecallPtr = arrRecallBuffer.length-1;
101 5b237745 Scott Ullrich
102 45d6ada5 Sjon Hortensius
	// Functions to extend String class.
103
	function str_encode() { return escape( this ) }
104
	function str_decode() { return unescape( this ) }
105
106
	// Extend string class to include encode() and decode() functions.
107
	String.prototype.encode = str_encode
108
	String.prototype.decode = str_decode
109
110
	// Function: is Blank
111
	// Returns boolean true or false if argument is blank.
112
	function isBlank( strArg ) { return strArg.match( /^\s*$/ ) }
113
114
	// Function: frmExecPlus onSubmit (event handler)
115
	// Builds the recall buffer from the command string on submit.
116
	function frmExecPlus_onSubmit( form ) {
117 5b237745 Scott Ullrich
118 45d6ada5 Sjon Hortensius
		if (!isBlank(form.txtCommand.value)) {
119
			// If this command is repeat of last command, then do not store command.
120
			if (form.txtCommand.value.encode() == arrRecallBuffer[arrRecallBuffer.length-1]) { return true }
121
122
			// Stuff encoded command string into the recall buffer.
123 41b1ff89 Phil Davis
			if (isBlank(form.txtRecallBuffer.value)) {
124 45d6ada5 Sjon Hortensius
				form.txtRecallBuffer.value = form.txtCommand.value.encode();
125 41b1ff89 Phil Davis
			} else {
126 45d6ada5 Sjon Hortensius
				form.txtRecallBuffer.value += '&' + form.txtCommand.value.encode();
127 41b1ff89 Phil Davis
			}
128 45d6ada5 Sjon Hortensius
		}
129
130
		return true;
131
	}
132 5b237745 Scott Ullrich
133 45d6ada5 Sjon Hortensius
	// Function: btnRecall onClick (event handler)
134
	// Recalls command buffer going either up or down.
135
	function btnRecall_onClick( form, n ) {
136 5b237745 Scott Ullrich
137 45d6ada5 Sjon Hortensius
		// If nothing in recall buffer, then error.
138
		if (!arrRecallBuffer.length) {
139 6c07db48 Phil Davis
			alert('<?=gettext("Nothing to recall"); ?>!');
140 45d6ada5 Sjon Hortensius
			form.txtCommand.focus();
141
			return;
142
		}
143 5b237745 Scott Ullrich
144 45d6ada5 Sjon Hortensius
		// Increment recall buffer pointer in positive or negative direction
145
		// according to <n>.
146
		intRecallPtr += n;
147 5b237745 Scott Ullrich
148 45d6ada5 Sjon Hortensius
		// Make sure the buffer stays circular.
149
		if (intRecallPtr < 0) { intRecallPtr = arrRecallBuffer.length - 1 }
150
		if (intRecallPtr > (arrRecallBuffer.length - 1)) { intRecallPtr = 0 }
151 5b237745 Scott Ullrich
152 45d6ada5 Sjon Hortensius
		// Recall the command.
153
		form.txtCommand.value = arrRecallBuffer[intRecallPtr].decode();
154
	}
155 5b237745 Scott Ullrich
156 45d6ada5 Sjon Hortensius
	// Function: Reset onClick (event handler)
157
	// Resets form on reset button click event.
158
	function Reset_onClick( form ) {
159 5b237745 Scott Ullrich
160 45d6ada5 Sjon Hortensius
		// Reset recall buffer pointer.
161
		intRecallPtr = arrRecallBuffer.length;
162 5b237745 Scott Ullrich
163 45d6ada5 Sjon Hortensius
		// Clear form (could have spaces in it) and return focus ready for cmd.
164
		form.txtCommand.value = '';
165
		form.txtCommand.focus();
166 5b237745 Scott Ullrich
167 45d6ada5 Sjon Hortensius
		return true;
168
	}
169 fa7855f3 Colin Fleming
//]]>
170 5b237745 Scott Ullrich
</script>
171 45d6ada5 Sjon Hortensius
<?php
172 5b237745 Scott Ullrich
173 947141fd Phil Davis
if (isBlank($_POST['txtCommand']) && isBlank($_POST['txtPHPCommand']) && isBlank($ulmsg)) {
174 7457ba51 k-paulius
	print_callout(gettext("The capabilities offered here can be dangerous. No support is available. Use them at your own risk!"), 'danger', gettext('Advanced Users Only'));
175 947141fd Phil Davis
}
176 5b237745 Scott Ullrich
177 59255714 NewEraCracker
if ($_POST['submit'] == "EXEC" && !isBlank($_POST['txtCommand'])):?>
178 45d6ada5 Sjon Hortensius
	<div class="panel panel-success responsive">
179 b7edfd3c Phil Davis
		<div class="panel-heading"><h2 class="panel-title"><?=sprintf(gettext('Shell Output - %s'), htmlspecialchars($_POST['txtCommand']))?></h2></div>
180 45d6ada5 Sjon Hortensius
		<div class="panel-body">
181 7b91ab09 Jared Dillard
			<div class="content">
182 5b237745 Scott Ullrich
<?php
183 45d6ada5 Sjon Hortensius
	putenv("PATH=/bin:/sbin:/usr/bin:/usr/sbin:/usr/local/bin:/usr/local/sbin");
184
	putenv("SCRIPT_FILENAME=" . strtok($_POST['txtCommand'], " "));
185 6aef15f8 Stephen Beaver
	$output = array();
186
	exec($_POST['txtCommand'] . ' 2>&1', $output);
187 5eb9f6ad NewEraCracker
188
	$output = implode("\n", $output);
189
	print("<pre>" . htmlspecialchars($output) . "</pre>");
190 7b91ab09 Jared Dillard
?>
191
			</div>
192 45d6ada5 Sjon Hortensius
		</div>
193
	</div>
194 fa172bc5 NewEraCracker
<?php endif; ?>
195 5b237745 Scott Ullrich
196 36a844df Stephen Beaver
<form action="diag_command.php" method="post" enctype="multipart/form-data" name="frmExecPlus" onsubmit="return frmExecPlus_onSubmit( this );">
197 45d6ada5 Sjon Hortensius
	<div class="panel panel-default">
198 f17594c7 Sjon Hortensius
		<div class="panel-heading"><h2 class="panel-title"><?=gettext('Execute Shell Command')?></h2></div>
199 45d6ada5 Sjon Hortensius
		<div class="panel-body">
200 7b91ab09 Jared Dillard
			<div class="content">
201 37676f4e jim-p
				<input id="txtCommand" name="txtCommand" placeholder="Command" type="text" class="col-sm-7"	 value="<?=htmlspecialchars($_POST['txtCommand'])?>" />
202 7b91ab09 Jared Dillard
				<br /><br />
203
				<input type="hidden" name="txtRecallBuffer" value="<?=htmlspecialchars($_POST['txtRecallBuffer']) ?>" />
204 37676f4e jim-p
205
				<div class="btn-group">
206 b8ce3e91 jim-p
					<button type="button" class="btn btn-success btn-sm" name="btnRecallPrev" onclick="btnRecall_onClick( this.form, -1 );" title="<?=gettext("Recall Previous Command")?>">
207 37676f4e jim-p
						<i class="fa fa-angle-double-left"></i>
208
					</button>
209 59255714 NewEraCracker
					<button name="submit" type="submit" class="btn btn-warning btn-sm" value="EXEC" title="<?=gettext("Execute the entered command")?>">
210 df2aa83e Stephen Beaver
						<i class="fa fa-bolt"></i>
211 37676f4e jim-p
						<?=gettext("Execute"); ?>
212
					</button>
213 b8ce3e91 jim-p
					<button type="button" class="btn btn-success btn-sm" name="btnRecallNext" onclick="btnRecall_onClick( this.form,  1 );" title="<?=gettext("Recall Next Command")?>">
214 37676f4e jim-p
						<i class="fa fa-angle-double-right"></i>
215 6fe069a4 jim-p
					</button>
216 417ace68 Jared Dillard
					<button style="margin-left: 10px;" type="button" class="btn btn-default btn-sm" onclick="return Reset_onClick( this.form );" title="<?=gettext("Clear command entry")?>">
217 37676f4e jim-p
						<i class="fa fa-undo"></i>
218
						<?=gettext("Clear"); ?>
219
					</button>
220
				</div>
221 7b91ab09 Jared Dillard
			</div>
222 45d6ada5 Sjon Hortensius
		</div>
223
	</div>
224
225
	<div class="panel panel-default">
226 3d7a8696 k-paulius
		<div class="panel-heading"><h2 class="panel-title"><?=gettext('Download File')?></h2></div>
227 45d6ada5 Sjon Hortensius
		<div class="panel-body">
228 7b91ab09 Jared Dillard
			<div class="content">
229 7f4268b6 Steve Beaver
				<input name="dlPath" type="text" id="dlPath" placeholder="File to download" class="col-sm-4" value="<?=htmlspecialchars($_REQUEST['dlPath']);?>"/>
230 7b91ab09 Jared Dillard
				<br /><br />
231 37676f4e jim-p
				<button name="submit" type="submit" class="btn btn-primary btn-sm" id="download" value="DOWNLOAD">
232
					<i class="fa fa-download icon-embed-btn"></i>
233
					<?=gettext("Download")?>
234
				</button>
235 7b91ab09 Jared Dillard
			</div>
236 45d6ada5 Sjon Hortensius
		</div>
237
	</div>
238 fbcf0037 Scott Ullrich
239 45d6ada5 Sjon Hortensius
<?php
240 947141fd Phil Davis
	if ($ulmsg) {
241 7c945f74 k-paulius
		print_info_box($ulmsg, 'success', false);
242 947141fd Phil Davis
	}
243 45d6ada5 Sjon Hortensius
?>
244
	<div class="panel panel-default">
245 3d7a8696 k-paulius
		<div class="panel-heading"><h2 class="panel-title"><?=gettext('Upload File')?></h2></div>
246 45d6ada5 Sjon Hortensius
		<div class="panel-body">
247 7b91ab09 Jared Dillard
			<div class="content">
248
				<input name="ulfile" type="file" class="btn btn-default btn-sm btn-file" id="ulfile" />
249
				<br />
250 37676f4e jim-p
				<button name="submit" type="submit" class="btn btn-primary btn-sm" id="upload" value="UPLOAD">
251
					<i class="fa fa-upload icon-embed-btn"></i>
252
					<?=gettext("Upload")?>
253
				</button>
254 7b91ab09 Jared Dillard
			</div>
255 45d6ada5 Sjon Hortensius
		</div>
256
	</div>
257
<?php
258 fd1bd705 stilez
	
259 f5ba2db3 Stephen Beaver
	// Experimental version. Writes the user's php code to a file and executes it via a new instance of PHP
260
	// This is intended to prevent bad code from breaking the GUI
261 59255714 NewEraCracker
	if ($_POST['submit'] == "EXECPHP" && !isBlank($_POST['txtPHPCommand'])) {
262 5eb9f6ad NewEraCracker
263 1155cd63 stilez
		safe_mkdir($g[tmp_path_user_code]);     //create if doesn't exist
264
		$tmpfile = tempnam($g[tmp_path_user_code], "");
265 fd1bd705 stilez
		$phpcode = <<<END_FILE
266
<?php
267
require_once("/etc/inc/config.inc");
268
require_once("/etc/inc/functions.inc");
269 3e115dbf Stephen Beaver
270 fd1bd705 stilez
// USER CODE STARTS HERE:
271 3e115dbf Stephen Beaver
272 fd1bd705 stilez
%s
273
?>
274
END_FILE;
275
		$lineno_correction = 6;  // line numbering correction, this should be the number of lines added above, BEFORE the user's code
276
277
		file_put_contents($tmpfile, sprintf($phpcode, $_POST['txtPHPCommand']));
278
279
		$output = $matches = array();
280
		$retval = 0;
281 4711322b stilez
		exec("/usr/local/bin/php -d log_errors=off {$tmpfile}", $output, $retval);
282 fd1bd705 stilez
283
		puts('<div class="panel panel-success responsive"><div class="panel-heading"><h2 class="panel-title">PHP Response</h2></div>');
284
285
		// Help user to find bad code line, if it gave an error
286 1155cd63 stilez
		$errmsg_found = preg_match("`error.*:.* (?:in|File:) {$tmpfile}(?:\(| on line |, Line: )(\d+)(?:, Message:|\).* eval\(\)'d code|$)`i", implode("\n", $output), $matches);
287 fd1bd705 stilez
		if ($retval || $errmsg_found) {
288
			/* Trap failed code - test both retval and output message
289
			 * Typical messages as at 2.3.x:
290
			 *   "Parse error: syntax error, ERR_DETAILS in FILE on line NN"
291
			 *   "PHP ERROR: Type: NN, File: FILE, Line: NN, Message: ERR_DETAILS" 
292 1155cd63 stilez
			 *   "Parse error: syntax error, unexpected end of file in FILE(NN) : eval()'d code on line 1" [the number in (..) is the error line]
293 fd1bd705 stilez
			*/
294 1155cd63 stilez
			if ($matches[1] > $lineno_correction) {
295
				$errline = $matches[1] - $lineno_correction;
296
				$errtext = sprintf(gettext('Line %s appears to have generated an error, and has been highlighted. The full response is below.'), $errline);
297
			} else {
298
				$errline = -1;
299
				$errtext = gettext('The code appears to have generated an error, but the line responsible cannot be identified. The full response is below.');
300
			}
301
			$errtext .= '<br/>' . sprintf(gettext('Note that the line number in the full PHP response will be %s lines too large. Nested code and eval() errors may incorrectly point to "line 1".'), $lineno_correction);
302 fd1bd705 stilez
			$syntax_output = array();
303
			$html = "";
304
			exec("/usr/local/bin/php -s -d log_errors=off {$tmpfile}", $syntax_output);
305
			// Lines 0, 2 and 3 are CSS wrapper for the syntax highlighted code which is at line 1 <br> separated.
306
			$syntax_output = explode("<br />", $syntax_output[1]);
307 1155cd63 stilez
			$margin_layout = '%3s %' . strlen(count($syntax_output)) . 'd:';
308 fd1bd705 stilez
			for ($lineno = 1; $lineno < count($syntax_output) - $lineno_correction; $lineno++) {
309 1155cd63 stilez
				$margin = str_replace(' ', '&nbsp;', sprintf($margin_layout, ($lineno == $errline ? '&gt;&gt;&gt;' : ''), $lineno));
310
				$html .= "<span style='color:black;backgroundcolor:lightgrey'><tt>{$margin}</tt></span>&nbsp;&nbsp;{$syntax_output[$lineno + $lineno_correction - 1]}<br/>\n";
311 fd1bd705 stilez
			}
312 1155cd63 stilez
			print_info_box($errtext, 'danger');
313
			print "<div style='margin:20px'><b>" . gettext("Error locator:") . "</b>\n";
314
			print "<div id='errdiv' style='height:7em; width:60%; overflow:auto; white-space: nowrap; border:darkgrey solid 1px; margin-top: 20px'>\n";
315
			print $html . "\n</div></div>\n";
316 fd1bd705 stilez
		}
317 3e115dbf Stephen Beaver
318 5eb9f6ad NewEraCracker
		$output = implode("\n", $output);
319
		print("<pre>" . htmlspecialchars($output) . "</pre>");
320
321 3e115dbf Stephen Beaver
//		echo eval($_POST['txtPHPCommand']);
322 fd1bd705 stilez
323 45d6ada5 Sjon Hortensius
		puts("</div>");
324 fd1bd705 stilez
325
		unlink($tmpfile);
326 bd8eeef9 Stephen Beaver
?>
327 8fd9052f Colin Fleming
<script type="text/javascript">
328
//<![CDATA[
329 947141fd Phil Davis
	events.push(function() {
330 fd1bd705 stilez
		// scroll error locator if needed (does nothing if no error)
331
		$('#errdiv').scrollTop(<?=max($errline - ($lineno_correction - 3.5), 0);?> * parseFloat($('#errdiv').css('line-height')));
332
333 bd8eeef9 Stephen Beaver
		// Scroll to the bottom of the page to more easily see the results of a PHP exec command
334
		$("html, body").animate({ scrollTop: $(document).height() }, 1000);
335
	});
336 8fd9052f Colin Fleming
//]]>
337 bd8eeef9 Stephen Beaver
</script>
338
<?php
339 fbcf0037 Scott Ullrich
}
340 5b237745 Scott Ullrich
?>
341 45d6ada5 Sjon Hortensius
	<div class="panel panel-default responsive">
342 f17594c7 Sjon Hortensius
		<div class="panel-heading"><h2 class="panel-title"><?=gettext('Execute PHP Commands')?></h2></div>
343 45d6ada5 Sjon Hortensius
		<div class="panel-body">
344 7b91ab09 Jared Dillard
			<div class="content">
345
				<textarea id="txtPHPCommand" placeholder="Command" name="txtPHPCommand" rows="9" cols="80"><?=htmlspecialchars($_POST['txtPHPCommand'])?></textarea>
346
				<br />
347 59255714 NewEraCracker
				<button name="submit" type="submit" class="btn btn-warning btn-sm" value="EXECPHP" title="<?=gettext("Execute this PHP Code")?>">
348 df2aa83e Stephen Beaver
					<i class="fa fa-bolt"></i>
349 37676f4e jim-p
					<?=gettext("Execute")?>
350
				</button>
351 7b91ab09 Jared Dillard
				<?=gettext("Example"); ?>: <code>print("Hello World!");</code>
352
			</div>
353 45d6ada5 Sjon Hortensius
		</div>
354
	</div>
355 fa7855f3 Colin Fleming
</form>
356 74285e13 Scott Ullrich
357
<?php
358 45d6ada5 Sjon Hortensius
include("foot.inc");
359 74285e13 Scott Ullrich
360 947141fd Phil Davis
if ($_POST) {
361
}