Project

General

Profile

Download (13.5 KB) Statistics
| Branch: | Tag: | Revision:
1
<?php
2
/*
3
 * diag_command.php
4
 *
5
 * part of pfSense (https://www.pfsense.org)
6
 * Copyright (c) 2004-2013 BSD Perimeter
7
 * Copyright (c) 2013-2016 Electric Sheep Fencing
8
 * Copyright (c) 2014-2019 Rubicon Communications, LLC (Netgate)
9
 * All rights reserved.
10
 *
11
 * 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
 *
15
 * originally based on m0n0wall (http://m0n0.ch/wall)
16
 * Copyright (c) 2003-2004 Manuel Kasper <mk@neon1.net>.
17
 * All rights reserved.
18
 *
19
 * 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
 *
23
 * http://www.apache.org/licenses/LICENSE-2.0
24
 *
25
 * 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
 */
31

    
32
##|+PRIV
33
##|*IDENT=page-diagnostics-command
34
##|*NAME=Diagnostics: Command
35
##|*DESCR=Allow access to the 'Diagnostics: Command' page.
36
##|*WARN=standard-warning-root
37
##|*MATCH=diag_command.php*
38
##|-PRIV
39

    
40
$allowautocomplete = true;
41

    
42
require_once("guiconfig.inc");
43

    
44
if ($_POST['submit'] == "DOWNLOAD" && file_exists($_POST['dlPath'])) {
45
	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
	header("Content-Disposition: attachment; filename=\"" .
50
		trim(htmlentities(basename($_POST['dlPath']))) . "\"");
51
	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

    
59
	fpassthru($fd);
60
	exit;
61
} else if ($_POST['submit'] == "UPLOAD" && is_uploaded_file($_FILES['ulfile']['tmp_name'])) {
62
	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
}
65

    
66
// Function: is Blank
67
// Returns true or false depending on blankness of argument.
68

    
69
function isBlank($arg) {
70
	return preg_match("/^\s*$/", $arg);
71
}
72

    
73
// Function: Puts
74
// Put string, Ruby-style.
75

    
76
function puts($arg) {
77
	echo "$arg\n";
78
}
79

    
80
$pgtitle = array(gettext("Diagnostics"), gettext("Command Prompt"));
81
include("head.inc");
82
?>
83
<script type="text/javascript">
84
//<![CDATA[
85
	// Create recall buffer array (of encoded strings).
86
<?php
87

    
88
if (isBlank($_POST['txtRecallBuffer'])) {
89
	puts("	 var arrRecallBuffer = new Array;");
90
} else {
91
	puts("	 var arrRecallBuffer = new Array(");
92
	$arrBuffer = explode("&", $_POST['txtRecallBuffer']);
93
	for ($i = 0; $i < (count($arrBuffer) - 1); $i++) {
94
		puts("		'" . htmlspecialchars($arrBuffer[$i], ENT_QUOTES | ENT_HTML401) . "',");
95
	}
96
	puts("		'" . htmlspecialchars($arrBuffer[count($arrBuffer) - 1], ENT_QUOTES | ENT_HTML401) . "'");
97
	puts("	 );");
98
}
99
?>
100

    
101
	// Set pointer to end of recall buffer.
102
	var intRecallPtr = arrRecallBuffer.length-1;
103

    
104
	// 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

    
120
		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
			if (isBlank(form.txtRecallBuffer.value)) {
126
				form.txtRecallBuffer.value = form.txtCommand.value.encode();
127
			} else {
128
				form.txtRecallBuffer.value += '&' + form.txtCommand.value.encode();
129
			}
130
		}
131

    
132
		return true;
133
	}
134

    
135
	// Function: btnRecall onClick (event handler)
136
	// Recalls command buffer going either up or down.
