Passed
Push — master ( d096df...9c6bda )
by Tomasz
09:00
created

DeviceXML::getCredentialApplicability()   B

Complexity

Conditions 7
Paths 32

Size

Total Lines 26
Code Lines 19

Duplication

Lines 0
Ratio 0 %

Importance

Changes 2
Bugs 0 Features 0
Metric Value
eloc 19
c 2
b 0
f 0
dl 0
loc 26
rs 8.8333
cc 7
nc 32
nop 0
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 fuction of the extenstions 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
        ]
73
    ];
74
75
    /**
76
     * construct the device
77
     */
78
    public function __construct()
79
    {
80
        parent::__construct();
81
    }
82
83
    /**
84
     * $langScope can be 'global' when all lang and all lang-specific information
85
     * is dumped or 'single' when only the selected lang (and defaults) are passed
86
     * NOTICE: 'global' is not yet supported
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
     * create HTML code explaining the installer
110
     * 
111
     * @return string
112
     */
113
    public function writeDeviceInfo()
114
    {
115
        \core\common\Entity::intoThePotatoes();
116
        $out = "<p>";
117
        $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");
118
        \core\common\Entity::outOfThePotatoes();
119
        return $out;
120
    }
121
122
    /**
123
     * create the actual XML file
124
     * 
125
     * @return string filename of the generated installer
126
     * @throws Exception
127
     *
128
     */
129
    public function writeInstaller()
130
    {
131
        \core\common\Entity::intoThePotatoes();
132
        $eapIdp = new \core\DeviceXMLmain();
133
        $eapIdp->setAttribute('version', '1');
134
        if ($this->langScope === 'single') {
135
            $eapIdp->setAttribute('lang', $this->languageInstance->getLang());
136
        }
137
        if (empty($this->attributes['internal:realm'][0])) {
138
            $eapIdp->setAttribute('ID', 'undefined');
139
            $namespace = 'urn:undefined';
140
        } else {
141
            $eapIdp->setAttribute('ID', $this->attributes['internal:realm'][0]);
142
            $namespace = 'urn:RFC4282:realm';
143
        }
144
        $eapIdp->setAttribute('namespace', $namespace);
145
        $authMethods = new \core\DeviceXMLmain();
146
        $authMethods->setChild('AuthenticationMethod', $this->getAuthMethodsList());
147
        $eapIdp->setChild('AuthenticationMethods', $authMethods);       
148
        $eapIdp->setChild('CredentialApplicability', $this->getCredentialApplicability());
149
// TODO   $eap_idp->setChild('ValidUntil',$this->getValidUntil());
150
        $eapIdp->setChild('ProviderInfo', $this->getProviderInfo());
151
// TODO   $eap_idp->setChild('VendorSpecific',$this->getVendorSpecific());
152
153
// Generate XML
154
        $rootname = 'EAPIdentityProviderList';
155
        $root = new \SimpleXMLElement("<?xml version=\"1.0\" encoding=\"utf-8\" ?><{$rootname} xmlns:xsi=\"http://www.w3.org/2001/XMLSchema-instance\" xsi:noNamespaceSchemaLocation=\"eap-metadata.xsd\"></{$rootname}>");
156
        \core\DeviceXMLmain::marshalObject($root, 'EAPIdentityProvider', $eapIdp);
157
        $dom = dom_import_simplexml($root)->ownerDocument;
158
        if ($dom->schemaValidate(ROOT.'/devices/eap_config/eap-metadata.xsd') === FALSE) {
159
            throw new Exception("Schema validation failed for eap-metadata");
160
        }
161
        $dom->formatOutput = true;
162
        file_put_contents($this->installerBasename.'.eap-config', $dom->saveXML());
163
        \core\common\Entity::outOfThePotatoes();
164
        return($this->installerBasename.'.eap-config');
165
    }
166
167
168
    /**
169
     * determines the inner authentication. Is it EAP, and which mechanism is used to convey actual auth data
170
     * @param array $eap the EAP type for which we want to get the inner auth
171
     * @return array
172
     */
173
    private function innerAuth($eap)
