Project

General

Profile

Download (12.8 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-2024 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
	send_user_download('file', $_POST['dlPath']);
47
} else if ($_POST['submit'] == "UPLOAD" && is_uploaded_file($_FILES['ulfile']['tmp_name'])) {
48
	move_uploaded_file($_FILES['ulfile']['tmp_name'], g_get('tmp_path') . "/" . $_FILES['ulfile']['name']);
49
	$ulmsg = sprintf(gettext('Uploaded file to %s.'), g_get('tmp_path') . "/" . htmlentities($_FILES['ulfile']['name']));
50
}
51

    
52
// Function: is Blank
53
// Returns true or false depending on blankness of argument.
54

    
55
function isBlank($arg) {
56
	return preg_match("/^\s*$/", $arg);
57
}
58

    
59
// Function: Puts
60
// Put string, Ruby-style.
61

    
62
function puts($arg) {
63
	echo "$arg\n";
64
}
65

    
66
$pgtitle = array(gettext("Diagnostics"), gettext("Command Prompt"));
67
include("head.inc");
68
?>
69
<script type="text/javascript">
70
//<![CDATA[
71
	// Create recall buffer array (of encoded strings).
72
<?php
73

    
74
if (isBlank($_POST['txtRecallBuffer'])) {
75
	puts("	 var arrRecallBuffer = new Array;");
76
} else {
77
	puts("	 var arrRecallBuffer = new Array(");
78
	$arrBuffer = explode("&", $_POST['txtRecallBuffer']);
79
	for ($i = 0; $i < (count($arrBuffer) - 1); $i++) {
80
		puts("		'" . htmlspecialchars($arrBuffer[$i], ENT_QUOTES | ENT_HTML401) . "',");
81
	}
82
	puts("		'" . htmlspecialchars($arrBuffer[count($arrBuffer) - 1], ENT_QUOTES | ENT_HTML401) . "'");
83
	puts("	 );");
84
}
85
?>
86

    
87
	// Set pointer to end of recall buffer.
88
	var intRecallPtr = arrRecallBuffer.length-1;
89

    
90
	// Functions to extend String class.
91
	function str_encode() { return escape( this ) }
92
	function str_decode() { return unescape( this ) }
93

    
94
	// Extend string class to include encode() and decode() functions.
95
	String.prototype.encode = str_encode
96
	String.prototype.decode = str_decode
97

    
98
	// Function: is Blank
99
	// Returns boolean true or false if argument is blank.
100
	function isBlank( strArg ) { return strArg.match( /^\s*$/ ) }
101

    
102
	// Function: frmExecPlus onSubmit (event handler)
103
	// Builds the recall buffer from the command string on submit.
104
	function frmExecPlus_onSubmit( form ) {
105

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

    
110
			// Stuff encoded command string into the recall buffer.
111
			if (isBlank(form.txtRecallBuffer.value)) {
112
				form.txtRecallBuffer.value = form.txtCommand.value.encode();
113
			} else {
114
				form.txtRecallBuffer.value += '&' + form.txtCommand.value.encode();
115
			}
116
		}
117

    
118
		return true;
119
	}
120

    
121
	// Function: btnRecall onClick (event handler)
122
	// Recalls command buffer going either up or down.
123
	function btnRecall_onClick( form, n ) {
124

    
125
		// If nothing in recall buffer, then error.
126
		if (!arrRecallBuffer.length) {
127
			alert('<?=gettext("Nothing to recall"); ?>!');
128
			form.txtCommand.focus();
129
			return;
130
		}
131

    
132
		// Increment recall buffer pointer in positive or negative direction
133
		// according to <n>.
134
		intRecallPtr += n;
135

    
136
		// Make sure the buffer stays circular.
137
		if (intRecallPtr < 0) { intRecallPtr = arrRecallBuffer.length - 1 }
138
		if (intRecallPtr > (arrRecallBuffer.length - 1)) { intRecallPtr = 0 }
139

    
140
		// Recall the command.
141
		form.txtCommand.value = arrRecallBuffer[intRecallPtr].decode();
142
	}
143

    
144
	// Function: Reset onClick (event handler)
145
	// Resets form on reset button click event.
146
	function Reset_onClick( form ) {
147

    
148
		// Reset recall buffer pointer.
149
		intRecallPtr = arrRecallBuffer.length;
150

    
151
		// Clear form (could have spaces in it) and return focus ready for cmd.
152
		form.txtCommand.value = '';
153
		form.txtCommand.focus();
154

    
155
		return true;
156
	}
157
//]]>
158
</script>
159
<?php
160

    
161
if (isBlank($_POST['txtCommand']) && isBlank($_POST['txtPHPCommand']) && isBlank($ulmsg)) {
162
	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'));
163
}
164

    
165
if ($_POST['submit'] == "EXEC" && !isBlank($_POST['txtCommand'])):?>
166
	<div class="panel panel-success responsive">
