Passed
Push — master ( 09cfdd...94b89f )
by Stefan
07:21 queued 03:30
created

RADIUSTests::redact()   A

Complexity

Conditions 4
Paths 3

Size

Total Lines 13
Code Lines 10

Duplication

Lines 0
Ratio 0 %

Importance

Changes 0
Metric Value
cc 4
eloc 10
nc 3
nop 2
dl 0
loc 13
rs 9.2
c 0
b 0
f 0
1
<?php
2
3
/*
4
 * ******************************************************************************
5
 * Copyright 2011-2017 DANTE Ltd. and GÉANT on behalf of the GN3, GN3+, GN4-1 
6
 * and GN4-2 consortia
7
 *
8
 * License: see the web/copyright.php file in the file structure
9
 * ******************************************************************************
10
 */
11
12
/**
13
 * This file contains code for testing EAP servers
14
 *
15
 * @author Stefan Winter <[email protected]>
16
 * @author Tomasz Wolniewicz <[email protected]>
17
 * @author Maja Gorecka-Wolniewicz <[email protected]>
18
 *
19
 * @package Developer
20
 * 
21
 */
22
23
namespace core\diag;
24
25
use \Exception;
26
27
require_once(dirname(dirname(__DIR__)) . "/config/_config.php");
28
29
/**
30
 * Test suite to verify that an EAP setup is actually working as advertised in
31
 * the real world. Can only be used if CONFIG_DIAGNOSTICS['RADIUSTESTS'] is configured.
32
 *
33
 * @author Stefan Winter <[email protected]>
34
 * @author Tomasz Wolniewicz <[email protected]>
35
 *
36
 * @license see LICENSE file in root directory
37
 *
38
 * @package Developer
39
 */
