Project

General

Profile

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