167
		<div class="panel-heading"><h2 class="panel-title"><?=sprintf(gettext('Shell Output - %s'), htmlspecialchars($_POST['txtCommand']))?></h2></div>
168
		<div class="panel-body">
169
			<div class="content">
170
<?php
171
	putenv("PATH=/bin:/sbin:/usr/bin:/usr/sbin:/usr/local/bin:/usr/local/sbin");
172
	putenv("SCRIPT_FILENAME=" . strtok($_POST['txtCommand'], " "));
173
	$output = array();
174
	exec($_POST['txtCommand'] . ' 2>&1', $output);
175

    
176
	$output = implode("\n", $output);
177
	print("<pre>" . htmlspecialchars($output) . "</pre>");
178
?>
179
			</div>
180
		</div>
181
	</div>
182
<?php endif; ?>
183

    
184
<form action="diag_command.php" method="post" enctype="multipart/form-data" name="frmExecPlus" onsubmit="return frmExecPlus_onSubmit( this );">
185
	<div class="panel panel-default">
186
		<div class="panel-heading"><h2 class="panel-title"><?=gettext('Execute Shell Command')?></h2></div>
187
		<div class="panel-body">
188
			<div class="content">
189
				<input id="txtCommand" name="txtCommand" placeholder="Command" type="text" class="col-sm-7"	 value="<?=htmlspecialchars($_POST['txtCommand'])?>" />
190
				<br /><br />
191
				<input type="hidden" name="txtRecallBuffer" value="<?=htmlspecialchars($_POST['txtRecallBuffer']) ?>" />
192

    
193
				<div class="btn-group">
194
					<button type="button" class="btn btn-success btn-sm" name="btnRecallPrev" onclick="btnRecall_onClick( this.form, -1 );" title="<?=gettext("Recall Previous Command")?>">
195
						<i class="fa-solid fa-angle-double-left"></i>
196
					</button>
197
					<button name="submit" type="submit" class="btn btn-warning btn-sm" value="EXEC" title="<?=gettext("Execute the entered command")?>">
198
						<i class="fa-solid fa-bolt"></i>
199
						<?=gettext("Execute"); ?>
200
					</button>
201
					<button type="button" class="btn btn-success btn-sm" name="btnRecallNext" onclick="btnRecall_onClick( this.form,  1 );" title="<?=gettext("Recall Next Command")?>">
202
						<i class="fa-solid fa-angle-double-right"></i>
203
					</button>
204
					<button style="margin-left: 10px;" type="button" class="btn btn-default btn-sm" onclick="return Reset_onClick( this.form );" title="<?=gettext("Clear command entry")?>">
205
						<i class="fa-solid fa-undo"></i>
206
						<?=gettext("Clear"); ?>
207
					</button>
208
				</div>
209
			</div>
210
		</div>
211
	</div>
212

    
213
	<div class="panel panel-default">
214
		<div class="panel-heading"><h2 class="panel-title"><?=gettext('Download File')?></h2></div>
215
		<div class="panel-body">
216
			<div class="content">
217
				<input name="dlPath" type="text" id="dlPath" placeholder="File to download" class="col-sm-4" value="<?=htmlspecialchars($_REQUEST['dlPath']);?>"/>
218
				<br /><br />
219
				<button name="submit" type="submit" class="btn btn-primary btn-sm" id="download" value="DOWNLOAD">
220
					<i class="fa-solid fa-download icon-embed-btn"></i>
221
					<?=gettext("Download")?>
222
				</button>
223
			</div>
224
		</div>
225
	</div>
226

    
227
<?php
228
	if ($ulmsg) {
229
		print_info_box($ulmsg, 'success', false);
230
	}
231
?>
232
	<div class="panel panel-default">
233
		<div class="panel-heading"><h2 class="panel-title"><?=gettext('Upload File')?></h2></div>
234
		<div class="panel-body">
235
			<div class="content">
236
				<input name="ulfile" type="file" class="btn btn-default btn-sm btn-file" id="ulfile" />
237
				<br />
238
				<button name="submit" type="submit" class="btn btn-primary btn-sm" id="upload" value="UPLOAD">
239
					<i class="fa-solid fa-upload icon-embed-btn"></i>
240
					<?=gettext("Upload")?>
241
				</button>
242
			</div>
243
		</div>
244
	</div>
245
<?php
246

    
247
	// Experimental version. Writes the user's php code to a file and executes it via a new instance of PHP
248
	// This is intended to prevent bad code from breaking the GUI