174
    {
175
        $out = [];
176
        $out['EAP'] = 0;
177
        // this is a hack - eduroamCAT does not handle NE_MSCHAP2 however
178
        // treats the inner NE_MSCHAP2 correctly wheb set to the EAP type
179
        switch ($eap["INNER"]) {
180
            case \core\common\EAP::NE_MSCHAP2:
181
                $out['METHOD'] = \core\common\EAP::MSCHAP2;
182
                $out['EAP'] = 1;
183
                break;
184
            case \core\common\EAP::NE_SILVERBULLET:
185
                $out['METHOD'] = \core\common\EAP::NONE;
186
                break;
187
            default:
188
                $out['METHOD'] = $eap["INNER"];
189
                break;
190
        }
191
        // override if there is an inner EAP
192
        if ($eap["INNER"] > 0) { // there is an inner EAP method
193
            $out['EAP'] = 1;
194
        }
195
        return $out;
196
    }
197
    
198
    /**
199
     * 
200
     * @param string $attrName the attribute name
201
     * @return array of values for this attribute
202
     */
203
    private function getSimpleMLAttribute($attrName)
204
    {
205
        if (empty($this->attributes[$attrName][0])) {
206
            return([]);
207
        }
208
        $attributeList = $this->attributes[$attrName];
209
        $objs = [];
210
        if ($this->langScope === 'global') {
211
            foreach ($attributeList['langs'] as $language => $value) {
212
                $language = ($language === 'C' ? 'any' : $language);
213
                $obj = new \core\DeviceXMLmain();
214
                $obj->setValue($value);
215
                $obj->setAttributes(['lang' => $language]);
216
                $objs[] = $obj;
217
            }
218
        } else {
219
            $objs[] = $attributeList[0];
220
        }
221
        return($objs);
222
    }
223
224
    /**
225
     * constructs the name of the institution and puts it into the XML.
226
     * consists of the best-language-match inst name, and if the inst has more 
227
     * than one profile also the best-language-match profile name
228
     * 
229
     * @return \core\DeviceXMLmain[]
230
     */
231
    private function getDisplayName()
232
    {
233
        $attr = $this->attributes;
234
        $objs = [];
235
        if ($this->langScope === 'global') {
236
            $instNameLangs = $attr['general:instname']['langs'];
237
            if ($attr['internal:profile_count'][0] > 1) {
238
                $profileNameLangs = $attr['profile:name']['langs'];
239
            }
240
            foreach ($instNameLangs as $language => $value) {
241
                $language = ($language === 'C' ? 'any' : $language);
242
                $displayname = new \core\DeviceXMLmain();
243
                if (isset($profileNameLangs)) {
244
                    $langOrC = isset($profileNameLangs[$language]) ? $profileNameLangs[$language] : $profileNameLangs['C'];
245
                    $value .= ' - '.$langOrC;
246
                }
247
                $displayname->setValue($value);
248
                $displayname->setAttributes(['lang' => $language]);
249
                $objs[] = $displayname;
250
            }
251
        } else {
252
            $displayname = new \core\DeviceXMLmain();
253
            $value = $attr['general:instname'][0];
254
            if ($attr['internal:profile_count'][0] > 1) {
255
                $value .= ' - '.$attr['profile:name'][0];
256
            }
257
            $displayname->setValue($value);
258
            $objs[] = $displayname;
259
        }
260
        return $objs;
261
    }
262
263
    /**
264
     * retrieves the provider logo and puts it into the XML structure
265
     * 
266
     * @return \core\DeviceXMLmain
267
     */
268
    private function getProviderLogo()
269
    {
270
        $attr = $this->attributes;
271
        if (isset($attr['general:logo_file'][0])) {
272
            $logoString = base64_encode($attr['general:logo_file'][0]);
273
            $logoMime = 'image/'.$attr['internal:logo_file'][0]['mime'];
274
            $providerlogo = new \core\DeviceXMLmain();
275
            $providerlogo->setAttributes(['mime' => $logoMime, 'encoding' => 'base64']);
276
            $providerlogo->setValue($logoString);
277
            return $providerlogo;
278
        }
279
        return NULL;
280
    }
281
282
    /**
283
     * retrieves provider information and puts it into the XML structure.
284
     * contains the profile description and the ToU file, if any
285
     * 
286
     * @return \core\DeviceXMLmain
287
     */
