FOSSology  4.7.1
Open Source License Compliance by Open Source Software
UploadSrvPage.php
1 <?php
2 /*
3  SPDX-FileCopyrightText: © 2008-2014 Hewlett-Packard Development Company, L.P.
4  SPDX-FileCopyrightText: © 2015, 2018 Siemens AG
5 
6  SPDX-License-Identifier: GPL-2.0-only
7 */
8 
9 namespace Fossology\UI\Page;
10 
13 use Symfony\Component\HttpFoundation\Request;
14 
16 {
17  const NAME = 'upload_srv_files';
18  const NAME_PARAM = 'name';
19  const SOURCE_FILES_FIELD = 'sourceFiles';
20 
21  public function __construct()
22  {
23  parent::__construct(self::NAME, array(
24  self::TITLE => _("Upload from Server"),
25  self::MENU_LIST => "Upload::From Server",
26  self::DEPENDENCIES => array("agent_unpack", "showjobs"),
27  self::PERMISSION => Auth::PERM_WRITE
28  ));
29  }
30 
31  function check_if_host_is_allowed($host)
32  {
33  global $SysConf;
34  $sysConfig = $SysConf['SYSCONFIG'];
35  if (array_key_exists('UploadFromServerAllowedHosts', $sysConfig)) {
36  $hostListPre = $sysConfig['UploadFromServerAllowedHosts'];
37  $hostList = explode(':', $hostListPre);
38  } else {
39  $hostList = array("localhost");
40  }
41 
42  return in_array($host,$hostList);
43  }
44 
73  function check_by_whitelist($path, $host = 'localhost')
74  {
75  $isLocalHost = ($host === 'localhost' || empty($host));
76  global $SysConf;
77  $sysConfig = $SysConf['SYSCONFIG'];
78  if (array_key_exists('UploadFromServerWhitelist', $sysConfig)) {
79  $whitelistPre = $sysConfig['UploadFromServerWhitelist'];
80  $whitelist = explode(':', $whitelistPre);
81  } else {
82  $whitelist = array("/tmp");
83  }
84  // An explicit "/" entry allows everything, there is no boundary to escape.
85  foreach ($whitelist as $item) {
86  if (trim($item) === '/') {
87  return true;
88  }
89  }
90  // A wildcard is expanded by wget_agent without being resolved. For other
91  // hosts the whole path is unresolved, for localhost normalize_path()
92  // resolves only the directory up to the first wildcard. A wildcard in a
93  // directory component (e.g. "/tmp/*/file") could match a symlink like
94  // /tmp/link -> /etc, so only a wildcard in the last component of a local
95  // path is accepted.
96  if ($this->path_is_pattern($path) &&
97  (!$isLocalHost || $this->path_is_pattern(dirname($path)))) {
98  return false;
99  }
100 
101  $path = str_replace('\ ', ' ', $path);
102  // Paths of remote hosts are compared textually, so a ".." segment
103  // could leave the whitelisted directory on that host.
104  if (preg_match('#(^|/)\.\.(/|$)#', $path)) {
105  return false;
106  }
107 
108  foreach ($whitelist as $item) {
109  $item = rtrim(trim($item), '/');
110  // Skip empty entries, relative entries, which realpath() would resolve
111  // against the working directory, and entries with "..", which
112  // realpath() could widen up to "/" (e.g. "/tmp/..").
113  if ($item === '' || $item[0] !== '/' ||
114  preg_match('#(^|/)\.\.(/|$)#', $item)) {
115  continue;
116  }
117  $prefixes = array($item);
118  $realItem = $isLocalHost ? realpath($item) : false;
119  if ($realItem === '/') {
120  return true;
121  }
122  if ($realItem !== false && $realItem !== $item) {
123  $prefixes[] = rtrim($realItem, '/');
124  }
125  foreach ($prefixes as $prefix) {
126  if ($prefix !== '' &&
127  ($path === $prefix || strpos($path, $prefix . '/') === 0)) {
128  return true;
129  }
130  }
131  }
132  return false;
133  }
134 
144  function remote_file_permission($path, $server = 'localhost', $persmission = 'r')
145  {
149  if ($server === 'localhost' || empty($server)) {
150  $temp_path = str_replace('\ ', ' ', $path); // replace '\ ' with ' '
151  return @fopen($temp_path, $persmission);
152  } else {
153  return 1; // don't do the file permission check if the file is not on the web server
154  }
155  }
156 
165  function remote_file_exists($path, $server = 'localhost')
166  {
170  if ($server === 'localhost' || empty($server)) {
171  $temp_path = str_replace('\ ', ' ', $path); // replace '\ ' with ' '
172  return file_exists($temp_path);
173  } else {
174  return 1; // don't do the file exist check if the file is not on the web server
175  }
176  }
177 
183  protected function handleView(Request $request, $vars)
184  {
185  $vars['sourceFilesField'] = self::SOURCE_FILES_FIELD;
186  $vars['nameField'] = self::NAME_PARAM;
187  $vars['hostlist'] = HostListOption();
188  return $this->render("upload_srv.html.twig", $this->mergeWithDefault($vars));
189  }
190 
194  protected function handleUpload(Request $request)
195  {
196  global $Plugins;
197 
198  define("UPLOAD_ERR_INVALID_FOLDER_PK", 100);
199  define("UPLOAD_ERR_RESEND", 200);
200  $uploadErrors = array(
201  UPLOAD_ERR_INVALID_FOLDER_PK => _("Invalid Folder."),
202  UPLOAD_ERR_RESEND => _("This seems to be a resent file.")
203  );
204 
205  $folderId = intval($request->get(self::FOLDER_PARAMETER_NAME));
206  $description = stripslashes($request->get(self::DESCRIPTION_INPUT_NAME));
207  $description = $this->basicShEscaping($description);
208 
209  if ($request->getSession()->get(self::UPLOAD_FORM_BUILD_PARAMETER_NAME) !=
210  $request->get(self::UPLOAD_FORM_BUILD_PARAMETER_NAME)) {
211  return array(false, $uploadErrors[UPLOAD_ERR_RESEND], $description);
212  }
213 
214  if (empty($folderId)) {
215  return array(false, $uploadErrors[UPLOAD_ERR_INVALID_FOLDER_PK], $description);
216  }
217 
218  $setGlobal = ($request->get('globalDecisions')) ? 1 : 0;
219 
220  $public = $request->get('public');
221  $publicPermission = ($public == self::PUBLIC_ALL) ? Auth::PERM_READ : Auth::PERM_NONE;
222 
223  $sourceFiles = trim($request->get(self::SOURCE_FILES_FIELD));
224  $sourceFiles = $this->basicShEscaping($sourceFiles);
225  $host = $request->get('host') ?: "localhost";
226  if (preg_match('/[^a-z.0-9]/i', $host)) {
227  $text = _("The given host is not valid.");
228  return array(false, $text, $description);
229  }
230  if (! $this->check_if_host_is_allowed($host)) {
231  $text = _("You are not allowed to upload from the chosen host.");
232  return array(false, $text,
233  $description
234  );
235  }
236 
237  $name = $request->get(self::NAME_PARAM);
238 
239  if ((preg_match('/[*?%$]+/', $sourceFiles)) && empty($name)) {
240  $text = _(
241  "The file path contains a wildchar, you must provide a name for the upload.");
242  return array(false, $text, $description);
243  }
244 
245  if (empty($name)) {
246  $name = basename($sourceFiles);
247  }
248  $shortName = $this->basicShEscaping(basename($name));
249  if (empty($shortName)) {
250  $shortName = $name;
251  }
252  if (strcmp($host,"localhost")) {
253  $shortName = $host . ':' . $shortName;
254  }
255 
256  $sourceFiles = $this->normalize_path($sourceFiles,$host);
257  $sourceFiles = str_replace('|', '\|', $sourceFiles);
258  $sourceFiles = str_replace(' ', '\ ', $sourceFiles);
259  $sourceFiles = str_replace("\t", "\\t", $sourceFiles);
260  if ($sourceFiles == FALSE) {
261  $text = _("failed to normalize/validate given path");
262  return array(false, $text, $description);
263  }
264  if ($this->check_by_whitelist($sourceFiles, $host) === FALSE) {
265  $text = _("no suitable prefix found in the whitelist") . ", " .
266  _("you are not allowed to upload this file");
267  return array(false, $text, $description);
268  }
269  if (! $this->path_is_pattern($sourceFiles) &&
270  ! $this->remote_file_exists($sourceFiles, $host)) {
271  $text = _("'$sourceFiles' does not exist.\n");
272  return array(false, $text, $description);
273  }
274  if (! $this->path_is_pattern($sourceFiles) &&
275  ! $this->remote_file_permission($sourceFiles, $host, "r")) {
276  $text = _("Have no READ permission on '$sourceFiles'.\n");
277  return array(false, $text, $description);
278  }
279  if (! $this->path_is_pattern($sourceFiles) && is_file($sourceFiles) &&
280  filesize($sourceFiles) <= 0) {
281  $text = _("You can not upload an empty file.\n");
282  return array(false, $text, $description);
283  }
284 
285  /* Create an upload record. */
286  $uploadMode = (1 << 3); // code for "it came from web upload"
287  $userId = Auth::getUserId();
288  $groupId = Auth::getGroupId();
289  $uploadId = JobAddUpload($userId, $groupId, $shortName, $sourceFiles,
290  $description, $uploadMode, $folderId, $publicPermission, $setGlobal);
291 
292  if (empty($uploadId)) {
293  $text = _("Failed to insert upload record");
294  return array(false, $text, $description);
295  }
296 
297  /* Prepare the job: job "wget" */
298  $jobpk = JobAddJob($userId, $groupId, "wget", $uploadId);
299  if (empty($jobpk) || ($jobpk < 0)) {
300  $text = _("Failed to insert upload record");
301  return array(false, $text, $description);
302  }
303 
304  $jq_args = "$uploadId - $sourceFiles";
305 
306  $jobqueuepk = JobQueueAdd($jobpk, "wget_agent", $jq_args, "no", NULL, $host);
307  if (empty($jobqueuepk)) {
308  $text = _("Failed to insert task 'wget' into job queue");
309  return array(false, $text, $description);
310  }
311 
312  $ErrorMsg = "";
313 
314  /* schedule agents */
315  $unpackplugin = &$Plugins[plugin_find_id("agent_unpack")];
316  $unpackargs = intval($request->get('scm') == 1) ? '-I' : '';
317  $ununpack_jq_pk = $unpackplugin->AgentAdd($jobpk, $uploadId, $ErrorMsg, array("wget_agent"), $unpackargs);
318  if ($ununpack_jq_pk < 0) {
319  return array(false, $text, _($ErrorMsg));
320  }
321 
322  $adj2nestplugin = &$Plugins[plugin_find_id("agent_adj2nest")];
323  $adj2nest_jq_pk = $adj2nestplugin->AgentAdd($jobpk, $uploadId, $ErrorMsg, array());
324  if ($adj2nest_jq_pk < 0) {
325  return array(false, $text, _($ErrorMsg));
326  }
327 
328  $message = $this->postUploadAddJobs($request, $Name, $uploadId, $jobpk);
329  return array(true, $message.$keep, $description, $uploadId);
330  }
331 }
332 register_plugin(new UploadSrvPage());
Contains the constants and helpers for authentication of user.
Definition: Auth.php:24
static getUserId()
Get the current user's id.
Definition: Auth.php:68
static getGroupId()
Get the current user's group id.
Definition: Auth.php:80
render($templateName, $vars=null, $headers=null)
path_is_pattern($path)
checks, whether a path is a pattern from the perspective of a shell
normalize_path($path, $host="localhost", $appendix="")
normalizes an path and returns FALSE on errors
handleView(Request $request, $vars)
handleUpload(Request $request)
Process the upload request.
remote_file_permission($path, $server='localhost', $persmission='r')
chck if one file/dir has one permission
check_by_whitelist($path, $host='localhost')
checks, whether a normalized path lies inside one of the directories in the whitelist
remote_file_exists($path, $server='localhost')
chck if one file/dir exist or not
JobQueueAdd($job_pk, $jq_type, $jq_args, $jq_runonpfile, $Depends, $host=NULL, $jq_cmd_args=NULL)
Insert a jobqueue + jobdepends records.
Definition: common-job.php:157
JobAddUpload($userId, $groupId, $job_name, $filename, $desc, $UploadMode, $folder_pk, $public_perm=Auth::PERM_NONE, $setGlobal=0)
Insert a new upload record, and update the foldercontents table.
Definition: common-job.php:56
HostListOption()
Get host list.
Definition: common-ui.php:174
char * trim(char *ptext)
Trimming whitespace.
Definition: fossconfig.c:690