249
	if ($_POST['submit'] == "EXECPHP" && !isBlank($_POST['txtPHPCommand'])) {
250

    
251
		safe_mkdir(g_get('tmp_path_user_code'));     //create if doesn't exist
252
		$tmpfile = tempnam(g_get('tmp_path_user_code'), "");
253
		$phpcode = <<<END_FILE
254
<?php
255
require_once("/etc/inc/config.inc");
256
require_once("/etc/inc/functions.inc");
257

    
258
// USER CODE STARTS HERE:
259

    
260
%s
261
?>
262
END_FILE;
263
		$lineno_correction = 6;  // line numbering correction, this should be the number of lines added above, BEFORE the user's code
264

    
265
		file_put_contents($tmpfile, sprintf($phpcode, $_POST['txtPHPCommand']));
266

    
267
		$output = $matches = array();
268
		$retval = 0;
269
		exec("/usr/local/bin/php -d zend.exception_ignore_args=0 -d log_errors=off {$tmpfile}", $output, $retval);
270

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

    
273
		// Help user to find bad code line, if it gave an error
274
		$errmsg_found = preg_match("`(error|warning).*:.* (?:in|File:) {$tmpfile}(?:\(| on line |, Line: )(\d+)(?:, Message:|\).* eval\(\)'d code|$)`i", implode(",", $output), $matches);
275
		if ($retval || $errmsg_found) {
276
			/* Trap failed code - test both retval and output message */
277
			if ($matches[2] > $lineno_correction) {
278
				$errline = (int)$matches[2] - $lineno_correction;
279
				$errtext = sprintf(gettext('Line %s appears to have generated an error or warning and has been highlighted. The full response is below.'), $errline);
280
			} else {
281
				$errline = -1;
282
				$errtext = gettext('The code appears to have generated an error, but the line responsible cannot be identified. The full response is below.');
283
			}
284
			$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);
285
			$syntax_output = array();
286
			$html = "";
287
			exec("/usr/local/bin/php -s -d zend.exception_ignore_args=0 -d log_errors=off {$tmpfile}", $syntax_output);
288

    
289
			/* Remove lines with automatically added code */
290
			$syntax_output = array_slice($syntax_output, $lineno_correction, (count($syntax_output) - ($lineno_correction + 1)));
291

    
292
			$margin_layout = '%3s %' . strlen(count($syntax_output)) . 'd:';
293
			for ($lineno = 1; $lineno < (count($syntax_output) + 1); $lineno++) {
294
				$margin = str_replace(' ', '&nbsp;', sprintf($margin_layout, ($lineno == $errline ? '&gt;&gt;&gt;' : ''), $lineno));
295
				$html .= "<span style='color:black;backgroundcolor:lightgrey'><tt>{$margin}</tt></span>&nbsp;&nbsp;{$syntax_output[$lineno - 1]}<br/>\n";
296
			}
297
			print_info_box($errtext, 'danger');
298
			print "<div style='margin:20px'><b>" . gettext("Error locator:") . "</b>\n";
299
			print "<div id='errdiv' style='height:7em; width:60%; overflow:auto; white-space: nowrap; border:darkgrey solid 1px; margin-top: 20px'>\n";
300
			print $html . "\n</div></div>\n";
301
		}
302

    
303
		$output = implode("\n", $output);
304
		print("<pre>" . htmlspecialchars($output) . "</pre>");
305

    
306
//		echo eval($_POST['txtPHPCommand']);
307

    
308
		puts("</div>");
309

    
310
		unlink($tmpfile);
311
?>
312
<script type="text/javascript">
313
//<![CDATA[
314
	events.push(function() {
315
		// scroll error locator if needed (does nothing if no error)
316
		$('#errdiv').scrollTop(<?=max($errline - ($lineno_correction - 3.5), 0);?> * parseFloat($('#errdiv').css('line-height')));
317

    
318
		// Scroll to the bottom of the page to more easily see the results of a PHP exec command
319
		$("html, body").animate({ scrollTop: $(document).height() }, 1000);
320
	});
321
//]]>
322
</script>
323
<?php
324
}
325
?>
326
	<div class="panel panel-default responsive">
327
		<div class="panel-heading"><h2 class="panel-title"><?=gettext('Execute PHP Commands')?></h2></div>
328
		<div class="panel-body">
329
			<div class="content">
330
				<textarea id="txtPHPCommand" placeholder="Command" name="txtPHPCommand" rows="9" cols="80"><?=htmlspecialchars($_POST['txtPHPCommand'])?></textarea>
331
				<br />
332
				<button name="submit" type="submit" class="btn btn-warning btn-sm" value="EXECPHP" title="<?=gettext("Execute this PHP Code")?>">
333
					<i class="fa-solid fa-bolt"></i>
334
					<?=gettext("Execute")?>
335
				</button>
336
				<?=gettext("Example"); ?>: <code>print("Hello World!");</code>
337
			</div>
338
		</div>
339
	</div>
340
</form>
341

    
342
<?php
343
include("foot.inc");
344

    
345
if ($_POST) {
346
}
(12-12/230)