288
    private function getProviderInfo()
289
    {
290
        $providerinfo = new \core\DeviceXMLmain();
291
        $providerinfo->setChild('DisplayName', $this->getDisplayName());
292
        $providerinfo->setChild('Description', $this->getSimpleMLAttribute('profile:description'));
293
        $providerinfo->setChild('ProviderLocation', $this->getProviderLocation());
294
        $providerinfo->setChild('ProviderLogo', $this->getProviderLogo());
295
        $providerinfo->setChild('TermsOfUse', $this->getSimpleMLAttribute('support:info_file'));
296
        $providerinfo->setChild('Helpdesk', $this->getHelpdesk());
297
        return $providerinfo;
298
    }
299
300
    /**
301
     * retrieves the location information and puts it into the XML structure
302
     * 
303
     * @return \core\DeviceXMLmain[]
304
     */
305
    private function getProviderLocation()
306
    {
307
        $attr = $this->attributes;
308
        if (isset($attr['general:geo_coordinates'])) {
309
            $attrCoordinates = $attr['general:geo_coordinates'];
310
            $location = [];
311
            foreach ($attrCoordinates as $a) {
312
                $providerlocation = new \core\DeviceXMLmain();
313
                $b = json_decode($a, true);
314
                $providerlocation->setChild('Longitude', $b['lon']);
315
                $providerlocation->setChild('Latitude', $b['lat']);
316
                $location[] = $providerlocation;
317
            }           
318
            return $location;
319
        }
320
        return NULL;
321
    }
322
323
    /**
324
     * retrieves helpdesk contact information and puts it into the XML structure
325
     * 
326
     * @return \core\DeviceXMLmain
327
     */
328
    private function getHelpdesk()
329
    {
330
        $helpdesk = new \core\DeviceXMLmain();
331
        $helpdesk->setChild('EmailAddress', $this->getSimpleMLAttribute('support:email'));
332
        $helpdesk->setChild('WebAddress', $this->getSimpleMLAttribute('support:url'));
333
        $helpdesk->setChild('Phone', $this->getSimpleMLAttribute('support:phone'));
334
        return $helpdesk;
335
    }
336
337
    /**
338
     * determine where this credential should be applicable
339
     * 
340
     * @return \core\DeviceXMLmain
341
     */
342
    private function getCredentialApplicability()
343
    {
344
        $setWired = isset($this->attributes['media:wired'][0]) && 
345
                $this->attributes['media:wired'][0] == 'on' ? 1 : 0;        
346
        $ssids = $this->attributes['internal:SSID'];
347
        $oids = $this->attributes['internal:consortia'];
348
        $credentialapplicability = new \core\DeviceXMLmain();
349
        $ieee80211s = [];
350
        foreach ($ssids as $ssid => $ciph) {
351
            $ieee80211 = new \core\DeviceXMLmain();
352
            $ieee80211->setChild('SSID', $ssid);
353
            $ieee80211->setChild('MinRSNProto', $ciph == 'AES' ? 'CCMP' : 'TKIP');
354
            $ieee80211s[] = $ieee80211;
355
        }
356
        foreach ($oids as $oid) {
357
            $ieee80211 = new \core\DeviceXMLmain();
358
            $ieee80211->setChild('ConsortiumOID', $oid);
359
            $ieee80211s[] = $ieee80211;
360
        }
361
        $credentialapplicability->setChild('IEEE80211', $ieee80211s);
362
        if ($setWired) {
363
//            $ieee8023 = new \core\DeviceXMLmain();
364
//            $ieee8023->setChild('NetworkID', "1");
365
            $credentialapplicability->setChild('IEEE8023', '');
366
        }
367
        return $credentialapplicability;
368
    }
369
370
    /**
371
     * retrieves the parameters needed for the given EAP method and creates
372
     * appropriate nodes in the XML structure for them
373
     * 
374
     * @param array $eap the EAP type in question
375
     * @return array a recap of the findings
376
     */
377
    private function getAuthenticationMethodParams($eap)
