Passed
Push — master ( 3b5380...186947 )
by Stefan
07:29
created

OptionParser::sanitiseInputs()   D

Complexity

Conditions 20
Paths 37

Size

Total Lines 80
Code Lines 60

Duplication

Lines 0
Ratio 0 %

Importance

Changes 0
Metric Value
eloc 60
dl 0
loc 80
rs 4.1666
c 0
b 0
f 0
cc 20
nc 37
nop 1

How to fix   Long Method    Complexity   

Long Method

Small methods make your code easier to understand, in particular if combined with a good name. Besides, if your method is small, finding a good name is usually much easier.

For example, if you find yourself adding comments to a method's body, this is usually a good sign to extract the commented part to a new method, and use the comment as a starting point when coming up with a good name for this new method.

Commonly applied refactorings include:

1
<?php
2
3
/*
4
 * *****************************************************************************
5
 * Contributions to this work were made on behalf of the GÉANT project, a 
6
 * project that has received funding from the European Union’s Framework 
7
 * Programme 7 under Grant Agreements No. 238875 (GN3) and No. 605243 (GN3plus),
8
 * Horizon 2020 research and innovation programme under Grant Agreements No. 
9
 * 691567 (GN4-1) and No. 731122 (GN4-2).
10
 * On behalf of the aforementioned projects, GEANT Association is the sole owner
11
 * of the copyright in all material which was developed by a member of the GÉANT
12
 * project. GÉANT Vereniging (Association) is registered with the Chamber of 
13
 * Commerce in Amsterdam with registration number 40535155 and operates in the 
14
 * UK as a branch of GÉANT Vereniging.
15
 * 
16
 * Registered office: Hoekenrode 3, 1102BR Amsterdam, The Netherlands. 
17
 * UK branch address: City House, 126-130 Hills Road, Cambridge CB2 1PQ, UK
18
 *
19
 * License: see the web/copyright.inc.php file in the file structure or
20
 *          <base_url>/copyright.php after deploying the software
21
 */
22
23
namespace web\lib\admin;
24
25
use Exception;
26
27
?>
28
<?php
29
30
require_once dirname(dirname(dirname(dirname(__FILE__)))) . "/config/_config.php";
31
32
/**
33
 * This class parses HTML field input from POST and FILES and extracts valid and authorized options to be set.
34
 * 
35
 * @author Stefan Winter <[email protected]>
36
 */