40
class RADIUSTests extends AbstractTest {
41
42
    /**
43
     * The variables below maintain state of the result of previous checks.
44
     * 
45
     */
46
    private $UDP_reachability_executed;
47
    private $errorlist;
48
49
    /**
50
     * This private variable contains the realm to be checked. Is filled in the
51
     * class constructor.
52
     * 
53
     * @var string
54
     */
55
    private $realm;
56
    private $outerUsernameForChecks;
57
    private $expectedCABundle;
58
    private $expectedServerNames;
59
60
    /**
61
     * the list of EAP types which the IdP allegedly supports.
62
     * 
63
     * @var array
64
     */
65
    private $supportedEapTypes;
66
    private $opMode;
67
    public $UDP_reachability_result;
68
69
    const RADIUS_TEST_OPERATION_MODE_SHALLOW = 1;
70
    const RADIUS_TEST_OPERATION_MODE_THOROUGH = 2;
71
72
    /**
73
     * Constructor for the EAPTests class. The single mandatory parameter is the
74
     * realm for which the tests are to be carried out.
75
     * 
76
     * @param string $realm
77
     * @param string $outerUsernameForChecks
78
     * @param array $supportedEapTypes (array of integer representations of EAP types)
79
     * @param array $expectedServerNames (array of strings)
80
     * @param array $expectedCABundle (array of PEM blocks)
81
     */
82
    public function __construct($realm, $outerUsernameForChecks, $supportedEapTypes = [], $expectedServerNames = [], $expectedCABundle = []) {
83
        parent::__construct();
84
        $oldlocale = $this->languageInstance->setTextDomain('diagnostics');
85
86
        $this->realm = $realm;
87
        $this->outerUsernameForChecks = $outerUsernameForChecks;
88
        $this->expectedCABundle = $expectedCABundle;
89
        $this->expectedServerNames = $expectedServerNames;
90
        $this->supportedEapTypes = $supportedEapTypes;
91
92
        $this->opMode = self::RADIUS_TEST_OPERATION_MODE_SHALLOW;
93
94
        $caNeeded = FALSE;
95
        $serverNeeded = FALSE;
96
        foreach ($supportedEapTypes as $oneEapType) {
97
            if ($oneEapType->needsServerCACert()) {
98
                $caNeeded = TRUE;
99
            }
100
            if ($oneEapType->needsServerName()) {
101
                $serverNeeded = TRUE;
102
            }
103
        }
104
105
        if ($caNeeded) {
106
            // we need to have info about at least one CA cert and server names
107
            if (count($this->expectedCABundle) == 0) {
108
                Throw new Exception("Thorough checks for an EAP type needing CAs were requested, but the required parameters were not given.");
109
            } else {
110
                $this->opMode = self::RADIUS_TEST_OPERATION_MODE_THOROUGH;
111
            }
112
        }
113
114
        if ($serverNeeded) {
115
            if (count($this->expectedServerNames) == 0) {
116
                Throw new Exception("Thorough checks for an EAP type needing server names were requested, but the required parameter was not given.");
117
            } else {
118
                $this->opMode = self::RADIUS_TEST_OPERATION_MODE_THOROUGH;
119
            }
120
        }
121
122
        $this->loggerInstance->debug(4, "RADIUSTests is in opMode " . $this->opMode . ", parameters were: $realm, $outerUsernameForChecks, " . print_r($supportedEapTypes, true));
123
        $this->loggerInstance->debug(4, print_r($expectedServerNames, true));
124
        $this->loggerInstance->debug(4, print_r($expectedCABundle, true));
125
126
        $this->UDP_reachability_result = [];
127
        $this->errorlist = [];
128
        $this->languageInstance->setTextDomain($oldlocale);
129
    }
130
131
    private function printDN($distinguishedName) {
132
        $out = '';
133
        foreach (array_reverse($distinguishedName) as $nameType => $nameValue) { // to give an example: "CN" => "some.host.example" 
134
            if (!is_array($nameValue)) { // single-valued: just a string
135
                $nameValue = ["$nameValue"]; // convert it to a multi-value attrib with just one value :-) for unified processing later on
136
            }
137
            foreach ($nameValue as $oneValue) {
138
                if ($out) {
139
                    $out .= ',';
140
                }
141
                $out .= "$nameType=$oneValue";
142
            }
143
        }
144
        return($out);
145
    }
146
147
    private function printTm($time) {
148
        return(gmdate(\DateTime::COOKIE, $time));
149
    }
150
151
    /**
152
     * This function parses a X.509 server cert and checks if it finds client device incompatibilities
153
     * 
154
     * @param array $servercert the properties of the certificate as returned by processCertificate(), 
155
     *    $servercert is modified, if CRL is defied, it is downloaded and added to the array
156
     *    incoming_server_names, sAN_DNS and CN array values are also defined
157
     * @return array of oddities; the array is empty if everything is fine
158
     */
159
    private function propertyCheckServercert(&$servercert) {
160
// we share the same checks as for CAs when it comes to signature algorithm and basicconstraints
161
// so call that function and memorise the outcome
162
        $returnarray = $this->propertyCheckIntermediate($servercert, TRUE);
163
        $sANdns = [];
164
        if (!isset($servercert['full_details']['extensions'])) {
165
            $returnarray[] = RADIUSTests::CERTPROB_NO_TLS_WEBSERVER_OID;
166
            $returnarray[] = RADIUSTests::CERTPROB_NO_CDP_HTTP;
167
        } else { // Extensions are present...
168
            if (!isset($servercert['full_details']['extensions']['extendedKeyUsage']) || !preg_match("/TLS Web Server Authentication/", $servercert['full_details']['extensions']['extendedKeyUsage'])) {
169
                $returnarray[] = RADIUSTests::CERTPROB_NO_TLS_WEBSERVER_OID;
170
            }
171
            if (isset($servercert['full_details']['extensions']['subjectAltName'])) {
172
                $sANlist = explode(", ", $servercert['full_details']['extensions']['subjectAltName']);
173
                foreach ($sANlist as $subjectAltName) {
174
                    if (preg_match("/^DNS:/", $subjectAltName)) {
175
                        $sANdns[] = substr($subjectAltName, 4);
176
                    }
177
                }
178
            }
179
        }
180
181
        // often, there is only one name, so we store it in an array of one member
182
        $commonName = [$servercert['full_details']['subject']['CN']];
183
        // if we got an array of names instead, then that is already an array, so override
184
        if (isset($servercert['full_details']['subject']['CN']) && is_array($servercert['full_details']['subject']['CN'])) {
185
            $commonName = $servercert['full_details']['subject']['CN'];
186
            $returnarray[] = RADIUSTests::CERTPROB_MULTIPLE_CN;
187
        }
188
        $allnames = array_values(array_unique(array_merge($commonName, $sANdns)));
189
// check for wildcards
190
// check for real hostnames, and whether there is a wildcard in a name
191
        foreach ($allnames as $onename) {
192
            if (preg_match("/\*/", $onename)) {
193
                $returnarray[] = RADIUSTests::CERTPROB_WILDCARD_IN_NAME;
194
                continue; // otherwise we'd ALSO complain that it's not a real hostname
195
            }
196
            if ($onename != "" && filter_var("foo@" . idn_to_ascii($onename), FILTER_VALIDATE_EMAIL) === FALSE) {
197
                $returnarray[] = RADIUSTests::CERTPROB_NOT_A_HOSTNAME;
198
            }
199
        }
200
        $servercert['incoming_server_names'] = $allnames;
201
        $servercert['sAN_DNS'] = $sANdns;
202
        $servercert['CN'] = $commonName;
203
        return $returnarray;
204
    }
205
206
    /**
207
     * This function parses a X.509 intermediate CA cert and checks if it finds client device incompatibilities
208
     * 
209
     * @param array $intermediateCa the properties of the certificate as returned by processCertificate()
210
     * @param boolean complain_about_cdp_existence: for intermediates, not having a CDP is less of an issue than for servers. Set the REMARK (..._INTERMEDIATE) flag if not complaining; and _SERVER if so
211
     * @return array of oddities; the array is empty if everything is fine
212
     */
213
    private function propertyCheckIntermediate(&$intermediateCa, $serverCert = FALSE) {
214
        $returnarray = [];
215
        if (preg_match("/md5/i", $intermediateCa['full_details']['signatureTypeSN'])) {
216
            $returnarray[] = RADIUSTests::CERTPROB_MD5_SIGNATURE;
217
        }
218
        if (preg_match("/sha1/i", $intermediateCa['full_details']['signatureTypeSN'])) {
219
            $returnarray[] = RADIUSTests::CERTPROB_SHA1_SIGNATURE;
220
        }
221
        $this->loggerInstance->debug(4, "CERT IS: " . print_r($intermediateCa, TRUE));
222
        if ($intermediateCa['basicconstraints_set'] == 0) {
223
            $returnarray[] = RADIUSTests::CERTPROB_NO_BASICCONSTRAINTS;
224
        }
225
        if ($intermediateCa['full_details']['public_key_algorithm'] == \core\common\X509::KNOWN_PUBLIC_KEY_ALGORITHMS[0] && $intermediateCa['full_details']['public_key_length'] < 2048) {
226
            $returnarray[] = RADIUSTests::CERTPROB_LOW_KEY_LENGTH;
227
        }
228
        if (!in_array($intermediateCa['full_details']['public_key_algorithm'], \core\common\X509::KNOWN_PUBLIC_KEY_ALGORITHMS)) {
229
            $returnarray[] = RADIUSTests::CERTPROB_UNKNOWN_KEY_ALGORITHM;
0 ignored issues
show
Bug introduced by
The constant core\diag\RADIUSTests::C...B_UNKNOWN_KEY_ALGORITHM was not found. Maybe you did not declare it correctly or list all dependencies?
Loading history...
230
        }
231
        $validFrom = $intermediateCa['full_details']['validFrom_time_t'];
232
        $now = time();
233
        $validTo = $intermediateCa['full_details']['validTo_time_t'];
234
        if ($validFrom > $now || $validTo < $now) {
235
            $returnarray[] = RADIUSTests::CERTPROB_OUTSIDE_VALIDITY_PERIOD;
236
        }
237
        $addCertCrlResult = $this->addCrltoCert($intermediateCa);
238
        if ($addCertCrlResult !== 0 && $serverCert) {
239
            $returnarray[] = $addCertCrlResult;
240
        }
241
242
        return $returnarray;
243
    }
244
245
    /**
246
     * This function returns an array of errors which were encountered in all the tests.
247
     * 
248
     * @return array all the errors
249
     */
250
    public function listerrors() {
251
        return $this->errorlist;
252
    }
253
254
    /**
255
     * This function performs actual authentication checks with MADE-UP credentials.
256
     * Its purpose is to check if a RADIUS server is reachable and speaks EAP.
257
     * The function fills array RADIUSTests::UDP_reachability_result[$probeindex] with all check detail
258
     * in case more than the return code is needed/wanted by the caller
259
     * 
260
     * @param int $probeindex refers to the specific UDP-host in the config that should be checked
261
     * @param boolean $opnameCheck should we check choking on Operator-Name?
262
     * @param boolean $frag should we cause UDP fragmentation? (Warning: makes use of Operator-Name!)
263
     * @return int returncode
264
     */
265
    public function udpReachability($probeindex, $opnameCheck = TRUE, $frag = TRUE) {
266
        // for EAP-TLS to be a viable option, we need to pass a random client cert to make eapol_test happy
267
        // the following PEM data is one of the SENSE EAPLab client certs (not secret at all)
268
        $clientcert = file_get_contents(dirname(__FILE__) . "/clientcert.p12");
269
        if ($clientcert === FALSE) {
1 ignored issue
show
introduced by
The condition $clientcert === FALSE can never be true.
Loading history...
270
            throw new Exception("A dummy client cert is part of the source distribution, but could not be loaded!");
271
        }
272
        // if we are in thorough opMode, use our knowledge for a more clever check
273
        // otherwise guess
274
        if ($this->opMode == self::RADIUS_TEST_OPERATION_MODE_THOROUGH) {
275
            return $this->udpLogin($probeindex, $this->supportedEapTypes[0]->getArrayRep(), $this->outerUsernameForChecks, 'eaplab', $opnameCheck, $frag, $clientcert);
276
        }
277
        return $this->udpLogin($probeindex, \core\common\EAP::EAPTYPE_ANY, "cat-connectivity-test@" . $this->realm, 'eaplab', $opnameCheck, $frag, $clientcert);
278
    }
279
280
    /**
281
     * There is a CRL Distribution Point URL in the certificate. So download the
282
     * CRL and attach it to the cert structure so that we can later find out if
283
     * the cert was revoked
284
     * @param array $cert by-reference: the cert data we are writing into
285
     * @return int result code whether we were successful in retrieving the CRL
286
     */
287
    private function addCrltoCert(&$cert) {
288
        $crlUrl = [];
289
        $returnresult = 0;
290
        if (!isset($cert['full_details']['extensions']['crlDistributionPoints'])) {
291
            $returnresult = RADIUSTests::CERTPROB_NO_CDP;
292
        } else if (!preg_match("/^.*URI\:(http)(.*)$/", str_replace(["\r", "\n"], ' ', $cert['full_details']['extensions']['crlDistributionPoints']), $crlUrl)) {
293
            $returnresult = RADIUSTests::CERTPROB_NO_CDP_HTTP;
294
        } else { // first and second sub-match is the full URL... check it
295
            $crlcontent = \core\common\OutsideComm::downloadFile(trim($crlUrl[1] . $crlUrl[2]));
296
            if ($crlcontent === FALSE) {
1 ignored issue
show
introduced by
The condition $crlcontent === FALSE can never be true.
Loading history...
297
                $returnresult = RADIUSTests::CERTPROB_NO_CRL_AT_CDP_URL;
298
            }
299
            $crlBegin = strpos($crlcontent, "-----BEGIN X509 CRL-----");
300
            if ($crlBegin === FALSE) {
1 ignored issue
show
introduced by
The condition $crlBegin === FALSE can never be true.
Loading history...
301
                $pem = chunk_split(base64_encode($crlcontent), 64, "\n");
302
                $crlcontent = "-----BEGIN X509 CRL-----\n" . $pem . "-----END X509 CRL-----\n";
303
            }
304
            $cert['CRL'] = [];
305
            $cert['CRL'][] = $crlcontent;
306
        }
307
        return $returnresult;
308
    }
309
310
    /**
311
     * We don't want to write passwords of the live login test to our logs. Filter them out
312
     * @param string $stringToRedact what should be redacted
313
     * @param array $inputarray array of strings (outputs of eapol_test command)
314
     * @return string[] the output of eapol_test with the password redacted
315
     */
316
    private function redact($stringToRedact, $inputarray) {
317
        $temparray = preg_replace("/^.*$stringToRedact.*$/", "LINE CONTAINING PASSWORD REDACTED", $inputarray);
318
        $hex = bin2hex($stringToRedact);
319
        $spaced = "";
320
        $origLength = strlen($hex);
321
        for ($i = 1; $i < $origLength; $i++) {
322
            if ($i % 2 == 1 && $i != strlen($hex)) {
323
                $spaced .= $hex[$i] . " ";
324
            } else {
325
                $spaced .= $hex[$i];
326
            }
327
        }
328
        return preg_replace("/$spaced/", " HEX ENCODED PASSWORD REDACTED ", $temparray);
329
    }
330
331
    /**
332
     * Filters eapol_test output and finds out the packet codes out of which the conversation was comprised of
333
     * 
334
     * @param array $inputarray array of strings (outputs of eapol_test command)
335
     * @return array the packet codes which were exchanged, in sequence
336
     */
337
    private function filterPackettype($inputarray) {
338
        $retarray = [];
339
        foreach ($inputarray as $line) {
340
            if (preg_match("/RADIUS message:/", $line)) {
341
                $linecomponents = explode(" ", $line);
342
                $packettypeExploded = explode("=", $linecomponents[2]);
343
                $packettype = $packettypeExploded[1];
344
                $retarray[] = $packettype;
345
            }
346
        }
347
        return $retarray;
348
    }
349
350
    const LINEPARSE_CHECK_REJECTIGNORE = 1;
351
    const LINEPARSE_CHECK_691 = 2;
352
    const LINEPARSE_EAPACK = 3;
353
354
    /**
355
     * this function checks for various special conditions which can be found 
356
     * only by parsing eapol_test output line by line. Checks currently 
357
     * implemented are:
358
     * * if the ETLRs sent back an Access-Reject because there appeared to
359
     *   be a timeout further downstream
360
     * * did the server send an MSCHAP Error 691 - Retry Allowed in a Challenge
361
     *   instead of an outright reject?
362
     * * was an EAP method ever acknowledged by both sides during the EAP
363
     *   conversation
364
     * 
365
     * @param array $inputarray array of strings (outputs of eapol_test command)
366
     * @param int $desiredCheck which test should be run (see constants above)
367
     * @return boolean returns TRUE if ETLR Reject logic was detected; FALSE if not
368
     */
369
    private function checkLineparse($inputarray, $desiredCheck) {
370
        foreach ($inputarray as $lineid => $line) {
371
            switch ($desiredCheck) {
372
                case self::LINEPARSE_CHECK_REJECTIGNORE:
373
                    if (preg_match("/Attribute 18 (Reply-Message)/", $line) && preg_match("/Reject instead of Ignore at eduroam.org/", $inputarray[$lineid + 1])) {
374
                        return TRUE;
375
                    }
376
                    break;
377
                case self::LINEPARSE_CHECK_691:
378
                    if (preg_match("/MSCHAPV2: error 691/", $line) && preg_match("/MSCHAPV2: retry is allowed/", $inputarray[$lineid + 1])) {
379
                        return TRUE;
380
                    }
381
                    break;
382
                case self::LINEPARSE_EAPACK:
383
                    if (preg_match("/CTRL-EVENT-EAP-PROPOSED-METHOD/", $line) && !preg_match("/NAK$/", $line)) {
384
                        return TRUE;
385
                    }
386
                    break;
387
                default:
388
                    throw new Exception("This lineparse test does not exist.");
389
            }
390
        }
391
        return FALSE;
392
    }
393
394
    /**
395
     * 
396
     * @param array $eaptype array representation of the EAP type
397
     * @param string $inner inner username
398
     * @param string $outer outer username
399
     * @param string $password the password
400
     * @return string[] [0] is the actual config for wpa_supplicant, [1] is a redacted version for logs
401
     */
402
    private function wpaSupplicantConfig(array $eaptype, string $inner, string $outer, string $password) {
403
        $eapText = \core\common\EAP::eapDisplayName($eaptype);
404
        $config = '
405
network={
406
  ssid="' . CONFIG['APPEARANCE']['productname'] . ' testing"
407
  key_mgmt=WPA-EAP
408
  proto=WPA2
409
  pairwise=CCMP
410
  group=CCMP
411
  ';
412
// phase 1
413
        $config .= 'eap=' . $eapText['OUTER'] . "\n";
414
        $logConfig = $config;
415
// phase 2 if applicable; all inner methods have passwords
416
        if (isset($eapText['INNER']) && $eapText['INNER'] != "") {
417
            $config .= '  phase2="auth=' . $eapText['INNER'] . "\"\n";
418
            $logConfig .= '  phase2="auth=' . $eapText['INNER'] . "\"\n";
419
        }
420
// all methods set a password, except EAP-TLS
421
        if ($eaptype != \core\common\EAP::EAPTYPE_TLS) {
422
            $config .= "  password=\"$password\"\n";
423
            $logConfig .= "  password=\"not logged for security reasons\"\n";
424
        }
425
// for methods with client certs, add a client cert config block
426
        if ($eaptype == \core\common\EAP::EAPTYPE_TLS || $eaptype == \core\common\EAP::EAPTYPE_ANY) {
427
            $config .= "  private_key=\"./client.p12\"\n";
428
            $logConfig .= "  private_key=\"./client.p12\"\n";
429
            $config .= "  private_key_passwd=\"$password\"\n";
430
            $logConfig .= "  private_key_passwd=\"not logged for security reasons\"\n";
431
        }
432
433
// inner identity
434
        $config .= '  identity="' . $inner . "\"\n";
435
        $logConfig .= '  identity="' . $inner . "\"\n";
436
// outer identity, may be equal
437
        $config .= '  anonymous_identity="' . $outer . "\"\n";
438
        $logConfig .= '  anonymous_identity="' . $outer . "\"\n";
439
// done
440
        $config .= "}";
441
        $logConfig .= "}";
442
443
        return [$config, $logConfig];
444
    }
445
446
    private function packetCountEvaluation(&$testresults, $packetcount) {
447
        $reqs = $packetcount[1] ?? 0;
448
        $accepts = $packetcount[2] ?? 0;
449
        $rejects = $packetcount[3] ?? 0;
450
        $challenges = $packetcount[11] ?? 0;
451
        $testresults['packetflow_sane'] = TRUE;
452
        if ($reqs - $accepts - $rejects - $challenges != 0 || $accepts > 1 || $rejects > 1) {
453
            $testresults['packetflow_sane'] = FALSE;
454
        }
455
456
        $this->loggerInstance->debug(5, "XYZ: Counting req, acc, rej, chal: $reqs, $accepts, $rejects, $challenges");
457
458
// calculate the main return values that this test yielded
459
460
        $finalretval = RADIUSTests::RETVAL_INVALID;
461
        if ($accepts + $rejects == 0) { // no final response. hm.
462
            if ($challenges > 0) { // but there was an Access-Challenge
463
                $finalretval = RADIUSTests::RETVAL_SERVER_UNFINISHED_COMM;
464
            } else {
465
                $finalretval = RADIUSTests::RETVAL_NO_RESPONSE;
466
            }
467
        } else // either an accept or a reject
468
// rejection without EAP is fishy
469
        if ($rejects > 0) {
470
            if ($challenges == 0) {
471
                $finalretval = RADIUSTests::RETVAL_IMMEDIATE_REJECT;
472
            } else { // i.e. if rejected with challenges
473
                $finalretval = RADIUSTests::RETVAL_CONVERSATION_REJECT;
474
            }
475
        } else if ($accepts > 0) {
476
            $finalretval = RADIUSTests::RETVAL_OK;
477
        }
478
479
        return $finalretval;
480
    }
481
482
    /**
483
     * generate an eapol_test command-line config for the fixed config filename 
484
     * ./udp_login_test.conf
485
     * @param int $probeindex number of the probe to check against
486
     * @param boolean $opName include Operator-Name in request?
487
     * @param boolean $frag make request so large that fragmentation is needed?
488
     * @return string the command-line for eapol_test
489
     */
490
    private function eapolTestConfig($probeindex, $opName, $frag) {
491
        $cmdline = CONFIG_DIAGNOSTICS['PATHS']['eapol_test'] .
492
                " -a " . CONFIG_DIAGNOSTICS['RADIUSTESTS']['UDP-hosts'][$probeindex]['ip'] .
493
                " -s " . CONFIG_DIAGNOSTICS['RADIUSTESTS']['UDP-hosts'][$probeindex]['secret'] .
494
                " -o serverchain.pem" .
495
                " -c ./udp_login_test.conf" .
496
                " -M 22:44:66:CA:20:" . sprintf("%02d", $probeindex) . " " .
497
                " -t " . CONFIG_DIAGNOSTICS['RADIUSTESTS']['UDP-hosts'][$probeindex]['timeout'] . " ";
498
        if ($opName) {
499
            $cmdline .= '-N126:s:"1cat.eduroam.org" ';
500
        }
501
        if ($frag) {
502
            for ($i = 0; $i < 6; $i++) { // 6 x 250 bytes means UDP fragmentation will occur - good!
503
                $cmdline .= '-N26:x:0000625A0BF961616161616161616161616161616161616161616161616161616161616161616161616161616161616161616161616161616161616161616161616161616161616161616161616161616161616161616161616161616161616161616161616161616161616161616161616161616161616161616161616161616161616161616161616161616161616161616161616161616161616161616161616161616161616161616161616161616161616161616161616161616161616161616161616161616161616161616161616161616161616161616161616161616161616161616161616161616161616161616161616161616161616161 ';
504
            }
505
        }
506
        return $cmdline;
507
    }
508
509
    private function createCArepository($tmpDir, &$intermOdditiesCAT, $servercert, $eapIntermediates, $eapIntermediateCRLs) {
510
        // collect CA certificates, both the incoming EAP chain and from CAT config
511
        // Write the root CAs into a trusted root CA dir
512
        // and intermediate and first server cert into a PEM file
513
        // for later chain validation
514
515
        if (!mkdir($tmpDir . "/root-ca-allcerts/", 0700, true)) {
516
            throw new Exception("unable to create root CA directory (RADIUS Tests): $tmpDir/root-ca-allcerts/\n");
517
        }
518
        if (!mkdir($tmpDir . "/root-ca-eaponly/", 0700, true)) {
519
            throw new Exception("unable to create root CA directory (RADIUS Tests): $tmpDir/root-ca-eaponly/\n");
520
        }
521
// make a copy of the EAP-received chain and add the configured intermediates, if any
522
        $catIntermediates = [];
523
        $catRoots = [];
524
        foreach ($this->expectedCABundle as $oneCA) {
525
            $x509 = new \core\common\X509();
526
            $decoded = $x509->processCertificate($oneCA);
527
            if ($decoded === FALSE) {
528
                throw new Exception("Unable to parse an expected CA certificate.");
529
            }
530
            if ($decoded['ca'] == 1) {
531
                if ($decoded['root'] == 1) { // save CAT roots to the root directory
532
                    file_put_contents($tmpDir . "/root-ca-eaponly/configuredroot" . count($catRoots) . ".pem", $decoded['pem']);
533
                    file_put_contents($tmpDir . "/root-ca-allcerts/configuredroot" . count($catRoots) . ".pem", $decoded['pem']);
534
                    $catRoots[] = $decoded['pem'];
535
                } else { // save the intermediates to allcerts directory
536
                    file_put_contents($tmpDir . "/root-ca-allcerts/cat-intermediate" . count($catIntermediates) . ".pem", $decoded['pem']);
537
                    $intermOdditiesCAT = array_merge($intermOdditiesCAT, $this->propertyCheckIntermediate($decoded));
538
                    if (isset($decoded['CRL']) && isset($decoded['CRL'][0])) {
539
                        $this->loggerInstance->debug(4, "got an intermediate CRL; adding them to the chain checks. (Remember: checking end-entity cert only, not the whole chain");
540
                        file_put_contents($tmpDir . "/root-ca-allcerts/crl_cat" . count($catIntermediates) . ".pem", $decoded['CRL'][0]);
541
                    }
542
                    $catIntermediates[] = $decoded['pem'];
543
                }
544
            }
545
        }
546
        // save all intermediate certificates and CRLs to separate files in 
547
        // both root-ca directories
548
        foreach ($eapIntermediates as $index => $onePem) {
549
            file_put_contents($tmpDir . "/root-ca-eaponly/intermediate$index.pem", $onePem);
550
            file_put_contents($tmpDir . "/root-ca-allcerts/intermediate$index.pem", $onePem);
551
        }
552
        foreach ($eapIntermediateCRLs as $index => $onePem) {
553
            file_put_contents($tmpDir . "/root-ca-eaponly/intermediateCRL$index.pem", $onePem);
554
            file_put_contents($tmpDir . "/root-ca-allcerts/intermediateCRL$index.pem", $onePem);
555
        }
556
557
        $checkstring = "";
558
        if (isset($servercert['CRL']) && isset($servercert['CRL'][0])) {
559
            $this->loggerInstance->debug(4, "got a server CRL; adding them to the chain checks. (Remember: checking end-entity cert only, not the whole chain");
560
            $checkstring = "-crl_check_all";
561
            file_put_contents($tmpDir . "/root-ca-eaponly/crl-server.pem", $servercert['CRL'][0]);
562
            file_put_contents($tmpDir . "/root-ca-allcerts/crl-server.pem", $servercert['CRL'][0]);
563
        }
564
565
566
// now c_rehash the root CA directory ...
567
        system(CONFIG_DIAGNOSTICS['PATHS']['c_rehash'] . " $tmpDir/root-ca-eaponly/ > /dev/null");
568
        system(CONFIG_DIAGNOSTICS['PATHS']['c_rehash'] . " $tmpDir/root-ca-allcerts/ > /dev/null");
569
        return $checkstring;
570
    }
571
572
    private function thoroughChainChecks(&$testresults, &$intermOdditiesCAT, $tmpDir, $servercert, $eapIntermediates, $eapIntermediateCRLs) {
573
574
        $crlCheckString = $this->createCArepository($tmpDir, $intermOdditiesCAT, $servercert, $eapIntermediates, $eapIntermediateCRLs);
575
576
// ... and run the verification test
577
        $verifyResultEaponly = [];
578
        $verifyResultAllcerts = [];
579
// the error log will complain if we run this test against an empty file of certs
580
// so test if there's something PEMy in the file at all
581
        if (filesize("$tmpDir/incomingserver.pem") > 10) {
582
            exec(CONFIG['PATHS']['openssl'] . " verify $crlCheckString -CApath $tmpDir/root-ca-eaponly/ -purpose any $tmpDir/incomingserver.pem", $verifyResultEaponly);
583
            $this->loggerInstance->debug(4, CONFIG['PATHS']['openssl'] . " verify $crlCheckString -CApath $tmpDir/root-ca-eaponly/ -purpose any $tmpDir/incomingserver.pem\n");
584
            $this->loggerInstance->debug(4, "Chain verify pass 1: " . print_r($verifyResultEaponly, TRUE) . "\n");
585
            exec(CONFIG['PATHS']['openssl'] . " verify $crlCheckString -CApath $tmpDir/root-ca-allcerts/ -purpose any $tmpDir/incomingserver.pem", $verifyResultAllcerts);
586
            $this->loggerInstance->debug(4, CONFIG['PATHS']['openssl'] . " verify $crlCheckString -CApath $tmpDir/root-ca-allcerts/ -purpose any $tmpDir/incomingserver.pem\n");
587
            $this->loggerInstance->debug(4, "Chain verify pass 2: " . print_r($verifyResultAllcerts, TRUE) . "\n");
588
        }
589
590
591
// now we do certificate verification against the collected parents
592
// this is done first for the server and then for each of the intermediate CAs
593
// any oddities observed will 
594
// openssl should havd returned exactly one line of output,
595
// and it should have ended with the string "OK", anything else is fishy
596
// The result can also be an empty array - this means there were no
597
// certificates to check. Don't complain about chain validation errors
598
// in that case.
599
// we have the following test result possibilities:
600
// 1. test against allcerts failed
601
// 2. test against allcerts succeded, but against eaponly failed - warn admin
602
// 3. test against eaponly succeded, in this case critical errors about expired certs
603
//    need to be changed to notices, since these certs obviously do tot participate
604
//    in server certificate validation.
605
        if (count($verifyResultAllcerts) == 0 || count($verifyResultEaponly) == 0) {
606
            throw new Exception("No output at all from openssl?");
607
        }
608
        if (!preg_match("/OK$/", $verifyResultAllcerts[0])) { // case 1
609
            if (preg_match("/certificate revoked$/", $verifyResultAllcerts[1])) {
610
                $testresults['cert_oddities'][] = RADIUSTests::CERTPROB_SERVER_CERT_REVOKED;
611
            } elseif (preg_match("/unable to get certificate CRL/", $verifyResultAllcerts[1])) {
612
                $testresults['cert_oddities'][] = RADIUSTests::CERTPROB_UNABLE_TO_GET_CRL;
613
            } else {
614
                $testresults['cert_oddities'][] = RADIUSTests::CERTPROB_TRUST_ROOT_NOT_REACHED;
615
            }
616
            return 1;
617
        }
618
        if (!preg_match("/OK$/", $verifyResultEaponly[0])) { // case 2
619
            if (preg_match("/certificate revoked$/", $verifyResultEaponly[1])) {
620
                $testresults['cert_oddities'][] = RADIUSTests::CERTPROB_SERVER_CERT_REVOKED;
621
            } elseif (preg_match("/unable to get certificate CRL/", $verifyResultEaponly[1])) {
622
                $testresults['cert_oddities'][] = RADIUSTests::CERTPROB_UNABLE_TO_GET_CRL;
623
            } else {
624
                $testresults['cert_oddities'][] = RADIUSTests::CERTPROB_TRUST_ROOT_REACHED_ONLY_WITH_OOB_INTERMEDIATES;
625
            }
626
            return 2;
627
        }
628
        return 3;
629
    }
630
631
    private function thoroughNameChecks($servercert, &$testresults) {
632
        // check the incoming hostname (both Subject:CN and subjectAltName:DNS
633
        // against what is configured in the profile; it's a significant error
634
        // if there is no match!
635
        // FAIL if none of the configured names show up in the server cert
636
        // WARN if the configured name is only in either CN or sAN:DNS
637
        // Strategy for checks: we are TOTALLY happy if any one of the
638
        // configured names shows up in both the CN and a sAN
639
        // This is the primary check.
640
        // If that was not the case, we are PARTIALLY happy if any one of
641
        // the configured names was in either of the CN or sAN lists.
642
        // we are UNHAPPY if no names match!
643
644
        $happiness = "UNHAPPY";
645
        foreach ($this->expectedServerNames as $expectedName) {
646
            $this->loggerInstance->debug(4, "Managing expectations for $expectedName: " . print_r($servercert['CN'], TRUE) . print_r($servercert['sAN_DNS'], TRUE));
647
            if (array_search($expectedName, $servercert['CN']) !== FALSE && array_search($expectedName, $servercert['sAN_DNS']) !== FALSE) {
648
                $this->loggerInstance->debug(4, "Totally happy!");
649
                $happiness = "TOTALLY";
650
                break;
651
            } else {
652
                if (array_search($expectedName, $servercert['CN']) !== FALSE || array_search($expectedName, $servercert['sAN_DNS']) !== FALSE) {
653
                    $happiness = "PARTIALLY";
654
// keep trying with other expected names! We could be happier!
655
                }
656
            }
657
        }
658
        switch ($happiness) {
659
            case "UNHAPPY":
660
                $testresults['cert_oddities'][] = RADIUSTests::CERTPROB_SERVER_NAME_MISMATCH;
661
                return;
662
            case "PARTIALLY":
663
                $testresults['cert_oddities'][] = RADIUSTests::CERTPROB_SERVER_NAME_PARTIAL_MATCH;
664
                return;
665
            default: // nothing to complain about!
666
                return;
667
        }
668
    }
669
670
    private function executeEapolTest($tmpDir, $probeindex, $eaptype, $innerUser, $password, $opnameCheck, $frag) {
671
        $finalInner = $innerUser;
672
        $finalOuter = $this->outerUsernameForChecks;
673
674
        $theconfigs = $this->wpaSupplicantConfig($eaptype, $finalInner, $finalOuter, $password);
675
        // the config intentionally does not include CA checking. We do this
676
        // ourselves after getting the chain with -o.
677
        file_put_contents($tmpDir . "/udp_login_test.conf", $theconfigs[0]);
678
679
        $cmdline = $this->eapolTestConfig($probeindex, $opnameCheck, $frag);
680
        $this->loggerInstance->debug(4, "Shallow reachability check cmdline: $cmdline\n");
681
        $this->loggerInstance->debug(4, "Shallow reachability check config: $tmpDir\n" . $theconfigs[1] . "\n");
682
        $time_start = microtime(true);
683
        $pflow = [];
684
        exec($cmdline, $pflow);
685
        if ($pflow === NULL) {
1 ignored issue
show
introduced by
The condition $pflow === NULL can never be true.
Loading history...
686
            throw new Exception("The output of an exec() call really can't be NULL!");
687
        }
688
        $time_stop = microtime(true);
689
        $this->loggerInstance->debug(5, print_r($this->redact($password, $pflow), TRUE));
690
        return [
691
            "time" => ($time_stop - $time_start) * 1000,
692
            "output" => $pflow,
693
        ];
694
    }
695
696
    private function checkRadiusPacketFlow(&$testresults, $packetflow_orig) {
697
698
        $packetflow = $this->filterPackettype($packetflow_orig);
699
700
701
// when MS-CHAPv2 allows retry, we never formally get a reject (just a 
702
// Challenge that PW was wrong but and we should try a different one; 
703
// but that effectively is a reject
704
// so change the flow results to take that into account
705
        if ($packetflow[count($packetflow) - 1] == 11 && $this->checkLineparse($packetflow_orig, self::LINEPARSE_CHECK_691)) {
706
            $packetflow[count($packetflow) - 1] = 3;
707
        }
708
// also, the ETLRs sometimes send a reject when the server is not 
709
// responding. This should not be considered a real reject; it's a middle
710
// box unduly altering the end-to-end result. Do not consider this final
711
// Reject if it comes from ETLR
712
        if ($packetflow[count($packetflow) - 1] == 3 && $this->checkLineparse($packetflow_orig, self::LINEPARSE_CHECK_REJECTIGNORE)) {
713
            array_pop($packetflow);
714
        }
715
        $this->loggerInstance->debug(5, "Packetflow: " . print_r($packetflow, TRUE));
716
        $packetcount = array_count_values($packetflow);
717
        $testresults['packetcount'] = $packetcount;
718
        $testresults['packetflow'] = $packetflow;
719
720
// calculate packet counts and see what the overall flow was
721
        return $this->packetCountEvaluation($testresults, $packetcount);
722
    }
723
724
    /**
725
     * parses the eapol_test output to determine whether we got to a point where
726
     * an EAP type was mutually agreed
727
     * 
728
     * @param array $testresults by-reference, we add our findings if something is noteworthy
729
     * @param array $packetflow_orig the array of text output from eapol_test
730
     * @return bool
731
     */
732
    private function wasEapTypeNegotiated(&$testresults, $packetflow_orig) {
733
        $testresults['cert_oddities'] = [];
734
735
        $negotiatedEapType = $this->checkLineparse($packetflow_orig, self::LINEPARSE_EAPACK);
736
        if (!$negotiatedEapType) {
737
            $testresults['cert_oddities'][] = RADIUSTests::CERTPROB_NO_COMMON_EAP_METHOD;
738
        }
739
740
        return $negotiatedEapType;
741
    }
742
743
    const SERVER_NO_CA_EXTENSION = 1;
744
    const SERVER_CA_SELFSIGNED = 2;
745
    const CA_INTERMEDIATE = 3;
746
    const CA_ROOT = 4;
747
748
    private function determineCertificateType(&$cert, $totalCertCount) {
749
        if ($cert['ca'] == 0 && $cert['root'] == 0) {
750
            return RADIUSTests::SERVER_NO_CA_EXTENSION;
751
        }
752
        if ($cert['ca'] == 1 && $cert['root'] == 1) {
753
            if ($totalCertCount == 1) {
754
                $cert['full_details']['type'] = 'totally_selfsigned';
755
                return RADIUSTests::SERVER_CA_SELFSIGNED;
756
            } else {
757
                return RADIUSTests::CA_ROOT;
758
            }
759
        }
760
        return RADIUSTests::CA_INTERMEDIATE;
761
    }
762
763
    private function extractIncomingCertsfromEAP(&$testresults, $tmpDir) {
764
765
        /*
766
         *  EAP's house rules:
767
         * 1) it is unnecessary to include the root CA itself (adding it has
768
         *    detrimental effects on performance)
769
         * 2) TLS Web Server OID presence (Windows OSes need that)
770
         * 3) MD5 signature algorithm disallowed (iOS barks if so)
771
         * 4) CDP URL (Windows Phone 8 barks if not present)
772
         * 5) there should be exactly one server cert in the chain
773
         */
774
775
        $x509 = new \core\common\X509();
776
        $eapCertArray = [];
777
// $eap_certarray holds all certs received in EAP conversation
778
        $incomingData = file_get_contents($tmpDir . "/serverchain.pem");
779
        if ($incomingData !== FALSE) {
1 ignored issue
show
introduced by
The condition $incomingData !== FALSE can never be false.
Loading history...
780
            $eapCertArray = $x509->splitCertificate($incomingData);
781
        }
782
        $eapIntermediates = [];
783
        $eapIntermediateCRLs = [];
784
        $servercert = [];
785
        $intermOdditiesEAP = [];
786
787
        $testresults['certdata'] = [];
788
789
790
        foreach ($eapCertArray as $certPem) {
791
            $cert = $x509->processCertificate($certPem);
792
            if ($cert === FALSE) {
793
                continue;
794
            }
795
// consider the certificate a server cert 
796
// a) if it is not a CA and is not a self-signed root
797
// b) if it is a CA, and self-signed, and it is the only cert in
798
//    the incoming cert chain
799
//    (meaning the self-signed is itself the server cert)
800
            switch ($this->determineCertificateType($cert, count($eapCertArray))) {
801
                case RADIUSTests::SERVER_NO_CA_EXTENSION: // both are handled same, fall-through
802
                case RADIUSTests::SERVER_CA_SELFSIGNED:
803
                    $servercert[] = $cert;
804
                    if (count($servercert) == 1) {
805
                        if (file_put_contents($tmpDir . "/incomingserver.pem", $certPem . "\n") === FALSE) {
806
                            $this->loggerInstance->debug(4, "The (first) server certificate could not be written to $tmpDir/incomingserver.pem!\n");
807
                        }
808
                        $this->loggerInstance->debug(4, "This is the (first) server certificate, with CRL content if applicable: " . print_r($servercert[0], true));
809
                    } elseif (!in_array(RADIUSTests::CERTPROB_TOO_MANY_SERVER_CERTS, $testresults['cert_oddities'])) {
810
                        $testresults['cert_oddities'][] = RADIUSTests::CERTPROB_TOO_MANY_SERVER_CERTS;
811
                    }
812
                    break;
813
                case RADIUSTests::CA_ROOT:
814
                    if (!in_array(RADIUSTests::CERTPROB_ROOT_INCLUDED, $testresults['cert_oddities'])) {
815
                        $testresults['cert_oddities'][] = RADIUSTests::CERTPROB_ROOT_INCLUDED;
816
                    }
817
// do not save the root CA, it serves no purpose
818
// chain checks need to be against the UPLOADED CA of the
819
// IdP/profile, not against an EAP-discovered CA
820
                    break;
821
                case RADIUSTests::CA_INTERMEDIATE:
822
                    $intermOdditiesEAP = array_merge($intermOdditiesEAP, $this->propertyCheckIntermediate($cert));
823
                    $eapIntermediates[] = $certPem;
824
825
                    if (isset($cert['CRL']) && isset($cert['CRL'][0])) {
826
                        $eapIntermediateCRLs[] = $cert['CRL'][0];
827
                    }
828
                    break;
829
                default:
830
                    throw new Exception("Status of certificate could not be determined!");
831
            }
832
            $testresults['certdata'][] = $cert['full_details'];
833
        }
834
        switch (count($servercert)) {
835
            case 0:
836
                $testresults['cert_oddities'][] = RADIUSTests::CERTPROB_NO_SERVER_CERT;
837
                break;
838
            default:
839
// check (first) server cert's properties
840
                $testresults['cert_oddities'] = array_merge($testresults['cert_oddities'], $this->propertyCheckServercert($servercert[0]));
841
                $testresults['incoming_server_names'] = $servercert[0]['incoming_server_names'];
842
        }
843
        return [
844
            "SERVERCERT" => $servercert,
845
            "INTERMEDIATE_CA" => $eapIntermediates,
846
            "INTERMEDIATE_CRL" => $eapIntermediateCRLs,
847
            "INTERMEDIATE_OBSERVED_ODDITIES" => $intermOdditiesEAP,
848
        ];
849
    }
850
851
    /**
852
     * The big Guy. This performs an actual login with EAP and records how far 
853
     * it got and what oddities were observed along the way
854
     * @param int $probeindex the probe we are connecting to (as set in product config)
855
     * @param array $eaptype EAP type to use for connection
856
     * @param string $innerUser inner username to try
857
     * @param string $password password to try
858
     * @param boolean $opnameCheck whether or not we check with Operator-Name set
859
     * @param boolean $frag whether or not we check with an oversized packet forcing fragmentation
860
     * @param string $clientcertdata client certificate credential to try
861
     * @return int overall return code of the login test
862
     * @throws Exception
863
     */
864
    public function udpLogin($probeindex, $eaptype, $innerUser, $password, $opnameCheck = TRUE, $frag = TRUE, $clientcertdata = NULL) {
865
        /** preliminaries */
866
        $eapText = \core\common\EAP::eapDisplayName($eaptype);
867
        // no host to send probes to? Nothing to do then
868
        if (!isset(CONFIG_DIAGNOSTICS['RADIUSTESTS']['UDP-hosts'][$probeindex])) {
869
            $this->UDP_reachability_executed = RADIUSTests::RETVAL_NOTCONFIGURED;
870
            return RADIUSTests::RETVAL_NOTCONFIGURED;
871
        }
872
        // if we need client certs but don't have one, return
873
        if (($eaptype == \core\common\EAP::EAPTYPE_ANY || $eaptype == \core\common\EAP::EAPTYPE_TLS) && $clientcertdata === NULL) {
874
            $this->UDP_reachability_executed = RADIUSTests::RETVAL_NOTCONFIGURED;
875
            return RADIUSTests::RETVAL_NOTCONFIGURED;
876
        }
877
        // if we don't have a string for outer EAP method name, give up
878
        if (!isset($eapText['OUTER'])) {
879
            $this->UDP_reachability_executed = RADIUSTests::RETVAL_NOTCONFIGURED;
880
            return RADIUSTests::RETVAL_NOTCONFIGURED;
881
        }
882
        // we will need a config blob for wpa_supplicant, in a temporary directory
883
        $temporary = $this->createTemporaryDirectory('test');
884
        $tmpDir = $temporary['dir'];
885
        chdir($tmpDir);
886
        $this->loggerInstance->debug(4, "temp dir: $tmpDir\n");
887
        if ($clientcertdata !== NULL) {
888
            file_put_contents($tmpDir . "/client.p12", $clientcertdata);
889
        }
890
        $testresults = [];
891
        // initialise the sub-array for cleaner parsing
892
        $testresults['cert_oddities'] = [];
893
        // execute RADIUS/EAP converation
894
        $runtime_results = $this->executeEapolTest($tmpDir, $probeindex, $eaptype, $innerUser, $password, $opnameCheck, $frag);
895
        $testresults['time_millisec'] = $runtime_results['time'];
896
        $packetflow_orig = $runtime_results['output'];
897
        $radiusResult = $this->checkRadiusPacketFlow($testresults, $packetflow_orig);
898
        $negotiatedEapType = $this->wasEapTypeNegotiated($testresults, $packetflow_orig);
899
        // now let's look at the server cert+chain, if we got a cert at all
900
        // that's not the case if we do EAP-pwd or could not negotiate an EAP method at
901
        // all
902
        if (
903
                $eaptype != \core\common\EAP::EAPTYPE_PWD &&
904
                (($radiusResult == RADIUSTests::RETVAL_CONVERSATION_REJECT && $negotiatedEapType) || $radiusResult == RADIUSTests::RETVAL_OK)
905
        ) {
906
            $bundle = $this->extractIncomingCertsfromEAP($testresults, $tmpDir);
907
// FOR OWN REALMS check:
908
// 1) does the incoming chain have a root in one of the configured roots
909
//    if not, this is a signficant configuration error
910
// return this with one or more of the CERTPROB_ constants (see defs)
911
// TRUST_ROOT_NOT_REACHED
912
// TRUST_ROOT_REACHED_ONLY_WITH_OOB_INTERMEDIATES
913
// then check the presented names
914
// check intermediate ca cert properties
915
// check trust chain for completeness
916
// works only for thorough checks, not shallow, so:
917
            $intermOdditiesCAT = [];
918
            $verifyResult = 0;
919
920
            if ($this->opMode == self::RADIUS_TEST_OPERATION_MODE_THOROUGH) {
921
                $verifyResult = $this->thoroughChainChecks($testresults, $intermOdditiesCAT, $tmpDir, $bundle["SERVERCERT"], $bundle["INTERMEDIATE_CA"], $bundle["INTERMEDIATE_CRL"]);
922
                $this->thoroughNameChecks($bundle["SERVERCERT"], $testresults);
923
            }
924
925
            $testresults['cert_oddities'] = array_merge($testresults['cert_oddities'], $bundle["INTERMEDIATE_OBSERVED_ODDITIES"]);
926
            if (in_array(RADIUSTests::CERTPROB_OUTSIDE_VALIDITY_PERIOD, $intermOdditiesCAT) && $verifyResult == 3) {
927
                $key = array_search(RADIUSTests::CERTPROB_OUTSIDE_VALIDITY_PERIOD, $intermOdditiesCAT);
928
                $intermOdditiesCAT[$key] = RADIUSTests::CERTPROB_OUTSIDE_VALIDITY_PERIOD_WARN;
929
            }
930
931
            $testresults['cert_oddities'] = array_merge($testresults['cert_oddities'], $intermOdditiesCAT);
932
933
// mention trust chain failure only if no expired cert was in the chain; otherwise path validation will trivially fail
934
            if (in_array(RADIUSTests::CERTPROB_OUTSIDE_VALIDITY_PERIOD, $testresults['cert_oddities'])) {
935
                $this->loggerInstance->debug(4, "Deleting trust chain problem report, if present.");
936
                if (($key = array_search(RADIUSTests::CERTPROB_TRUST_ROOT_NOT_REACHED, $testresults['cert_oddities'])) !== false) {
937
                    unset($testresults['cert_oddities'][$key]);
938
                }
939
                if (($key = array_search(RADIUSTests::CERTPROB_TRUST_ROOT_REACHED_ONLY_WITH_OOB_INTERMEDIATES, $testresults['cert_oddities'])) !== false) {
940
                    unset($testresults['cert_oddities'][$key]);
941
                }
942
            }
943
        }
944
        $this->UDP_reachability_result[$probeindex] = $testresults;
945
        $this->UDP_reachability_executed = $radiusResult;
946
        return $radiusResult;
947
    }
948
949
    public function setOuterIdentity($id) {
950
        $this->outerUsernameForChecks = $id;
951
    }
952
    
953
    public function consolidateUdpResult($host) {
954
        $ret = [];
955
        $serverCert = [];
956
        $udpResult = $this->UDP_reachability_result[$host];
957
        if (isset($udpResult['certdata']) && count($udpResult['certdata'])) {
958
            foreach ($udpResult['certdata'] as $certdata) {
959
                if ($certdata['type'] != 'server' && $certdata['type'] != 'totally_selfsigned') {
960
                    continue;
961
                }
962
                if (isset($certdata['extensions'])) {
963
                    foreach ($certdata['extensions'] as $k => $v) {
964
                        $certdata['extensions'][$k] = iconv('UTF-8', 'UTF-8//IGNORE', $certdata['extensions'][$k]);
965
                    }
966
                }
967
                $serverCert = [
968
                    'subject' => $this->printDN($certdata['subject']),
969
                    'issuer' => $this->printDN($certdata['issuer']),
970
                    'validFrom' => $this->printTm($certdata['validFrom_time_t']),
971
                    'validTo' => $this->printTm($certdata['validTo_time_t']),
972
                    'serialNumber' => $certdata['serialNumber'] . sprintf(" (0x%X)", $certdata['serialNumber']),
973
                    'sha1' => $certdata['sha1'],
974
                    'extensions' => $certdata['extensions']
975
                ];
976
            }
977
        }
978
        $ret['server_cert'] = $serverCert;
979
        $ret['server'] = 0;
980
        if (isset($udpResult['incoming_server_names'][0])) {
981
            $ret['server'] = sprintf(_("Connected to %s."), $udpResult['incoming_server_names'][0]);
982
        }
983
        $ret['level'] = \core\common\Entity::L_OK;
984
        $ret['time_millisec'] = sprintf("%d", $udpResult['time_millisec']);
985
        if (empty($udpResult['cert_oddities'])) {
986
            $ret['message'] = _("<strong>Test successful</strong>: a bidirectional RADIUS conversation with multiple round-trips was carried out, and ended in an Access-Reject as planned.");
987
            return $ret;
988
        }
989
990
        $ret['message'] = _("<strong>Test partially successful</strong>: a bidirectional RADIUS conversation with multiple round-trips was carried out, and ended in an Access-Reject as planned. Some properties of the connection attempt were sub-optimal; the list is below.");
991
        $ret['cert_oddities'] = [];
992
        foreach ($udpResult['cert_oddities'] as $oddity) {
993
            $o = [];
994
            $o['code'] = $oddity;
995
            $o['message'] = isset($this->returnCodes[$oddity]["message"]) && $this->returnCodes[$oddity]["message"] ? $this->returnCodes[$oddity]["message"] : $oddity;
996
            $o['level'] = $this->returnCodes[$oddity]["severity"];
997
            $ret['level'] = max($ret['level'], $this->returnCodes[$oddity]["severity"]);
998
            $ret['cert_oddities'][] = $o;
999
        }
1000
1001
        return $ret;
1002
    }
1003
1004
}
1005