137
	function btnRecall_onClick( form, n ) {
138

    
139
		// If nothing in recall buffer, then error.
140
		if (!arrRecallBuffer.length) {
141
			alert('<?=gettext("Nothing to recall"); ?>!');
142
			form.txtCommand.focus();
143
			return;
144
		}
145

    
146
		// Increment recall buffer pointer in positive or negative direction
147
		// according to <n>.
148
		intRecallPtr += n;
149

    
150
		// Make sure the buffer stays circular.
151
		if (intRecallPtr < 0) { intRecallPtr = arrRecallBuffer.length - 1 }
152
		if (intRecallPtr > (arrRecallBuffer.length - 1)) { intRecallPtr = 0 }
153

    
154
		// Recall the command.
155
		form.txtCommand.value = arrRecallBuffer[intRecallPtr].decode();
156
	}
157

    
158
	// Function: Reset onClick (event handler)
159
	// Resets form on reset button click event.
160
	function Reset_onClick( form ) {
161

    
162
		// Reset recall buffer pointer.
163
		intRecallPtr = arrRecallBuffer.length;
164

    
165
		// Clear form (could have spaces in it) and return focus ready for cmd.
166
		form.txtCommand.value = '';
167
		form.txtCommand.focus();
168

    
169
		return true;
170
	}
171
//]]>
172
</script>
173
<?php
174

    
175
if (isBlank($_POST['txtCommand']) && isBlank($_POST['txtPHPCommand']) && isBlank($ulmsg)) {
176
	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
}
178

    
179
if ($_POST['submit'] == "EXEC" && !isBlank($_POST['txtCommand'])):?>
180
	<div class="panel panel-success responsive">
181
		<div class="panel-heading"><h2 class="panel-title"><?=sprintf(gettext('Shell Output - %s'), htmlspecialchars($_POST['txtCommand']))?></h2></div>
182
		<div class="panel-body">
183
			<div class="content">
184
<?php
185
	putenv("PATH=/bin:/sbin:/usr/bin:/usr/sbin:/usr/local/bin:/usr/local/sbin");
186
	putenv("SCRIPT_FILENAME=" . strtok($_POST['txtCommand'], " "));
187
	$output = array();
188
	exec($_POST['txtCommand'] . ' 2>&1', $output);
189

    
190
	$output = implode("\n", $output);
191
	print("<pre>" . htmlspecialchars($output) . "</pre>");
192
?>
193
			</div>
194
		</div>
195
	</div>
196
<?php endif; ?>
197

    
198
<form action="diag_command.php" method="post" enctype="multipart/form-data" name="frmExecPlus" onsubmit="return frmExecPlus_onSubmit( this );">
199
	<div class="panel panel-default">
200
		<div class="panel-heading"><h2 class="panel-title"><?=gettext('Execute Shell Command')?></h2></div>
201
		<div class="panel-body">
202
			<div class="content">
203
				<input id="txtCommand" name="txtCommand" placeholder="Command" type="text" class="col-sm-7"	 value="<?=htmlspecialchars($_POST['txtCommand'])?>" />
204
				<br /><br />
205
				<input type="hidden" name="txtRecallBuffer" value="<?=htmlspecialchars($_POST['txtRecallBuffer']) ?>" />
206

    
207
				<div class="btn-group">
208
					<button type="button" class="btn btn-success btn-sm" name="btnRecallPrev" onclick="btnRecall_onClick( this.form, -1 );" title="<?=gettext("Recall Previous Command")?>">
209
						<i class="fa fa-angle-double-left"></i>
210
					</button>
211
					<button name="submit" type="submit" class="btn btn-warning btn-sm" value="EXEC" title="<?=gettext("Execute the entered command")?>">
212
						<i class="fa fa-bolt"></i>
213
						<?=gettext("Execute"); ?>
214
					</button>
215
					<button type="button" class="btn btn-success btn-sm" name="btnRecallNext" onclick="btnRecall_onClick( this.form,  1 );" title="<?=gettext("Recall Next Command")?>">
216
						<i class="fa fa-angle-double-right"></i>
217
					</button>
218
					<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
						<i class="fa fa-undo"></i>
