Test Failed
Push — master ( 889cd8...f87563 )
by Tomasz
09:24
created

DeviceXML::scaleLogo()   B

Complexity

Conditions 6
Paths 11

Size

Total Lines 35
Code Lines 26

Duplication

Lines 0
Ratio 0 %

Importance

Changes 1
Bugs 0 Features 1
Metric Value
eloc 26
c 1
b 0
f 1
dl 0
loc 35
rs 8.8817
cc 6
nc 11
nop 2
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
/**
24
 * This file defines an abstract class used for generic XML
25
 * devices
26
 * actual modules only define available EAP types.
27
 *
28
 * @author Maja Gorecka-Wolniewicz <[email protected]>
29
 * @author Tomasz Wolniewicz <[email protected]>
30
 *
31
 * @package ModuleWriting
32
 */
33
34
namespace devices\eap_config;
35
36
use Exception;
37
38
/**
39
 * This class implements full functionality of the generic XML device
40
 * the only function of the extensions of this class is to specify
41
 * supported EAP methods.
42
 * Instead of specifying supported EAPS an extension can set $all_eaps to true
43
 * this will cause the installer to configure all EAP methods supported by 
44
 * the current profile and declared by the given device.
45
 */
46
abstract class DeviceXML extends \core\DeviceConfig
47
{
48
    
49
    /**
50
     *  @var array $AuthMethodElements is used to limit
51
     *  XML elements present within ServerSideCredentials and
52
     *  ClientSideCredentials to ones which are relevant
53
     *  for a given EAP method.
54
     *  @var array of XLM element names which are allowed
55
     *  EAP method names are defined in core/EAP.php
56
     */
57
    private $authMethodElements = [
58
        'server' => [
59
            \core\common\EAP::TLS => ['CA', 'ServerID'],
60
            \core\common\EAP::FAST => ['CA', 'ServerID'],
61
            \core\common\EAP::PEAP => ['CA', 'ServerID'],
62
            \core\common\EAP::TTLS => ['CA', 'ServerID'],
63
            \core\common\EAP::PWD => ['ServerID'],
64
        ],
65
        'client' => [
66
            \core\common\EAP::TLS => ['UserName', 'Password', 'ClientCertificate'],
67
            \core\common\EAP::NE_MSCHAP2 => ['UserName', 'Password', 'OuterIdentity', 'InnerIdentitySuffix', 'InnerIdentityHint'],
68
            \core\common\EAP::MSCHAP2 => ['UserName', 'Password', 'OuterIdentity', 'InnerIdentitySuffix', 'InnerIdentityHint'],
69
            \core\common\EAP::GTC => ['UserName', 'OneTimeToken'],
70
            \core\common\EAP::NE_PAP => ['UserName', 'Password', 'OuterIdentity', 'InnerIdentitySuffix', 'InnerIdentityHint'],
71
            \core\common\EAP::NE_SILVERBULLET => ['UserName', 'ClientCertificate', 'OuterIdentity'],
72
            \core\common\EAP::NONE => [],
73
        ]
74
    ];
75
76
    /**
77
     * construct the device
78
     */
79
    public function __construct()
80
    {
81
        parent::__construct();
82
    }
83
84
    /**
85
     * $langScope can be 'global' when all lang and all lang-specific information
86
     * is dumped or 'single' when only the selected lang (and defaults) are passed
87
     * 
88
     * @var string
89
     */
90
    public $langScope;
91
92
    /**
93
     * whether all EAP types should be included in the file or only the 
94
     * preferred one
95
     * 
96
     * @var boolean
97
     */
98
    public $allEaps = false;
99
100
    /**
101
     * vendor-specific additional information, this is nit yest fully
102
     * implemented due to lack of use cases.
103
     * 
104
     * @var array
105
     */
106
    public $VendorSpecific;
107
    
108
    /**
109
     * A flag to preserve backwards compatibility for eduroamCAT application
110
     */
111
    public $eduroamCATcompatibility = false; 
112
    public $singleEAPProvider = false;
113
114
    private $eapId;
115
    private $namespace;
116
    private $providerInfo;
117
    private $authMethodsList;
118
    
119
    /**
120
     * create HTML code explaining the installer
121
     * 
122
     * @return string
123
     */
124
    public function writeDeviceInfo()
125
    {
126
        \core\common\Entity::intoThePotatoes();
127
        $out = "<p>";
128
        $out .= sprintf(_("This is a generic configuration file in the IETF <a href='%s'>EAP Metadata -00</a> XML format."), "https://tools.ietf.org/html/draft-winter-opsawg-eap-metadata-00");
129
        \core\common\Entity::outOfThePotatoes();
130
        return $out;
131
    }
132
133
    /**
134
     * create the actual XML file
135
     * 
136
     * @return string filename of the generated installer
137
     * @throws Exception
138
     *
139
     */
140
    public function writeInstaller()
141
    {
142
        \core\common\Entity::intoThePotatoes();
143
        $rootname = 'EAPIdentityProviderList';
144
        $dom = new \DOMDocument('1.0', 'utf-8');
145
        $root = $dom->createElement($rootname);
146
        $dom->appendChild($root);
147
        $ns = $dom->createAttributeNS( 'http://www.w3.org/2001/XMLSchema-instance', 'xsi:noNamespaceSchemaLocation' );
148
        $ns->value = "eap-metadata.xsd";
149
        $root->appendChild($ns);
150
        $this->openRoamingToU = sprintf(_("I have read and agree to OpenRoaming Terms of Use at %s."), "https://wballiance.com/openroaming/toc-2020/");
151
        foreach ($this->languageInstance->getAllTranslations("I have read and agree to OpenRoaming Terms of Use at %s", "device") as $lang => $message) {
152
            $this->openRoamingToUArray[$lang] = sprintf($message, "https://wballiance.com/openroaming/toc-2020/");
153
        }
154
        
155
        if (empty($this->attributes['internal:realm'][0])) {
156
            $this->eapId = 'undefined';
157
            $this->namespace = 'urn:undefined';
158
        } else {
159
            $this->eapId = $this->attributes['internal:realm'][0];
160
            $this->namespace = 'urn:RFC4282:realm';
161
        }
162
        
163
        $this->authMethodsList = $this->getAuthMethodsList();
164
        $this->loggerInstance->debug(5, $this->attributes['internal:networks'], "NETWORKS:", "\n");
165
        /*
166
         * This approach is forced by geteduroam compatibility. We pack all networks into a single Provider
167
         * with the exception of the openroaming one which we pack separately.
168
         */
169
        
170
        if ($this->singleEAPProvider === true) {
171
            /*
172
             * if "condition" is set to openroaming, OpenRoaming terms of use must be mentioned
173
             * unless the preagreed is set for openroaming
174
             * if "ask" is set then we generate a separate OR profile which needs to contain the OR ToU
175
             * the ToU is not needed in the eduroam-only profile
176
             */
177
            $ssids = [];
178
            $ois = [];
179
            $orNetwork = [];
180
            foreach ($this->attributes['internal:networks'] as $netName => $netDefinition) {
181
                if ($netDefinition['condition'] === 'internal:openroaming' &&
182
                        $this->attributes['internal:openroaming']) {
183
                    $this->setORtou();
184
                    if (preg_match("/^ask/",$this->attributes['media:openroaming'][0])) {
185
                        $orNetwork = $netDefinition;
186
                        continue;                        
187
                    }
188
                }
189
                foreach ($netDefinition['ssid'] as $ssid) {
190
                    $ssids[] = $ssid;
191
                }
192
                foreach ($netDefinition['oi'] as $oi) {
193
                    $ois[] = $oi;
194
                }
195
            }
196
197
            if (!empty($orNetwork)) {
198
                $this->addORtou = false;
199
            }
200
            $this->providerInfo = $this->getProviderInfo();
201
            
202
            if (!empty($ssids) || !empty($ois)) {
203
                \core\DeviceXMLmain::marshalObject($dom, $root, 'EAPIdentityProvider', $this->eapIdp($ssids, $ois));
204
            }
205
            
206
            if (!empty($orNetwork)) {
207
                // here we need to add the Tou unless preagreed is set
208
                $this->setORtou();
209
                $this->providerInfo = $this->getProviderInfo();
210
                \core\DeviceXMLmain::marshalObject($dom, $root, 'EAPIdentityProvider', $this->eapIdp($orNetwork['ssid'], $orNetwork['oi']));
211
            }
212
        } else {
213
214
            foreach ($this->attributes['internal:networks'] as $netName => $netDefinition) {
215
                if ($netDefinition['condition'] === 'internal:openroaming' &&
216
                        $this->attributes['internal:openroaming']) {
217
                    $this->setORtou();
218
                } else {
219
                    $this->addORtou = false;
220
                }
221
                $this->providerInfo = $this->getProviderInfo();
222
                $ssids = $netDefinition['ssid'];
223
                $ois = $netDefinition['oi'];
224
                if (!empty($ssids) || !empty($ois)) {
225
                    \core\DeviceXMLmain::marshalObject($dom, $root, 'EAPIdentityProvider', $this->eapIdp($ssids, $ois));
226
                }
227
            }
228
        }
229
        
230
        if ($dom->schemaValidate(ROOT.'/devices/eap_config/eap-metadata.xsd') === FALSE) {
231
            throw new Exception("Schema validation failed for eap-metadata");
232
        }
233
234
        $dom->formatOutput = true;
235
        file_put_contents($this->installerBasename.'.eap-config', $dom->saveXML($dom));
236
        \core\common\Entity::outOfThePotatoes();
237
        return($this->installerBasename.'.eap-config');
238
    }
239
    
240
    private function setORtou() {
241
        if (preg_match("/preagreed/",$this->attributes['media:openroaming'][0])) {
242
            $this->addORtou = false;
243
        } else {
244
            $this->addORtou = true;
245
        }
246
    }
247
    
248
    /**
249
     * determines the inner authentication. Is it EAP, and which mechanism is used to convey actual auth data
250
     * @param array $eap the EAP type for which we want to get the inner auth
251
     * @return array
252
     */    
253
    private function eapIdp($ssids, $oids)
254
    {
255
        $eapIdp = new \core\DeviceXMLmain();
256
        $eapIdp->setAttribute('version', '1');
257
        if ($this->langScope === 'single') {
258
            $eapIdp->setAttribute('lang', $this->languageInstance->getLang());
259
        }
260
        $eapIdp->setAttribute('ID', $this->eapId);
261
        $eapIdp->setAttribute('namespace', $this->namespace);
262
        $authMethods = new \core\DeviceXMLmain();
263
        $authMethods->setChild('AuthenticationMethod', $this->authMethodsList);
264
        $eapIdp->setChild('AuthenticationMethods', $authMethods);
265
        $eapIdp->setChild('CredentialApplicability', $this->getCredentialApplicability($ssids,$oids));
266
// TODO   $eap_idp->setChild('ValidUntil',$this->getValidUntil());
267
        $eapIdp->setChild('ProviderInfo', $this->providerInfo);
268
// TODO   $eap_idp->setChild('VendorSpecific',$this->getVendorSpecific());
269
        return($eapIdp);
0 ignored issues
show
Bug Best Practice introduced by
The expression return $eapIdp returns the type core\DeviceXMLmain which is incompatible with the documented return type array.
Loading history...
270
    }
271
272
    /**
273
     * determines the inner authentication. Is it EAP, and which mechanism is used to convey actual auth data
274
     * @param array $eap the EAP type for which we want to get the inner auth
275
     * @return array
276
     */  
277
    private function innerAuth($eap)
278
    {
279
        $out = [];
280
        $out['EAP'] = 0;
281
        switch ($eap["INNER"]) {
282
            case \core\common\EAP::NE_MSCHAP2:
283
                if ($this->eduroamCATcompatibility === TRUE) {
284
                    $out['METHOD'] = \core\common\EAP::MSCHAP2;
285
                    $out['EAP'] = 1;
286
                } else {
287
                    $out['METHOD'] = $eap["INNER"];
288
                }
289
                break;
290
            case \core\common\EAP::NE_SILVERBULLET:
291
                $out['METHOD'] = \core\common\EAP::NONE;
292
                break;
293
            default:
294
                $out['METHOD'] = $eap["INNER"];
295
                break;
296
        }
297
        // override if there is an inner EAP
298
        if ($eap["INNER"] > 0) { // there is an inner EAP method
299
            $out['EAP'] = 1;
300
        }
301
        return $out;
302
    }
303
    
304
    /**
305
     * 
306
     * @param string $attrName the attribute name
307
     * @return array of values for this attribute
308
     */
309
    private function getSimpleMLAttribute($attrName)
310
    {
311
        if (empty($this->attributes[$attrName][0])) {
312
            return([]);
313
        }
314
        $attributeList = $this->attributes[$attrName];
315
        $objs = [];
316
        if ($this->langScope === 'global') {
317
            foreach ($attributeList['langs'] as $language => $value) {
318
                $language = ($language === 'C' ? 'any' : $language);
319
                $obj = new \core\DeviceXMLmain();
320
                $obj->setValue($value);
321
                $obj->setAttributes(['lang' => $language]);
322
                $objs[] = $obj;
323
            }
324
        } else {
325
            $objs[] = $attributeList[0];
326
        }
327
        return($objs);
328
    }
329
    
330
    /**
331
     * constructs the name of the institution and puts it into the XML.
332
     * consists of the best-language-match inst name, and if the inst has more 
333
     * than one profile also the best-language-match profile name
334
     * 
335
     * @return \core\DeviceXMLmain[]
336
     */
337
    private function getDisplayName()
338
    {
339
        $attr = $this->attributes;
340
        $objs = [];
341
        if ($this->langScope === 'global') {
342
            $instNameLangs = $attr['general:instname']['langs'];
343
            if ($attr['internal:profile_count'][0] > 1) {
344
                $profileNameLangs = $attr['profile:name']['langs'];
345
            }
346
            foreach ($instNameLangs as $language => $value) {
347
                $language = ($language === 'C' ? 'any' : $language);
348
                $displayname = new \core\DeviceXMLmain();
349
                if (isset($profileNameLangs)) {
350
                    $langOrC = isset($profileNameLangs[$language]) ? $profileNameLangs[$language] : $profileNameLangs['C'];
351
                    $value .= ' - '.$langOrC;
352
                }
353
                $displayname->setValue($value);
354
                $displayname->setAttributes(['lang' => $language]);
355
                $objs[] = $displayname;
356
            }
357
        } else {
358
            $displayname = new \core\DeviceXMLmain();
359
            $value = $attr['general:instname'][0];
360
            if ($attr['internal:profile_count'][0] > 1) {
361
                $value .= ' - '.$attr['profile:name'][0];
362
            }
363
            $displayname->setValue($value);
364
            $objs[] = $displayname;
365
        }
366
        return $objs;
367
    }
368
369
    /**
370
     * retrieves the provider logo and puts it into the XML structure
371
     * 
372
     * @return \core\DeviceXMLmain
373
     */
374
    private function getProviderLogo()
375
    {
376
        $attr = $this->attributes;
377
        if (isset($attr['general:logo_file'][0])) {
378
            $rawLogoBlob = $attr['general:logo_file'][0];
379
            $logoMime= $attr['internal:logo_file'][0]['mime'];
380
            [$scaledBlob, $scaledMime] = $this->scaleLogo($rawLogoBlob, $logoMime);
381
            $logoString = base64_encode($scaledBlob);
382
            $providerlogo = new \core\DeviceXMLmain();
383
            $providerlogo->setAttributes(['mime' => 'image/'.$scaledMime, 'encoding' => 'base64']);
384
            $providerlogo->setValue($logoString);
385
            return $providerlogo;
386
        }
387
        return NULL;
388
    }
389
    
390
    /**
391
     * Scales a logo to the desired byte imag size if necessary.
392
     * If the image size is below tha alowed maximum, nothing is done;
393
     * if the image is larger than we run a series of scaling iterations to sizes
394
     * specified in $maxPixelSize and the moment we manage to end up below the $maxByte
395
     * we returm the scaled blob - we always use png as the output format since it seems
396
     * to behave best in scaling.
397
     * 
398
     * @param string $blob the image data
399
     * @param string $mime the mime type of the original image
400
     * @return array the scaled blob, the resulting mime type
401
     */
402
    private function scaleLogo($blob, $mime)
403
    {
404
        $maxByte = 1024*50;
405
        $maxPixelSize = [400,300,200,100];
406
        // start with the actual file size
407
        $logoSize = strlen($blob);
408
        \core\common\Logging::debug_s(4, $logoSize, "Logo file size: ", "\n");
409
        if ($logoSize <= $maxByte) {
410
            return [$blob, $mime];
411
        }
412
        // resize logo if necessary
413
        if (class_exists('\\Gmagick')) { 
414
            $imageObject = new \Gmagick(); 
415
        } else {
416
            $imageObject = new \Imagick();
417
        }
418
        $imageObject->readImageBlob($blob);       
419
        $imageSize = $imageObject->getImageGeometry();
0 ignored issues
show
Bug introduced by
The method getImageGeometry() does not exist on Gmagick. ( Ignorable by Annotation )

If this is a false-positive, you can also ignore this issue in your code via the ignore-call  annotation

419
        /** @scrutinizer ignore-call */ 
420
        $imageSize = $imageObject->getImageGeometry();

This check looks for calls to methods that do not seem to exist on a given type. It looks for the method on the type itself as well as in inherited classes or implemented interfaces.

This is most likely a typographical error or the method has been renamed.

Loading history...
420
        \core\common\Logging::debug_s(4, $imageSize, "Input logo pixel size: ","\n");        
421
        foreach ($maxPixelSize as $size) {
422
            $tmpImage = $imageObject;
423
            $tmpImage->setImageFormat('PNG');
424
            \core\common\Logging::debug_s(4, $size, "Reducing size to: ", "\n");
425
            if ($imageSize['width'] > $imageSize['height']) {
426
                $tmpImage->thumbnailImage($size, 0);
427
            } else {
428
                $tmpImage->thumbnailImage(0, $size);
429
            }
430
            $outBlob = $tmpImage->getImageBlob();
0 ignored issues
show
Bug introduced by
The method getImageBlob() does not exist on Gmagick. ( Ignorable by Annotation )

If this is a false-positive, you can also ignore this issue in your code via the ignore-call  annotation

430
            /** @scrutinizer ignore-call */ 
431
            $outBlob = $tmpImage->getImageBlob();

This check looks for calls to methods that do not seem to exist on a given type. It looks for the method on the type itself as well as in inherited classes or implemented interfaces.

This is most likely a typographical error or the method has been renamed.

Loading history...
431
            if (strlen($outBlob) <= $maxByte) {
432
                break;
433
            }
434
        }
435
        \core\common\Logging::debug_s(4, strlen($outBlob), "Scaled size: ", "\n");
0 ignored issues
show
Comprehensibility Best Practice introduced by
The variable $outBlob seems to be defined by a foreach iteration on line 421. Are you sure the iterator is never empty, otherwise this variable is not defined?
Loading history...
436
        return [$outBlob, 'png'];
437
    }
438
439
    /**
440
     * retrieves provider information and puts it into the XML structure.
441
     * contains the profile description and the ToU file, if any
442
     * 
443
     * @return \core\DeviceXMLmain
444
     */
445
    private function getProviderInfo()
446
    {
447
        $providerinfo = new \core\DeviceXMLmain();
448
        $providerinfo->setChild('DisplayName', $this->getDisplayName());
449
        $providerinfo->setChild('Description', $this->getSimpleMLAttribute('profile:description'));
450
        $providerinfo->setChild('ProviderLocation', $this->getProviderLocation());
451
        $providerinfo->setChild('ProviderLogo', $this->getProviderLogo());
452
        $providerinfo->setChild('TermsOfUse', $this->getProviderTou(), null, 'cdata');
453
        $providerinfo->setChild('Helpdesk', $this->getHelpdesk());
454
        return $providerinfo; 
455
    }
456
    
457
    private function getProviderTou() {
458
        $standardTou = $this->getSimpleMLAttribute('support:info_file');
459
        if ($this->addORtou === false) {
460
            return $standardTou;
461
        }
462
        $out = [];
463
        if ($this->langScope === 'global') {
464
            foreach ($standardTou as $touObj) {
465
                $tou = $touObj->getValue();
466
                $lngAttr = $touObj->getAttributes();
467
                $lng = $lngAttr['lang'] === 'any' ? \config\Master::APPEARANCE['defaultlocale'] : $lngAttr['lang'];
468
                $tou .= "\n".$this->openRoamingToUArray[$lng];
469
                $touObj->setValue($tou);
470
                $out[] =  $touObj;
471
            } 
472
        } else {
473
            $tou = $standardTou[0];
474
            $tou .= "\n".$this->openRoamingToU;
475
            $out = [$tou];
476
        }
477
        return $out;
478
    }
479
480
    /**
481
     * retrieves the location information and puts it into the XML structure
482
     * 
483
     * @return \core\DeviceXMLmain[]
484
     */
485
    private function getProviderLocation()
486
    {
487
        $attr = $this->attributes;
488
        if (isset($attr['general:geo_coordinates'])) {
489
            $attrCoordinates = $attr['general:geo_coordinates'];
490
            $location = [];
491
            foreach ($attrCoordinates as $a) {
492
                $providerlocation = new \core\DeviceXMLmain();
493
                $b = json_decode($a, true);
494
                $providerlocation->setChild('Longitude', $b['lon']);
495
                $providerlocation->setChild('Latitude', $b['lat']);
496
                $location[] = $providerlocation;
497
            }           
498
            return $location;
499
        }
500
        return NULL;
501
    }
502
503
    /**
504
     * retrieves helpdesk contact information and puts it into the XML structure
505
     * 
506
     * @return \core\DeviceXMLmain
507
     */
508
    private function getHelpdesk()
509
    {
510
        $helpdesk = new \core\DeviceXMLmain();
511
        $helpdesk->setChild('EmailAddress', $this->getSimpleMLAttribute('support:email'));
512
        $helpdesk->setChild('WebAddress', $this->getSimpleMLAttribute('support:url'));
513
        $helpdesk->setChild('Phone', $this->getSimpleMLAttribute('support:phone'));
514
        return $helpdesk;
515
    }
516
517
    /**
518
     * determine where this credential should be applicable
519
     * 
520
     * @return \core\DeviceXMLmain
521
     */
522
    private function getCredentialApplicability($ssids, $oids)
523
    {
524
        $setWired = isset($this->attributes['media:wired'][0]) && 
525
                $this->attributes['media:wired'][0] == 'on' ? 1 : 0;        
526
        $credentialapplicability = new \core\DeviceXMLmain();
527
        $ieee80211s = [];
528
        foreach ($ssids as $ssid) {
529
            $ieee80211 = new \core\DeviceXMLmain();
530
            $ieee80211->setChild('SSID', $ssid);
531
            $ieee80211->setChild('MinRSNProto', 'CCMP');
532
            $ieee80211s[] = $ieee80211;
533
        }
534
        foreach ($oids as $oid) {
535
            $ieee80211 = new \core\DeviceXMLmain();
536
            $ieee80211->setChild('ConsortiumOID', $oid);
537
            $ieee80211s[] = $ieee80211;
538
        }
539
        $credentialapplicability->setChild('IEEE80211', $ieee80211s);
540
        if ($setWired) {
541
            $credentialapplicability->setChild('IEEE8023', '');
542
        }
543
        return $credentialapplicability;
544
    }
545
546
    /**
547
     * retrieves the parameters needed for the given EAP method and creates
548
     * appropriate nodes in the XML structure for them
549
     * 
550
     * @param array $eap the EAP type in question
551
     * @return array a recap of the findings
552
     */
553
    private function getAuthenticationMethodParams($eap)
554
    {
555
        $inner = $this->innerAuth($eap);
556
        $outerMethod = $eap["OUTER"];
557
558
        if (isset($inner["METHOD"]) && $inner["METHOD"]) {
559
            $innerauthmethod = new \core\DeviceXMLmain();
560
            $typeOfInner = ($inner["EAP"] ? 'EAPMethod' : 'NonEAPAuthMethod');
561
            $eapmethod = new \core\DeviceXMLmain();
562
            $eapmethod->setChild('Type', abs($inner['METHOD']));
563
            $innerauthmethod->setChild($typeOfInner, $eapmethod);
564
            return ['inner_method' => $innerauthmethod, 'methodID' => $outerMethod, 'inner_methodID' => $inner['METHOD']];
565
        } else {
566
            return ['inner_method' => 0, 'methodID' => $outerMethod, 'inner_methodID' => 0];
567
        }
568
    }
569
570
    /**
571
     * sets the server-side credentials for a given EAP type
572
     * 
573
     * @param \devices\XML\Type $eaptype the EAP type
0 ignored issues
show
Bug introduced by
The type devices\XML\Type was not found. Maybe you did not declare it correctly or list all dependencies?

The issue could also be caused by a filter entry in the build configuration. If the path has been excluded in your configuration, e.g. excluded_paths: ["lib/*"], you can move it to the dependency path list as follows:

filter:
    dependency_paths: ["lib/*"]

For further information see https://scrutinizer-ci.com/docs/tools/php/php-scrutinizer/#list-dependency-paths

Loading history...
574
     * @return \core\DeviceXMLmain
575
     */
576
    private function getServerSideCredentials($eap)
577
    {
578
        $attr = $this->attributes;
579
        $children = $this->authMethodElements['server'][$eap];
580
        $serversidecredential = new \core\DeviceXMLmain();
581
// Certificates and server names
582
        $cAlist = [];
583
        $attrCaList = $attr['internal:CAs'][0];
584
        foreach ($attrCaList as $ca) {
585
            /* possibly we will want to stop sending server certificates in the future
586
            if ($ca['full_details']['type'] == 'server') {
587
                continue;
588
            }
589
             * 
590
             */
591
            $caObject = new \core\DeviceXMLmain();
592
            $caObject->setValue(base64_encode($ca['der']));
593
            $caObject->setAttributes(['format' => 'X.509', 'encoding' => 'base64']);
594
            $cAlist[] = $caObject;
595
        }
596
        $serverids = [];
597
        $servers = $attr['eap:server_name'];
598
        foreach ($servers as $server) {
599
            $serverid = new \core\DeviceXMLmain();
600
            $serverid->setValue($server);
601
            $serverids[] = $serverid;
602
        }
603
        if (in_array('CA', $children)) {
604
            $serversidecredential->setChild('CA', $cAlist);
605
        }
606
        if (in_array('ServerID', $children)) {
607
            $serversidecredential->setChild('ServerID', $serverids);
608
        }
609
        return $serversidecredential;
610
    }
611
612
    /**
613
     * sets the realm information for the client-side credential
614
     * 
615
     * @param \core\DeviceXMLmain $clientsidecredential the ClientSideCredential to which the realm info is to be added
616
     * @return void
617
     */
618
    private function setClientSideRealm($clientsidecredential)
619
    {
620
        $attr = $this->attributes;
621
        $realm = \core\common\Entity::getAttributeValue($attr, 'internal:realm', 0);
622
        if ($realm === NULL) {
623
            return;
624
        }
625
        if (\core\common\Entity::getAttributeValue($attr, 'internal:verify_userinput_suffix', 0) !== 1) {
626
            return;
627
        }
628
        $clientsidecredential->setChild('InnerIdentitySuffix', $realm);
629
        if (\core\common\Entity::getAttributeValue($attr, 'internal:hint_userinput_suffix', 0) === 1) {
630
            $clientsidecredential->setChild('InnerIdentityHint', 'true');
631
        }
632
    }
633
634
    /**
635
     * sets the client certificate
636
     * 
637
     * @return \core\DeviceXMLmain
638
     */
639
    private function getClientCertificate()
640
    {
641
        $clientCertificateObject = new \core\DeviceXMLmain();
642
        $clientCertificateObject->setValue(base64_encode($this->clientCert["certdata"]));
643
        $clientCertificateObject->setAttributes(['format' => 'PKCS12', 'encoding' => 'base64']);
644
        return $clientCertificateObject;
645
    }
646
647
    /**
648
     * sets the client-side credentials for the given EAP type
649
     * 
650
     * @param array $eapParams the EAP parameters
651
     * @return \core\DeviceXMLmain
652
     */
653
    private function getClientSideCredentials($eap)
654
    {
655
        $children = $this->authMethodElements['client'][$eap];
656
        $clientsidecredential = new \core\DeviceXMLmain();
657
        $outerId = $this->determineOuterIdString();
658
        $this->loggerInstance->debug(5, $eap, "XMLOI:", "\n");
659
        if (in_array('OuterIdentity', $children)) {
660
            if ($outerId !== NULL) {
661
                $clientsidecredential->setChild('OuterIdentity', $outerId);
662
            }
663
        }
664
        $this->setClientSideRealm($clientsidecredential);
665
//        $clientsidecredential->setChild('EAPType', $eapParams['inner_methodID'] ? $eapParams['inner_methodID'] : $eapParams['methodID']);
666
667
        // Client Certificate
668
        if ($this->selectedEap == \core\common\EAP::EAPTYPE_SILVERBULLET) {
669
            $attr = $this->attributes;
670
            $outerId = \core\common\Entity::getAttributeValue($attr, 'internal:username', 0);
671
            $clientsidecredential->setChild('OuterIdentity', $outerId);
672
            $clientsidecredential->setChild('ClientCertificate', $this->getClientCertificate());
673
        }
674
        return $clientsidecredential;
675
    }
676
677
    /**
678
     * sets the EAP method
679
     * 
680
     * @param \devices\XML\Type $eaptype the EAP type XMLObject
681
     * @return \core\DeviceXMLmain
682
     */
683
    private function getEapMethod($eaptype)
684
    {
685
        $eapmethod = new \core\DeviceXMLmain();
686
        $eapmethod->setChild('Type', $eaptype);
687
        if (isset($this->VendorSpecific)) {
688
            $vendorspecifics = [];
689
            foreach ($this->VendorSpecific as $vs) {
690
                $vendorspecific = new \core\DeviceXMLmain();
691
                $vs['value']->addAttribute('xsi:noNamespaceSchemaLocation', "xxx.xsd");
692
                $vendorspecific->setValue($vs['value']);
693
                $vendorspecific->setAttributes(['vendor' => $vs['vendor']]);
694
                $vendorspecifics[] = $vendorspecific;
695
            }
696
            $eapmethod->setChild('VendorSpecific', $vendorspecifics);
697
        }
698
        return($eapmethod);
699
    }
700
701
    /**
702
     * determines the authentication method to use
703
     * 
704
     * @param array $eap the EAP methods, in array representation
705
     * @return \core\DeviceXMLmain
706
     */
707
    private function getAuthMethod($eap)
708
    {
709
        $authmethod = new \core\DeviceXMLmain();
710
        $eapParams = $this->getAuthenticationMethodParams($eap);
711
        $eaptype = new \core\DeviceXMLmain();
712
        $eaptype->setValue($eapParams['methodID']);
713
// Type
714
        $authmethod->setChild('EAPMethod', $this->getEapMethod($eaptype));
715
716
// ServerSideCredentials
717
        $authmethod->setChild('ServerSideCredential', $this->getServerSideCredentials($eap['OUTER']));
718
719
// ClientSideCredentials
720
        $authmethod->setChild('ClientSideCredential', $this->getClientSideCredentials($eap['INNER']));
721
722
        if ($eapParams['inner_method']) {
723
            $authmethod->setChild('InnerAuthenticationMethod', $eapParams['inner_method']);
724
        }
725
        return $authmethod;
726
    }
727
    
728
    private function getAuthMethodsList() {
729
        $methodList = [];
730
        if ($this->allEaps) {
731
            $eapmethods = [];
732
            foreach ($this->attributes['all_eaps'] as $eap) {
733
                $eapRep = $eap->getArrayRep();
734
                if (in_array($eapRep, $this->supportedEapMethods)) {
735
                    $eapmethods[] = $eapRep;
736
                }
737
            }
738
        } else {
739
            $eapmethods = [$this->selectedEap];
740
        }
741
        foreach ($eapmethods as $eap) {
742
            $methodList[] = $this->getAuthMethod($eap);
743
        }
744
        return $methodList;
745
    }
746
    
747
    private $openRoamingToUArray;
748
    private $openRoamingToU;
749
    private $addORtou = false;
750
751
}
752