378
    {
379
        $inner = $this->innerAuth($eap);
380
        $outerMethod = $eap["OUTER"];
381
382
        if (isset($inner["METHOD"]) && $inner["METHOD"]) {
383
            $innerauthmethod = new \core\DeviceXMLmain();
384
            $typeOfInner = ($inner["EAP"] ? 'EAPMethod' : 'NonEAPAuthMethod');
385
            $eapmethod = new \core\DeviceXMLmain();
386
            $eapmethod->setChild('Type', abs($inner['METHOD']));
387
            $innerauthmethod->setChild($typeOfInner, $eapmethod);
388
            return ['inner_method' => $innerauthmethod, 'methodID' => $outerMethod, 'inner_methodID' => $inner['METHOD']];
389
        } else {
390
            return ['inner_method' => 0, 'methodID' => $outerMethod, 'inner_methodID' => 0];
391
        }
392
    }
393
394
    /**
395
     * sets the server-side credentials for a given EAP type
396
     * 
397
     * @param \devices\XML\Type $eaptype the EAP type
398
     * @return \core\DeviceXMLmain
399
     */
400
    private function getServerSideCredentials($eap)
401
    {
402
        $attr = $this->attributes;
403
        $children = $this->authMethodElements['server'][$eap];
404
        $serversidecredential = new \core\DeviceXMLmain();
405
// Certificates and server names
406
        $cAlist = [];
407
        $attrCaList = $attr['internal:CAs'][0];
408
        foreach ($attrCaList as $ca) {
409
            $caObject = new \core\DeviceXMLmain();
410
            $caObject->setValue(base64_encode($ca['der']));
411
            $caObject->setAttributes(['format' => 'X.509', 'encoding' => 'base64']);
412
            $cAlist[] = $caObject;
413
        }
414
        $serverids = [];
415
        $servers = $attr['eap:server_name'];
416
        foreach ($servers as $server) {
417
            $serverid = new \core\DeviceXMLmain();
418
            $serverid->setValue($server);
419
            $serverids[] = $serverid;
420
        }
421
        if (in_array('CA', $children)) {
422
            $serversidecredential->setChild('CA', $cAlist);
423
        }
424
        if (in_array('ServerID', $children)) {
425
            $serversidecredential->setChild('ServerID', $serverids);
426
        }
427
        return $serversidecredential;
428
    }
429
430
    /**
431
     * sets the realm information for the client-side credential
432
     * 
433
     * @param \core\DeviceXMLmain $clientsidecredential the ClientSideCredential to which the realm info is to be added
434
     * @return void
435
     */
436
    private function setClientSideRealm($clientsidecredential)
437
    {
438
        $attr = $this->attributes;
439
        $realm = \core\common\Entity::getAttributeValue($attr, 'internal:realm', 0);
440
        if ($realm === NULL) {
441
            return;
442
        }
443
        if (\core\common\Entity::getAttributeValue($attr, 'internal:verify_userinput_suffix', 0) !== 1) {
444
            return;
445
        }
446
        $clientsidecredential->setChild('InnerIdentitySuffix', $realm);
447
        if (\core\common\Entity::getAttributeValue($attr, 'internal:hint_userinput_suffix', 0) === 1) {
448
            $clientsidecredential->setChild('InnerIdentityHint', 'true');
449
        }
450
    }
451
452
    /**
453
     * sets the client certificate
454
     * 
455
     * @return \core\DeviceXMLmain
456
     */
457
    private function getClientCertificate()
458
    {
459
        $clientCertificateObject = new \core\DeviceXMLmain();
460
        $clientCertificateObject->setValue(base64_encode($this->clientCert["certdata"]));
461
        $clientCertificateObject->setAttributes(['format' => 'PKCS12', 'encoding' => 'base64']);
462
        return $clientCertificateObject;
463
    }
464
465
    /**
466
     * sets the client-side credentials for the given EAP type
467
     * 
468
     * @param array $eapParams the EAP parameters
469
     * @return \core\DeviceXMLmain
470
     */
471
    private function getClientSideCredentials($eap)