37
class OptionParser extends \core\common\Entity {
38
39
    /**
40
     * an instance of the InputValidation class which we use heavily for syntax checks.
41
     * 
42
     * @var \web\lib\common\InputValidation
43
     */
44
    private $validator;
45
46
    /**
47
     * an instance of the UIElements() class to draw some UI widgets from.
48
     * 
49
     * @var UIElements
50
     */
51
    private $uiElements;
52
53
    /**
54
     * a handle for the Options singleton
55
     * 
56
     * @var \core\Options
57
     */
58
    private $optioninfoObject;
59
60
    /**
61
     * initialises the various handles.
62
     */
63
    public function __construct() {
64
        $this->validator = new \web\lib\common\InputValidation();
65
        $this->uiElements = new UIElements();
66
        $this->optioninfoObject = \core\Options::instance();
67
    }
68
69
    /**
70
     * Verifies whether an incoming upload was actually valid data
71
     * 
72
     * @param string $optiontype     for which option was the data uploaded
73
     * @param string $incomingBinary the uploaded data
74
     * @return boolean whether the data was valid
75
     */
76
    private function checkUploadSanity(string $optiontype, string $incomingBinary) {
77
        switch ($optiontype) {
78
            case "general:logo_file":
79
            case "fed:logo_file":
80
            case "internal:logo_from_url":
81
                // we check logo_file with ImageMagick
82
                return $this->validator->image($incomingBinary);
83
            case "eap:ca_file":
84
            // fall-through intended: both CA types are treated the same
85
            case "fed:minted_ca_file":
86
                // echo "Checking $optiontype with file $filename";
87
                $func = new \core\common\X509;
88
                $cert = $func->processCertificate($incomingBinary);
89
                if (is_array($cert)) { // could also be FALSE if it was incorrect incoming data
1 ignored issue
show
introduced by
The condition is_array($cert) is always false.
Loading history...
90
                    return TRUE;
91
                }
92
                // the certificate seems broken
93
                return FALSE;
94
            case "support:info_file":
95
                $info = new \finfo();
96
                $filetype = $info->buffer($incomingBinary, FILEINFO_MIME_TYPE);
97
98
                // we only take plain text files in UTF-8!
99
                if ($filetype == "text/plain" && iconv("UTF-8", "UTF-8", $incomingBinary) !== FALSE) {
100
                    return TRUE;
101
                }
102
                return FALSE;
103
            default:
104
                return FALSE;
105
        }
106
    }
107
108
    /**
109
     * Known-good options are sometimes converted, this function takes care of that.
110
     * 
111
     * Cases in point:
112
     * - CA import by URL reference: fetch cert from URL and store it as CA file instead
113
     * - Logo import by URL reference: fetch logo from URL and store it as logo file instead
114
     * - CA file: mangle the content so that *only* the valid content remains (raw input may contain line breaks or spaces which are valid, but some supplicants choke upon)
115
     * 
116
     * @param array $options the list of options we got
117
     * @param array $good    by-reference: the future list of actually imported options
118
     * @param array $bad     by-reference: the future list of submitted but rejected options
119
     * @return array the options, post-processed
120
     */
121
    private function postProcessValidAttributes(array $options, array &$good, array &$bad) {
122
        foreach ($options as $index => $iterateOption) {
123
            foreach ($iterateOption as $name => $optionPayload) {
124
                switch ($name) {
125
                    case "eap:ca_url": // eap:ca_url becomes eap:ca_file by downloading the file
126
                        $finalOptionname = "eap:ca_file";
127
                    // intentional fall-through, treatment identical to logo_url
128
                    case "general:logo_url": // logo URLs become logo files by downloading the file
129
                        $finalOptionname = $finalOptionname ?? "general:logo_file";
130
                        if (empty($optionPayload['content'])) {
131
                            break;
132
                        }
133
                        $bindata = \core\common\OutsideComm::downloadFile($optionPayload['content']);
134
                        unset($options[$index]);
135
                        if ($bindata === FALSE) {
136
                            $bad[] = $name;
137
                            break;
138
                        }
139
                        if ($this->checkUploadSanity($finalOptionname, $bindata)) {
140
                            $good[] = $name;
141
                            $options[] = [$finalOptionname => ['lang' => NULL, 'content' => base64_encode($bindata)]];
142
                        } else {
143
                            $bad[] = $name;
144
                        }
145
                        break;
146
                    case "eap:ca_file":
147
                    case "fed:minted_ca_file":
148
                        // CA files get split (PEM files can contain more than one CA cert)
149
                        // the data being processed here is always "good": 
150
                        // if it was eap:ca_file initially then its sanity was checked in step 1;
151
                        // if it was eap:ca_url then it was checked after we downloaded it
152
                        if (empty($optionPayload['content'])) {
153
                            break;
154
                        }
155
                        if (preg_match('/^ROWID-/', $optionPayload['content'])) {
156
                            // accounted for, already in DB
157
                            $good[] = $name;
158
                            break;
159
                        }
160
                        $content = base64_decode($optionPayload['content']);
161
                        unset($options[$index]);
162
                        $x509 = new \core\common\X509();
163
                        $cAFiles = $x509->splitCertificate($content);
164
                        foreach ($cAFiles as $cAFile) {
165
                            $options[] = [$name => ['lang' => NULL, 'content' => base64_encode($x509->pem2der($cAFile))]];
166
                        }
167
                        $good[] = $name;
168
                        break;
169
                    default:
170
                        $good[] = $name; // all other options were checked and are sane in step 1 already
171
                        break;
172
                }
173
            }
174
        }
175
176
        return $options;
177
    }
178
179
    /**
180
     * extracts a coordinate pair from _POST (if any) and returns it in our 
181
     * standard attribute notation
182
     * 
183
     * @param array $postArray data as sent by POST
184
     * @param array $good      options which have been successfully parsed
185
     * @return array
186
     */
187
    private function postProcessCoordinates(array $postArray, array &$good) {
188
        if (!empty($postArray['geo_long']) && !empty($postArray['geo_lat'])) {
189
190
            $lat = $this->validator->coordinate($postArray['geo_lat']);
191
            $lon = $this->validator->coordinate($postArray['geo_long']);
192
            $good[] = ("general:geo_coordinates");
193
            return [0 => ["general:geo_coordinates" => ['lang' => NULL, 'content' => json_encode(["lon" => $lon, "lat" => $lat])]]];
194
        }
195
        return [];
196
    }
197
198
    /**
199
     * creates HTML code for a user-readable summary of the imports
200
     * @param array $good           list of actually imported options
201
     * @param array $bad            list of submitted but rejected options
202
     * @param array $mlAttribsWithC list of language-variant options
203
     * @return string HTML code
204
     */
205
    private function displaySummaryInUI(array $good, array $bad, array $mlAttribsWithC) {
206
        \core\common\Entity::intoThePotatoes();
207
        $retval = "";
208
        // don't do your own table - only the <tr>s here
209
        // list all attributes that were set correctly
210
        $listGood = array_count_values($good);
211
        $uiElements = new UIElements();
212
        foreach ($listGood as $name => $count) {
213
            /// number of times attribute is present, and its name
214
            /// Example: "5x Support E-Mail"
215
            $retval .= $this->uiElements->boxOkay(sprintf(_("%dx %s"), $count, $uiElements->displayName($name)));
216
        }
217
        // list all atributes that had errors
218
        $listBad = array_count_values($bad);
219
        foreach ($listBad as $name => $count) {
220
            $retval .= $this->uiElements->boxError(sprintf(_("%dx %s"), (int) $count, $uiElements->displayName($name)));
221
        }
222
        // list multilang without default
223
        foreach ($mlAttribsWithC as $attribName => $isitsetornot) {
224
            if ($isitsetornot == FALSE) {
225
                $retval .= $this->uiElements->boxWarning(sprintf(_("You did not set a 'default language' value for %s. This means we can only display this string for installers which are <strong>exactly</strong> in the language you configured. For the sake of all other languages, you may want to edit the profile again and populate the 'default/other' language field."), $uiElements->displayName($attribName)));
226
            }
227
        }
228
        \core\common\Entity::outOfThePotatoes();
229
        return $retval;
230
    }
231
232
    /**
233
     * Incoming data is in $_POST and possibly in $_FILES. Collate values into 
234
     * one array according to our name and numbering scheme.
235
     * 
236
     * @param array $postArray  _POST
237
     * @param array $filesArray _FILES
238
     * @return array
239
     */
240
    private function collateOptionArrays(array $postArray, array $filesArray) {
241
242
        $optionarray = $postArray['option'] ?? [];
243
        $valuearray = $postArray['value'] ?? [];
244
        $filesarray = $filesArray['value']['tmp_name'] ?? [];
245
246
        $iterator = array_merge($optionarray, $valuearray, $filesarray);
247
248
        return $iterator;
249
    }
250
251
    /**
252
     * The very end of the processing: clean input data gets sent to the database
253
     * for storage
254
     * 
255
     * @param mixed  $object            for which object are the options
256
     * @param array  $options           the options to store
257
     * @param array  $pendingattributes list of attributes which are already stored but may need to be deleted
258
     * @param string $device            when the $object is Profile, this indicates device-specific attributes
259
     * @param int    $eaptype           when the $object is Profile, this indicates eap-specific attributes
260
     * @return array list of attributes which were previously stored but are to be deleted now
261
     * @throws Exception
262
     */
263
    private function sendOptionsToDatabase($object, array $options, array $pendingattributes, string $device = NULL, int $eaptype = NULL) {
264
        $retval = [];
265
        foreach ($options as $iterateOption) {
266
            foreach ($iterateOption as $name => $optionPayload) {
267
                $optiontype = $this->optioninfoObject->optionType($name);
268
                // some attributes are in the DB and were only called by reference
269
                // keep those which are still referenced, throw the rest away
270
                if ($optiontype["type"] == \core\Options::TYPECODE_FILE && preg_match("/^ROWID-.*-([0-9]+)/", $optionPayload['content'], $retval)) {
271
                    unset($pendingattributes[$retval[1]]);
272
                    continue;
273
                }
274
                switch (get_class($object)) {
275
                    case 'core\\ProfileRADIUS':
276
                        if ($device !== NULL) {
277
                            $object->addAttributeDeviceSpecific($name, $optionPayload['lang'], $optionPayload['content'], $device);
278
                        } elseif ($eaptype !== NULL) {
279
                            $object->addAttributeEAPSpecific($name, $optionPayload['lang'], $optionPayload['content'], $eaptype);
280
                        } else {
281
                            $object->addAttribute($name, $optionPayload['lang'], $optionPayload['content']);
282
                        }
283
                        break;
284
                    case 'core\\IdP':
285
                    case 'core\\User':
286
                    case 'core\\Federation':
287
                    case 'core\\DeploymentManaged':
288
                        $object->addAttribute($name, $optionPayload['lang'], $optionPayload['content']);
289
                        break;
290
                    default:
291
                        throw new Exception("This type of object can't have options that are parsed by this file!");
292
                }
293
            }
294
        }
295
        return $pendingattributes;
296
    }
297
298
    /** many of the content check cases in sanitiseInputs condense due to
299
     *  identical treatment except which validator function to call and 
300
     *  where in POST the content is.
301
     * 
302
     * This is a map between datatype and validation function.
303
     * 
304
     * @var array
305
     */
306
    private const VALIDATOR_FUNCTIONS = [
307
        \core\Options::TYPECODE_TEXT => ["function" => "string", "field" => \core\Options::TYPECODE_TEXT, "extraarg" => [TRUE]],
308
        \core\Options::TYPECODE_COORDINATES => ["function" => "coordJsonEncoded", "field" => \core\Options::TYPECODE_TEXT, "extraarg" => []],
309
        \core\Options::TYPECODE_BOOLEAN => ["function" => "boolean", "field" => \core\Options::TYPECODE_BOOLEAN, "extraarg" => []],
310
        \core\Options::TYPECODE_INTEGER => ["function" => "integer", "field" => \core\Options::TYPECODE_INTEGER, "extraarg" => []],
311
    ];
312
313
    /**
314
     * filters the input to find syntactically correctly submitted attributes
315
     * 
316
     * @param array $listOfEntries       list of POST and FILES entries
317
     * @return array sanitised list of options
318
     * @throws Exception
319
     */
320
    private function sanitiseInputs(array $listOfEntries) {
321
        $retval = [];
322
        $bad = [];
323
        $multilangAttrsWithC = [];
324
        foreach ($listOfEntries as $objId => $objValueRaw) {
325
// pick those without dash - they indicate a new value        
326
            if (preg_match('/^S[0123456789]*$/', $objId) != 1) { // no match
327
                continue;
328
            }
329
            $objValue = $this->validator->optionName(preg_replace('/#.*$/', '', $objValueRaw));
330
            $optioninfo = $this->optioninfoObject->optionType($objValue);
331
            $languageFlag = NULL;
332
            if ($optioninfo["flag"] == "ML") {
333
                if (!isset($listOfEntries["$objId-lang"])) {
334
                    $bad[] = $objValue;
335
                    continue;
336
                }
337
                $this->determineLanguages($objValue, $listOfEntries["$objId-lang"], $multilangAttrsWithC);
338
            }
339
340
            switch ($optioninfo["type"]) {
341
                case \core\Options::TYPECODE_TEXT:
342
                case \core\Options::TYPECODE_COORDINATES:
343
                case \core\Options::TYPECODE_INTEGER:
344
                    $varName = $listOfEntries["$objId-" . self::VALIDATOR_FUNCTIONS[$optioninfo['type']]['field']];
345
                    if (!empty($varName)) {
346
                        $content = call_user_func_array([$this->validator, self::VALIDATOR_FUNCTIONS[$optioninfo['type']]['function']], array_merge([$varName], self::VALIDATOR_FUNCTIONS[$optioninfo['type']]['extraarg']));
347
                        break;
348
                    }
349
                    continue 2;
350
                case \core\Options::TYPECODE_BOOLEAN:
351
                    $varName = $listOfEntries["$objId-" . \core\Options::TYPECODE_BOOLEAN];
352
                    if (!empty($varName)) {
353
                        $contentValid = $this->validator->boolean($varName);
354
                        if ($contentValid) {
355
                            $content = "on";
356
                        } else {
357
                            $bad[] = $objValue;
358
                            continue 2;
359
                        }
360
                        break;
361
                    }
362
                    continue 2;
363
                case \core\Options::TYPECODE_STRING:
364
                    $previsionalContent = $listOfEntries["$objId-" . \core\Options::TYPECODE_STRING];
365
                    if (!empty($previsionalContent)) {
366
                        $content = $this->furtherStringChecks($objValue, $previsionalContent, $bad);
367
                        if ($content === FALSE) {
368
                            continue 2;
369
                        }
370
                        break;
371
                    }
372
                    continue 2;
373
                case \core\Options::TYPECODE_FILE:
374
                    // this is either actually an uploaded file, or a reference to a DB entry of a previously uploaded file
375
                    $reference = $listOfEntries["$objId-" . \core\Options::TYPECODE_STRING];
376
                    if (!empty($reference)) { // was already in, by ROWID reference, extract
377
                        // ROWID means it's a multi-line string (simple strings are inline in the form; so allow whitespace)
378
                        $content = $this->validator->string(urldecode($reference), TRUE);
379
                        break;
380
                    }
381
                    $fileName = $listOfEntries["$objId-" . \core\Options::TYPECODE_FILE] ?? "";
382
                    if ($fileName != "") { // let's do the download
383
                        $rawContent = \core\common\OutsideComm::downloadFile("file:///" . $fileName);
384
385
                        if ($rawContent === FALSE || !$this->checkUploadSanity($objValue, $rawContent)) {
386
                            $bad[] = $objValue;
387
                            continue 2;
388
                        }
389
                        $content = base64_encode($rawContent);
390
                        break;
391
                    }
392
                    continue 2;
393
                default:
394
                    throw new Exception("Internal Error: Unknown option type " . $objValue . "!");
395
            }
396
            // lang can be NULL here, if it's not a multilang attribute, or a ROWID reference. Never mind that.
397
            $retval[] = ["$objValue" => ["lang" => $languageFlag, "content" => $content]];
398
        }
399
        return [$retval, $multilangAttrsWithC, $bad];
400
    }
401
402
    private function determineLanguages($attribute, $languageFlag, &$multilangAttrsWithC) {
403
        if (!isset($multilangAttrsWithC[$attribute])) { // on first sight, initialise the attribute as "no C language set"
404
            $multilangAttrsWithC[$attribute] = FALSE;
405
        }
406
        if ($languageFlag == "") { // user forgot to select a language
407
            $languageFlag = "C";
408
        }
409
        // did we get a C language? set corresponding value to TRUE
410
        if ($languageFlag == "C") {
411
            $multilangAttrsWithC[$attribute] = TRUE;
412
        }
413
    }
414
415
    /**
416
     * 
417
     * @param string $attribute          which attribute was sent?
418
     * @param string $previsionalContent which content was sent?
419
     * @param array  $bad                list of malformed attributes, by-reference
420
     * @return string|false FALSE if value is not in expected format, else the content itself
421
     */
422
    private function furtherStringChecks($attribute, $previsionalContent, &$bad) {
423
        $content = FALSE;
424
        switch ($attribute) {
425
            case "media:consortium_OI":
426
                $content = $this->validator->consortiumOI($previsionalContent);
427
                if ($content === FALSE) {
428
                    $bad[] = $attribute;
429
                    return FALSE;
430
                }
431
                break;
432
            case "media:remove_SSID":
433
                $content = $this->validator->string($previsionalContent);
434
                if ($content == "eduroam") {
435
                    $bad[] = $attribute;
436
                    return FALSE;
437
                }
438
                break;
439
            case "media:force_proxy":
440
                $content = $this->validator->string($previsionalContent);
441
                $serverAndPort = explode(':', strrev($content), 2);
442
                if (count($serverAndPort) != 2) {
443
                    $bad[] = $attribute;
444
                    return FALSE;
445
                }
446
                $port = strrev($serverAndPort[0]);
447
                if (!is_numeric($port)) {
448
                    $bad[] = $attribute;
449
                    return FALSE;
450
                }
451
                break;
452
            case "support:url":
453
                $content = $this->validator->string($previsionalContent);
454
                if (preg_match("/^http/", $content) != 1) {
455
                    $bad[] = $attribute;
456
                    return FALSE;
457
                }
458
                break;
459
            case "support:email":
460
                $content = $this->validator->email($previsionalContent);
461
                if ($content === FALSE) {
462
                    $bad[] = $attribute;
463
                    return FALSE;
464
                }
465
                break;
466
            case "managedsp:operatorname":
467
                $content = $previsionalContent;
468
                if (!preg_match("/^1.*\..*/", $content)) {
469
                    $bad[] = $attribute;
470
                    return FALSE;
471
                }
472
                break;
473
            default:
474
                $content = $this->validator->string($previsionalContent);
475
                break;
476
        }
477
        return $content;
478
    }
479
480
    /**
481
     * The main function: takes all HTML field inputs, makes sense of them and stores valid data in the database
482
     * 
483
     * @param mixed  $object     The object for which attributes were submitted
484
     * @param array  $postArray  incoming attribute names and values as submitted with $_POST
485
     * @param array  $filesArray incoming attribute names and values as submitted with $_FILES
486
     * @param int    $eaptype    for eap-specific attributes (only used where $object is a ProfileRADIUS instance)
487
     * @param string $device     for device-specific attributes (only used where $object is a ProfileRADIUS instance)
488
     * @return string text to be displayed in UI with the summary of attributes added
489
     * @throws Exception
490
     */
491
    public function processSubmittedFields($object, array $postArray, array $filesArray, int $eaptype = NULL, string $device = NULL) {
492
        $good = [];
493
        // Step 1: collate option names, option values and uploaded files (by 
494
        // filename reference) into one array for later handling
495
496
        $iterator = $this->collateOptionArrays($postArray, $filesArray);
497
498
        // Step 2: sieve out malformed input
499
        // $multilangAttrsWithC is a helper array to keep track of multilang 
500
        // options that were set in a specific language but are not 
501
        // accompanied by a "default" language setting
502
        // if there are some without C by the end of processing, we need to warn
503
        // the admin that this attribute is "invisible" in certain languages
504
        // attrib_name -> boolean
505
        // $bad contains the attributes which failed input validation
506
507
        list($cleanData, $multilangAttrsWithC, $bad) = $this->sanitiseInputs($iterator);
508
509
        // Step 3: now we have clean input data. Some attributes need special care:
510
        // URL-based attributes need to be downloaded to get their actual content
511
        // CA files may need to be split (PEM can contain multiple CAs 
512
513
        $optionsStep2 = $this->postProcessValidAttributes($cleanData, $good, $bad);
514
515
        // Step 4: coordinates do not follow the usual POST array as they are 
516
        // two values forming one attribute; extract those two as an extra step
517
518
        $options = array_merge($optionsStep2, $this->postProcessCoordinates($postArray, $good));
519
520
        // Step 5: push all the received options to the database. Keep mind of 
521
        // the list of existing database entries that are to be deleted.
522
        // 5a: first deletion step: purge all old content except file-based attributes;
523
        //     then take note of which file-based attributes are now stale
524
        if ($device === NULL && $eaptype === NULL) {
525
            $remaining = $object->beginflushAttributes();
526
            $killlist = $this->sendOptionsToDatabase($object, $options, $remaining);
527
        } elseif ($device !== NULL) {
528
            $remaining = $object->beginFlushMethodLevelAttributes(0, $device);
529
            $killlist = $this->sendOptionsToDatabase($object, $options, $remaining, $device);
530
        } else {
531
            $remaining = $object->beginFlushMethodLevelAttributes($eaptype, "");
532
            $killlist = $this->sendOptionsToDatabase($object, $options, $remaining, NULL, $eaptype);
533
        }
534
        // 5b: finally, kill the stale file-based attributes which are not wanted any more.
535
        $object->commitFlushAttributes($killlist);
536
537
        // finally: return HTML code that gives feedback about what we did. 
538
        // In some cases, callers won't actually want to display it; so simply
539
        // do not echo the return value. Reasons not to do this is if we working
540
        // e.g. from inside an overlay
541
542
        return $this->displaySummaryInUI($good, $bad, $multilangAttrsWithC);
543
    }
544
545
}
546