Project

General

Profile

Download (15.1 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-2016 Rubicon Communications, LLC (Netgate)
7
 * All rights reserved.
8
 *
9
 * 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
 *
13
 * originally based on m0n0wall (http://m0n0.ch/wall)
14
 * Copyright (c) 2003-2004 Manuel Kasper <mk@neon1.net>.
15
 * All rights reserved.
16
 *
17
 * Redistribution and use in source and binary forms, with or without
18
 * modification, are permitted provided that the following conditions are met:
19
 *
20
 * 1. Redistributions of source code must retain the above copyright notice,
21
 *    this list of conditions and the following disclaimer.
22
 *
23
 * 2. Redistributions in binary form must reproduce the above copyright
24
 *    notice, this list of conditions and the following disclaimer in
25
 *    the documentation and/or other materials provided with the
26
 *    distribution.
27
 *
28
 * 3. All advertising materials mentioning features or use of this software
29
 *    must display the following acknowledgment:
30
 *    "This product includes software developed by the pfSense Project
31
 *    for use in the pfSense® software distribution. (http://www.pfsense.org/).
32
 *
33
 * 4. The names "pfSense" and "pfSense Project" must not be used to
34
 *    endorse or promote products derived from this software without
35
 *    prior written permission. For written permission, please contact
36
 *    coreteam@pfsense.org.
37
 *
38
 * 5. Products derived from this software may not be called "pfSense"
39
 *    nor may "pfSense" appear in their names without prior written
40
 *    permission of the Electric Sheep Fencing, LLC.
41
 *
42
 * 6. Redistributions of any form whatsoever must retain the following
43
 *    acknowledgment:
44
 *
45
 * "This product includes software developed by the pfSense Project
46
 * for use in the pfSense software distribution (http://www.pfsense.org/).
47
 *
48
 * THIS SOFTWARE IS PROVIDED BY THE pfSense PROJECT ``AS IS'' AND ANY
49
 * EXPRESSED OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE
50
 * IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR
51
 * PURPOSE ARE DISCLAIMED. IN NO EVENT SHALL THE pfSense PROJECT OR
52
 * ITS CONTRIBUTORS BE LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL,
53
 * SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES (INCLUDING, BUT
54
 * NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES;
55
 * LOSS OF USE, DATA, OR PROFITS; OR BUSINESS INTERRUPTION)
56
 * HOWEVER CAUSED AND ON ANY THEORY OF LIABILITY, WHETHER IN CONTRACT,
57
 * STRICT LIABILITY, OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE)
58
 * ARISING IN ANY WAY OUT OF THE USE OF THIS SOFTWARE, EVEN IF ADVISED
59
 * OF THE POSSIBILITY OF SUCH DAMAGE.
60
 */
61

    
62
##|+PRIV
63
##|*IDENT=page-diagnostics-command
64
##|*NAME=Diagnostics: Command
65
##|*DESCR=Allow access to the 'Diagnostics: Command' page.
66
##|*MATCH=diag_command.php*
67
##|-PRIV
68

    
69
$allowautocomplete = true;
70

    
71
require_once("guiconfig.inc");
72

    
73
if ($_POST['submit'] == "DOWNLOAD" && file_exists($_POST['dlPath'])) {
74
	session_cache_limiter('public');
75
	$fd = fopen($_POST['dlPath'], "rb");
76
	header("Content-Type: application/octet-stream");
77
	header("Content-Length: " . filesize($_POST['dlPath']));
78
	header("Content-Disposition: attachment; filename=\"" .
79
		trim(htmlentities(basename($_POST['dlPath']))) . "\"");
80
	if (isset($_SERVER['HTTPS'])) {
81
		header('Pragma: ');
82
		header('Cache-Control: ');
83
	} else {
84
		header("Pragma: private");
85
		header("Cache-Control: private, must-revalidate");
86
	}
87

    
88
	fpassthru($fd);
89
	exit;
90
} else if ($_POST['submit'] == "UPLOAD" && is_uploaded_file($_FILES['ulfile']['tmp_name'])) {
91
	move_uploaded_file($_FILES['ulfile']['tmp_name'], "/tmp/" . $_FILES['ulfile']['name']);
92
	$ulmsg = sprintf(gettext('Uploaded file to /tmp/%s.'), htmlentities($_FILES['ulfile']['name']));
93
}
94

    
95
if ($_POST) {
96
	conf_mount_rw();
97
}
98

    
99
// Function: is Blank
100
// Returns true or false depending on blankness of argument.
101

    
102
function isBlank($arg) {
103
	return preg_match("/^\s*$/", $arg);
104
}
105

    
106
// Function: Puts
107
// Put string, Ruby-style.
108

    
109
function puts($arg) {
110
	echo "$arg\n";
111
}
112

    
113
// "Constants".
114

    
115
$Version = '';
116
$ScriptName = $REQUEST['SCRIPT_NAME'];
117

    
118
// Get year.
119

    
120
$arrDT = localtime();
121
$intYear = $arrDT[5] + 1900;
122

    
123
$pgtitle = array(gettext("Diagnostics"), gettext("Command Prompt"));
124
include("head.inc");
125
?>
126
<script type="text/javascript">
127
//<![CDATA[
128
	// Create recall buffer array (of encoded strings).
129
<?php
130

    
131
if (isBlank($_POST['txtRecallBuffer'])) {
132
	puts("	 var arrRecallBuffer = new Array;");
133
} else {
134
	puts("	 var arrRecallBuffer = new Array(");
135
	$arrBuffer = explode("&", $_POST['txtRecallBuffer']);
136
	for ($i = 0; $i < (count($arrBuffer) - 1); $i++) {
137
		puts("		'" . htmlspecialchars($arrBuffer[$i], ENT_QUOTES | ENT_HTML401) . "',");
138
	}
139
	puts("		'" . htmlspecialchars($arrBuffer[count($arrBuffer) - 1], ENT_QUOTES | ENT_HTML401) . "'");
140
	puts("	 );");
141
}
142
?>
143

    
144
	// Set pointer to end of recall buffer.
145
	var intRecallPtr = arrRecallBuffer.length-1;
146

    
147
	// Functions to extend String class.
148
	function str_encode() { return escape( this ) }
149
	function str_decode() { return unescape( this ) }
150

    
151
	// Extend string class to include encode() and decode() functions.
152
	String.prototype.encode = str_encode
153
	String.prototype.decode = str_decode
154

    
155
	// Function: is Blank
156
	// Returns boolean true or false if argument is blank.
157
	function isBlank( strArg ) { return strArg.match( /^\s*$/ ) }
158

    
159
	// Function: frmExecPlus onSubmit (event handler)
160
	// Builds the recall buffer from the command string on submit.
161
	function frmExecPlus_onSubmit( form ) {
162

    
163
		if (!isBlank(form.txtCommand.value)) {
164
			// If this command is repeat of last command, then do not store command.
165
			if (form.txtCommand.value.encode() == arrRecallBuffer[arrRecallBuffer.length-1]) { return true }
166

    
167
			// Stuff encoded command string into the recall buffer.
168
			if (isBlank(form.txtRecallBuffer.value)) {
169
				form.txtRecallBuffer.value = form.txtCommand.value.encode();
170
			} else {
171
				form.txtRecallBuffer.value += '&' + form.txtCommand.value.encode();
172
			}
173
		}
174

    
175
		return true;
176
	}
177

    
178
	// Function: btnRecall onClick (event handler)
179
	// Recalls command buffer going either up or down.
180
	function btnRecall_onClick( form, n ) {
181

    
182
		// If nothing in recall buffer, then error.
183
		if (!arrRecallBuffer.length) {
184
			alert('<?=gettext("Nothing to recall"); ?>!');
185
			form.txtCommand.focus();
186
			return;
187
		}
188

    
189
		// Increment recall buffer pointer in positive or negative direction
190
		// according to <n>.
191
		intRecallPtr += n;
192

    
193
		// Make sure the buffer stays circular.
194
		if (intRecallPtr < 0) { intRecallPtr = arrRecallBuffer.length - 1 }
195
		if (intRecallPtr > (arrRecallBuffer.length - 1)) { intRecallPtr = 0 }
196

    
197
		// Recall the command.
198
		form.txtCommand.value = arrRecallBuffer[intRecallPtr].decode();
199
	}
200

    
201
	// Function: Reset onClick (event handler)
202
	// Resets form on reset button click event.
203
	function Reset_onClick( form ) {
204

    
205
		// Reset recall buffer pointer.
206
		intRecallPtr = arrRecallBuffer.length;
207

    
208
		// Clear form (could have spaces in it) and return focus ready for cmd.
209
		form.txtCommand.value = '';
210
		form.txtCommand.focus();
211

    
212
		return true;
213
	}
214
//]]>
215
</script>
216
<?php
217

    
218
if (isBlank($_POST['txtCommand']) && isBlank($_POST['txtPHPCommand']) && isBlank($ulmsg)) {
219
	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'));
220
}
221

    
222
if ($_POST['submit'] == "EXEC" && !isBlank($_POST['txtCommand'])):?>
223
	<div class="panel panel-success responsive">
224
		<div class="panel-heading"><h2 class="panel-title"><?=sprintf(gettext('Shell Output - %s'), htmlspecialchars($_POST['txtCommand']))?></h2></div>
225
		<div class="panel-body">
226
			<div class="content">
227
<?php
228
	putenv("PATH=/bin:/sbin:/usr/bin:/usr/sbin:/usr/local/bin:/usr/local/sbin");
229
	putenv("SCRIPT_FILENAME=" . strtok($_POST['txtCommand'], " "));
230
	$output = array();
231
	exec($_POST['txtCommand'] . ' 2>&1', $output);
232

    
233
	$output = implode("\n", $output);
234
	print("<pre>" . htmlspecialchars($output) . "</pre>");
235
?>
236
			</div>
237
		</div>
238
	</div>
239
<?php endif; ?>
240

    
241
<form action="diag_command.php" method="post" enctype="multipart/form-data" name="frmExecPlus" onsubmit="return frmExecPlus_onSubmit( this );">
242
	<div class="panel panel-default">
243
		<div class="panel-heading"><h2 class="panel-title"><?=gettext('Execute Shell Command')?></h2></div>
244
		<div class="panel-body">
245
			<div class="content">
246
				<input id="txtCommand" name="txtCommand" placeholder="Command" type="text" class="col-sm-7"	 value="<?=htmlspecialchars($_POST['txtCommand'])?>" />
247
				<br /><br />
248
				<input type="hidden" name="txtRecallBuffer" value="<?=htmlspecialchars($_POST['txtRecallBuffer']) ?>" />
249

    
250
				<div class="btn-group">
251
					<button type="button" class="btn btn-success btn-sm" name="btnRecallPrev" onclick="btnRecall_onClick( this.form, -1 );" title="<?=gettext("Recall Previous Command")?>">
252
						<i class="fa fa-angle-double-left"></i>
253
					</button>
254
					<button name="submit" type="submit" class="btn btn-warning btn-sm" value="EXEC" title="<?=gettext("Execute the entered command")?>">
255
						<i class="fa fa-bolt"></i>
256
						<?=gettext("Execute"); ?>
257
					</button>
258
					<button type="button" class="btn btn-success btn-sm" name="btnRecallNext" onclick="btnRecall_onClick( this.form,  1 );" title="<?=gettext("Recall Next Command")?>">
259
						<i class="fa fa-angle-double-right"></i>
260
					</button>
261
					<button style="margin-left: 10px;" type="button" class="btn btn-default btn-sm" onclick="return Reset_onClick( this.form );" title="<?=gettext("Clear command entry")?>">
262
						<i class="fa fa-undo"></i>
263
						<?=gettext("Clear"); ?>
264
					</button>
265
				</div>
266
			</div>
267
		</div>
268
	</div>
269

    
270
	<div class="panel panel-default">
271
		<div class="panel-heading"><h2 class="panel-title"><?=gettext('Download File')?></h2></div>
272
		<div class="panel-body">
273
			<div class="content">
274
				<input name="dlPath" type="text" id="dlPath" placeholder="File to download" class="col-sm-4" value="<?=htmlspecialchars($_GET['dlPath']);?>"/>
275
				<br /><br />
276
				<button name="submit" type="submit" class="btn btn-primary btn-sm" id="download" value="DOWNLOAD">
277
					<i class="fa fa-download icon-embed-btn"></i>
278
					<?=gettext("Download")?>
279
				</button>
280
			</div>
281
		</div>
282
	</div>
283

    
284
<?php
285
	if ($ulmsg) {
286
		print_info_box($ulmsg, 'success', false);
287
	}
288
?>
289
	<div class="panel panel-default">
290
		<div class="panel-heading"><h2 class="panel-title"><?=gettext('Upload File')?></h2></div>
291
		<div class="panel-body">
292
			<div class="content">
293
				<input name="ulfile" type="file" class="btn btn-default btn-sm btn-file" id="ulfile" />
294
				<br />
295
				<button name="submit" type="submit" class="btn btn-primary btn-sm" id="upload" value="UPLOAD">
296
					<i class="fa fa-upload icon-embed-btn"></i>
297
					<?=gettext("Upload")?>
298
				</button>
299
			</div>
300
		</div>
301
	</div>
302
<?php
303
	
304
	// Experimental version. Writes the user's php code to a file and executes it via a new instance of PHP
305
	// This is intended to prevent bad code from breaking the GUI
306
	if ($_POST['submit'] == "EXECPHP" && !isBlank($_POST['txtPHPCommand'])) {
307

    
308
		safe_mkdir($g[tmp_path_user_code]);     //create if doesn't exist
309
		$tmpfile = tempnam($g[tmp_path_user_code], "");
310
		$phpcode = <<<END_FILE
311
<?php
312
require_once("/etc/inc/config.inc");
313
require_once("/etc/inc/functions.inc");
314

    
315
// USER CODE STARTS HERE:
316

    
317
%s
318
?>
319
END_FILE;
320
		$lineno_correction = 6;  // line numbering correction, this should be the number of lines added above, BEFORE the user's code
321

    
322
		file_put_contents($tmpfile, sprintf($phpcode, $_POST['txtPHPCommand']));
323

    
324
		$output = $matches = array();
325
		$retval = 0;
326
		exec("/usr/local/bin/php -d log_errors=off {$tmpfile}", $output, $retval);
327

    
328
		puts('<div class="panel panel-success responsive"><div class="panel-heading"><h2 class="panel-title">PHP Response</h2></div>');
329

    
330
		// Help user to find bad code line, if it gave an error
331
		$errmsg_found = preg_match("`error.*:.* (?:in|File:) {$tmpfile}(?:\(| on line |, Line: )(\d+)(?:, Message:|\).* eval\(\)'d code|$)`i", implode("\n", $output), $matches);
332
		if ($retval || $errmsg_found) {
333
			/* Trap failed code - test both retval and output message
334
			 * Typical messages as at 2.3.x:
335
			 *   "Parse error: syntax error, ERR_DETAILS in FILE on line NN"
336
			 *   "PHP ERROR: Type: NN, File: FILE, Line: NN, Message: ERR_DETAILS" 
337
			 *   "Parse error: syntax error, unexpected end of file in FILE(NN) : eval()'d code on line 1" [the number in (..) is the error line]
338
			*/
339
			if ($matches[1] > $lineno_correction) {
340
				$errline = $matches[1] - $lineno_correction;
341
				$errtext = sprintf(gettext('Line %s appears to have generated an error, and has been highlighted. The full response is below.'), $errline);
342
			} else {
343
				$errline = -1;
344
				$errtext = gettext('The code appears to have generated an error, but the line responsible cannot be identified. The full response is below.');
345
			}
346
			$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);
347
			$syntax_output = array();
348
			$html = "";
349
			exec("/usr/local/bin/php -s -d log_errors=off {$tmpfile}", $syntax_output);
350
			// Lines 0, 2 and 3 are CSS wrapper for the syntax highlighted code which is at line 1 <br> separated.
351
			$syntax_output = explode("<br />", $syntax_output[1]);
352
			$margin_layout = '%3s %' . strlen(count($syntax_output)) . 'd:';
353
			for ($lineno = 1; $lineno < count($syntax_output) - $lineno_correction; $lineno++) {
354
				$margin = str_replace(' ', '&nbsp;', sprintf($margin_layout, ($lineno == $errline ? '&gt;&gt;&gt;' : ''), $lineno));
355
				$html .= "<span style='color:black;backgroundcolor:lightgrey'><tt>{$margin}</tt></span>&nbsp;&nbsp;{$syntax_output[$lineno + $lineno_correction - 1]}<br/>\n";
356
			}
357
			print_info_box($errtext, 'danger');
358
			print "<div style='margin:20px'><b>" . gettext("Error locator:") . "</b>\n";
359
			print "<div id='errdiv' style='height:7em; width:60%; overflow:auto; white-space: nowrap; border:darkgrey solid 1px; margin-top: 20px'>\n";
360
			print $html . "\n</div></div>\n";
361
		}
362

    
363
		$output = implode("\n", $output);
364
		print("<pre>" . htmlspecialchars($output) . "</pre>");
365

    
366
//		echo eval($_POST['txtPHPCommand']);
367

    
368
		puts("</div>");
369

    
370
		unlink($tmpfile);
371
?>
372
<script type="text/javascript">
373
//<![CDATA[
374
	events.push(function() {
375
		// scroll error locator if needed (does nothing if no error)
376
		$('#errdiv').scrollTop(<?=max($errline - ($lineno_correction - 3.5), 0);?> * parseFloat($('#errdiv').css('line-height')));
377

    
378
		// Scroll to the bottom of the page to more easily see the results of a PHP exec command
379
		$("html, body").animate({ scrollTop: $(document).height() }, 1000);
380
	});
381
//]]>
382
</script>
383
<?php
384
}
385
?>
386
	<div class="panel panel-default responsive">
387
		<div class="panel-heading"><h2 class="panel-title"><?=gettext('Execute PHP Commands')?></h2></div>
388
		<div class="panel-body">
389
			<div class="content">
390
				<textarea id="txtPHPCommand" placeholder="Command" name="txtPHPCommand" rows="9" cols="80"><?=htmlspecialchars($_POST['txtPHPCommand'])?></textarea>
391
				<br />
392
				<button name="submit" type="submit" class="btn btn-warning btn-sm" value="EXECPHP" title="<?=gettext("Execute this PHP Code")?>">
393
					<i class="fa fa-bolt"></i>
394
					<?=gettext("Execute")?>
395
				</button>
396
				<?=gettext("Example"); ?>: <code>print("Hello World!");</code>
397
			</div>
398
		</div>
399
	</div>
400
</form>
401

    
402
<?php
403
include("foot.inc");
404

    
405
if ($_POST) {
406
	conf_mount_ro();
407
}
(7-7/225)