220
						<?=gettext("Clear"); ?>
221
					</button>
222
				</div>
223
			</div>
224
		</div>
225
	</div>
226

    
227
	<div class="panel panel-default">
228
		<div class="panel-heading"><h2 class="panel-title"><?=gettext('Download File')?></h2></div>
229
		<div class="panel-body">
230
			<div class="content">
231
				<input name="dlPath" type="text" id="dlPath" placeholder="File to download" class="col-sm-4" value="<?=htmlspecialchars($_REQUEST['dlPath']);?>"/>
232
				<br /><br />
233
				<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
			</div>
238
		</div>
239
	</div>
240

    
241
<?php
242
	if ($ulmsg) {
243
		print_info_box($ulmsg, 'success', false);
244
	}
245
?>
246
	<div class="panel panel-default">
247
		<div class="panel-heading"><h2 class="panel-title"><?=gettext('Upload File')?></h2></div>
248
		<div class="panel-body">
249
			<div class="content">
250
				<input name="ulfile" type="file" class="btn btn-default btn-sm btn-file" id="ulfile" />
251
				<br />
252
				<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
			</div>
257
		</div>
258
	</div>
259
<?php
260

    
261
	// 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
	if ($_POST['submit'] == "EXECPHP" && !isBlank($_POST['txtPHPCommand'])) {
264

    
265
		safe_mkdir($g['tmp_path_user_code']);     //create if doesn't exist
266
		$tmpfile = tempnam($g['tmp_path_user_code'], "");
267
		$phpcode = <<<END_FILE
268
<?php
269
require_once("/etc/inc/config.inc");
270
require_once("/etc/inc/functions.inc");
271

    
272
// USER CODE STARTS HERE:
273

    
274
%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
		exec("/usr/local/bin/php -d log_errors=off {$tmpfile}", $output, $retval);
284

    
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
		$errmsg_found = preg_match("`error.*:.* (?:in|File:) {$tmpfile}(?:\(| on line |, Line: )(\d+)(?:, Message:|\).* eval\(\)'d code|$)`i", implode("\n", $output), $matches);
289
		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
			 *   "PHP ERROR: Type: NN, File: FILE, Line: NN, Message: ERR_DETAILS"
294
			 *   "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
			*/
296
			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
			$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
			$margin_layout = '%3s %' . strlen(count($syntax_output)) . 'd:';
310
			for ($lineno = 1; $lineno < count($syntax_output) - $lineno_correction; $lineno++) {
311
				$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
			}
314
			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
		}
319

    
320
		$output = implode("\n", $output);
321
		print("<pre>" . htmlspecialchars($output) . "</pre>");
322

    
323
//		echo eval($_POST['txtPHPCommand']);
324

    
325
		puts("</div>");
326

    
327
		unlink($tmpfile);
328
?>
329
<script type="text/javascript">
330
//<![CDATA[
331
	events.push(function() {
332
		// 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
		// 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
//]]>
339
</script>
340
<?php
341
}
342
?>
343
	<div class="panel panel-default responsive">
344
		<div class="panel-heading"><h2 class="panel-title"><?=gettext('Execute PHP Commands')?></h2></div>
345
		<div class="panel-body">
346
			<div class="content">
347
				<textarea id="txtPHPCommand" placeholder="Command" name="txtPHPCommand" rows="9" cols="80"><?=htmlspecialchars($_POST['txtPHPCommand'])?></textarea>
348
				<br />
349
				<button name="submit" type="submit" class="btn btn-warning btn-sm" value="EXECPHP" title="<?=gettext("Execute this PHP Code")?>">
350
					<i class="fa fa-bolt"></i>
351
					<?=gettext("Execute")?>
352
				</button>
353
				<?=gettext("Example"); ?>: <code>print("Hello World!");</code>
354
			</div>
355
		</div>
356
	</div>
357
</form>
358

    
359
<?php
360
include("foot.inc");
361

    
362
if ($_POST) {
363
}
(11-11/227)