472
    {
473
        $children = $this->authMethodElements['client'][$eap];
474
        $clientsidecredential = new \core\DeviceXMLmain();
475
        $outerId = $this->determineOuterIdString();
476
        $this->loggerInstance->debug(5, $eap, "XMLOI:", "\n");
477
        if (in_array('OuterIdentity', $children)) {
478
            if ($outerId !== NULL) {
479
                $clientsidecredential->setChild('OuterIdentity', $outerId);
480
            }
481
        }
482
        $this->setClientSideRealm($clientsidecredential);
483
//        $clientsidecredential->setChild('EAPType', $eapParams['inner_methodID'] ? $eapParams['inner_methodID'] : $eapParams['methodID']);
484
485
        // Client Certificate
486
        if ($this->selectedEap == \core\common\EAP::EAPTYPE_SILVERBULLET) {
487
            $attr = $this->attributes;
488
            $outerId = \core\common\Entity::getAttributeValue($attr, 'internal:username', 0);
489
            $clientsidecredential->setChild('OuterIdentity', $outerId);
490
            $clientsidecredential->setChild('ClientCertificate', $this->getClientCertificate());
491
        }
492
        return $clientsidecredential;
493
    }
494
495
    /**
496
     * sets the EAP method
497
     * 
498
     * @param \devices\XML\Type $eaptype the EAP type XMLObject
499
     * @return \core\DeviceXMLmain
500
     */
501
    private function getEapMethod($eaptype)
502
    {
503
        $eapmethod = new \core\DeviceXMLmain();
504
        $eapmethod->setChild('Type', $eaptype);
505
        if (isset($this->VendorSpecific)) {
506
            $vendorspecifics = [];
507
            foreach ($this->VendorSpecific as $vs) {
508
                $vendorspecific = new \core\DeviceXMLmain();
509
                $vs['value']->addAttribute('xsi:noNamespaceSchemaLocation', "xxx.xsd");
510
                $vendorspecific->setValue($vs['value']);
511
                $vendorspecific->setAttributes(['vendor' => $vs['vendor']]);
512
                $vendorspecifics[] = $vendorspecific;
513
            }
514
            $eapmethod->setChild('VendorSpecific', $vendorspecifics);
515
        }
516
        return($eapmethod);
517
    }
518
519
    /**
520
     * determines the authentication method to use
521
     * 
522
     * @param array $eap the EAP methods, in array representation
523
     * @return \core\DeviceXMLmain
524
     */
525
    private function getAuthMethod($eap)
526
    {
527
        $authmethod = new \core\DeviceXMLmain();
528
        $eapParams = $this->getAuthenticationMethodParams($eap);
529
        $eaptype = new \core\DeviceXMLmain();
530
        $eaptype->setValue($eapParams['methodID']);
531
// Type
532
        $authmethod->setChild('EAPMethod', $this->getEapMethod($eaptype));
0 ignored issues
show
Bug introduced by
$eaptype of type core\DeviceXMLmain is incompatible with the type devices\XML\Type expected by parameter $eaptype of devices\eap_config\DeviceXML::getEapMethod(). ( Ignorable by Annotation )

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

532
        $authmethod->setChild('EAPMethod', $this->getEapMethod(/** @scrutinizer ignore-type */ $eaptype));
Loading history...
533
534
// ServerSideCredentials
535
        $authmethod->setChild('ServerSideCredential', $this->getServerSideCredentials($eap['OUTER']));
536
537
// ClientSideCredentials
538
        $authmethod->setChild('ClientSideCredential', $this->getClientSideCredentials($eap['INNER']));
539
540
        if ($eapParams['inner_method']) {
541
            $authmethod->setChild('InnerAuthenticationMethod', $eapParams['inner_method']);
542
        }
543
        return $authmethod;
544
    }
545
    
546
    private function getAuthMethodsList() {
547
        $methodList = [];
548
        if ($this->allEaps) {
549
            $eapmethods = [];
550
            foreach ($this->attributes['all_eaps'] as $eap) {
551
                $eapRep = $eap->getArrayRep();
552
                if (in_array($eapRep, $this->supportedEapMethods)) {
553
                    $eapmethods[] = $eapRep;
554
                }
555
            }
556
        } else {
557
            $eapmethods = [$this->selectedEap];
558
        }
559
        foreach ($eapmethods as $eap) {
560
            $methodList[] = $this->getAuthMethod($eap);
561
        }
562
        return $methodList;
563
    }
564
565
566
567
}
568