Passed
Push — master ( 54cc30...cc7767 )
by Maja
08:24
created

Device_Vista7::writeWLANprofile()   A

Complexity

Conditions 4
Paths 8

Size

Total Lines 53

Duplication

Lines 0
Ratio 0 %

Importance

Changes 0
Metric Value
cc 4
nc 8
nop 6
dl 0
loc 53
rs 9.0254
c 0
b 0
f 0

How to fix   Long Method   

Long Method

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

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

Commonly applied refactorings include:

1
<?php
2
3
/*
4
 * ******************************************************************************
5
 * 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 creates MS Windows Vista and MS Windows 7 installers
14
 * It supports EAP-TLS, PEAP and EAP-pwd (with external software)
15
 * @author Tomasz Wolniewicz <[email protected]>
16
 *
17
 * @package ModuleWriting
18
 */
19
/**
20
 * necessary includes
21
 */
22
23
namespace devices\ms;
24
use \Exception;
25
26
class Device_Vista7 extends WindowsCommon {
27
28
    final public function __construct() {
29
        parent::__construct();
30
        $this->setSupportedEapMethods([\core\common\EAP::EAPTYPE_TLS, \core\common\EAP::EAPTYPE_PEAP_MSCHAP2, \core\common\EAP::EAPTYPE_PWD, \core\common\EAP::EAPTYPE_TTLS_PAP, \core\common\EAP::EAPTYPE_TTLS_MSCHAP2, \core\common\EAP::EAPTYPE_SILVERBULLET]);
31
        $this->loggerInstance->debug(4, "This device supports the following EAP methods: ");
32
        $this->loggerInstance->debug(4, $this->supportedEapMethods);
33
        $this->specialities['internal:use_anon_outer'][serialize(\core\common\EAP::EAPTYPE_PEAP_MSCHAP2)] = _("Anonymous identities do not use the realm as specified in the profile - it is derived from the suffix of the user's username input instead.");
34
    }
35
36
    public function writeInstaller() {
37
        $dom = textdomain(NULL);
38
        textdomain("devices");
39
        // create certificate files and save their names in $caFiles arrary
40
        $caFiles = $this->saveCertificateFiles('der');
41
42
        $allSSID = $this->attributes['internal:SSID'];
43
        $delSSIDs = $this->attributes['internal:remove_SSID'];
44
        $this->prepareInstallerLang();
45
        $setWired = isset($this->attributes['media:wired'][0]) && $this->attributes['media:wired'][0] == 'on' ? 1 : 0;
46
//   create a list of profiles to be deleted after installation
47
        $delProfiles = [];
48
        foreach ($delSSIDs as $ssid => $cipher) {
49
            if ($cipher == 'DEL') {
50
                $delProfiles[] = $ssid;
51
            }
52
            if ($cipher == 'TKIP') {
53
                $delProfiles[] = $ssid . ' (TKIP)';
54
            }
55
        }
56
57
        if ($this->selectedEap == \core\common\EAP::EAPTYPE_TLS || $this->selectedEap == \core\common\EAP::EAPTYPE_PEAP_MSCHAP2 || $this->selectedEap == \core\common\EAP::EAPTYPE_PWD || $this->selectedEap == \core\common\EAP::EAPTYPE_TTLS_PAP || $this->selectedEap == \core\common\EAP::EAPTYPE_SILVERBULLET) {
58
            $windowsProfile = [];
59
            $eapConfig = $this->prepareEapConfig($this->attributes);
60
            $iterator = 0;
61
            foreach ($allSSID as $ssid => $cipher) {
62
                if ($cipher == 'TKIP') {
63
                    $windowsProfile[$iterator] = $this->writeWLANprofile($ssid . ' (TKIP)', $ssid, 'WPA', 'TKIP', $eapConfig, $iterator);
64
                    $iterator++;
65
                }
66
                $windowsProfile[$iterator] = $this->writeWLANprofile($ssid, $ssid, 'WPA2', 'AES', $eapConfig, $iterator);
67
                $iterator++;
68
            }
69
            if ($setWired) {
70
                $this->writeLANprofile($eapConfig);
71
            }
72
        } else {
73
            print("  this EAP type is not handled yet.\n");
74
            return;
75
        }
76
        $this->loggerInstance->debug(4, "windowsProfile");
77
        $this->loggerInstance->debug(4, $windowsProfile);
78
79
        $this->writeProfilesNSH($windowsProfile, $caFiles);
80
        $this->writeAdditionalDeletes($delProfiles);
81
        if ($this->selectedEap == \core\common\EAP::EAPTYPE_SILVERBULLET) {
82
            $this->writeClientP12File();
83
        }
84
        $this->copyFiles($this->selectedEap);
85
        $fedLogo = $this->attributes['fed:logo_file'] ?? NULL;
86
        $idpLogo = $this->attributes['internal:logo_file'] ?? NULL;
87
        $this->combineLogo($idpLogo, $fedLogo);
88
        $this->writeMainNSH($this->selectedEap, $this->attributes);
89
        $this->compileNSIS();
90
        $installerPath = $this->signInstaller();
91
92
        textdomain($dom);
93
        return($installerPath);
94
    }
95
96
    private function prepareEapConfig($attr) {
97
        $outerUser = '';
98
        $vistaExt = '';
99
        $w7Ext = '';
100
        $useAnon = $attr['internal:use_anon_outer'] [0];
101
        $realm = $attr['internal:realm'] [0];
102
        if ($useAnon) {
103
            $outerUser = $attr['internal:anon_local_value'][0];
104
        }
105
//   $servers = preg_quote(implode(';',$attr['eap:server_name']));
106
        $servers = implode(';', $attr['eap:server_name']);
107
        $caArray = $attr['internal:CAs'][0];
108
        $authorId = "0";
109
        if ($this->selectedEap == \core\common\EAP::EAPTYPE_TTLS_PAP || $this->selectedEap == \core\common\EAP::EAPTYPE_TTLS_MSCHAP2) {
110
            $authorId = "67532";
111
            $servers = implode('</ServerName><ServerName>', $attr['eap:server_name']);
112
        }
113
114
        $profileFileCont = '<EAPConfig><EapHostConfig xmlns="http://www.microsoft.com/provisioning/EapHostConfig">
115
<EapMethod>
116
<Type xmlns="http://www.microsoft.com/provisioning/EapCommon">' .
117
                $this->selectedEap["OUTER"] . '</Type>
118
<VendorId xmlns="http://www.microsoft.com/provisioning/EapCommon">0</VendorId>
119
<VendorType xmlns="http://www.microsoft.com/provisioning/EapCommon">0</VendorType>
120
<AuthorId xmlns="http://www.microsoft.com/provisioning/EapCommon">' . $authorId . '</AuthorId>
121
</EapMethod>
122
';
123
124
125
        if ($this->selectedEap == \core\common\EAP::EAPTYPE_TTLS_PAP || $this->selectedEap == \core\common\EAP::EAPTYPE_TTLS_MSCHAP2) {
126
            $innerMethod = 'MSCHAPv2';
127
            if ($this->selectedEap == \core\common\EAP::EAPTYPE_TTLS_PAP) {
128
                $innerMethod = 'PAP';
129
            }
130
            $profileFileCont .= '
131
<Config xmlns="http://www.microsoft.com/provisioning/EapHostConfig">
132
<EAPIdentityProviderList xmlns="urn:ietf:params:xml:ns:yang:ietf-eap-metadata">
133
<EAPIdentityProvider ID="' . $this->deviceUUID . '" namespace="urn:UUID">
134
<ProviderInfo>
135
<DisplayName>' . $this->translateString($attr['general:instname'][0], $this->codePage) . '</DisplayName>
136
</ProviderInfo>
137
<AuthenticationMethods>
138
<AuthenticationMethod>
139
<EAPMethod>21</EAPMethod>
140
<ClientSideCredential>
141
<allow-save>true</allow-save>
142
';
143
            if ($useAnon == 1) {
144
                if ($outerUser == '') {
145
                    $profileFileCont .= '<AnonymousIdentity>@</AnonymousIdentity>';
146
                } else {
147
                    $profileFileCont .= '<AnonymousIdentity>' . $outerUser . '@' . $realm . '</AnonymousIdentity>';
148
                }
149
            }
150
            $profileFileCont .= '</ClientSideCredential>
151
<ServerSideCredential>
152
';
153
154
            foreach ($caArray as $ca) {
155
                $profileFileCont .= '<CA><format>PEM</format><cert-data>';
156
                $profileFileCont .= base64_encode($ca['der']);
157
                $profileFileCont .= '</cert-data></CA>
158
';
159
            }
160
            $profileFileCont .= "<ServerName>$servers</ServerName>\n";
161
162
            $profileFileCont .= '
163
</ServerSideCredential>
164
<InnerAuthenticationMethod>
165
<NonEAPAuthMethod>' .$innerMethod. '</NonEAPAuthMethod>
166
</InnerAuthenticationMethod>
167
<VendorSpecific>
168
<SessionResumption>false</SessionResumption>
169
</VendorSpecific>
170
</AuthenticationMethod>
171
</AuthenticationMethods>
172
</EAPIdentityProvider>
173
</EAPIdentityProviderList>
174
</Config>
175
';
176
        } elseif ($this->selectedEap == \core\common\EAP::EAPTYPE_TLS || $this->selectedEap == \core\common\EAP::EAPTYPE_SILVERBULLET) {
177
178
            $profileFileCont .= '
179
180
<Config xmlns:baseEap="http://www.microsoft.com/provisioning/BaseEapConnectionPropertiesV1" 
181
  xmlns:eapTls="http://www.microsoft.com/provisioning/EapTlsConnectionPropertiesV1">
182
<baseEap:Eap>
183
<baseEap:Type>13</baseEap:Type> 
184
<eapTls:EapType>
185
<eapTls:CredentialsSource>
186
<eapTls:CertificateStore />
187
</eapTls:CredentialsSource>
188
<eapTls:ServerValidation>
189
<eapTls:DisableUserPromptForServerValidation>true</eapTls:DisableUserPromptForServerValidation>
190
<eapTls:ServerNames>' . $servers . '</eapTls:ServerNames>';
191
            if ($caArray) {
192
                foreach ($caArray as $certAuthority) {
193
                    if ($certAuthority['root']) {
194
                        $profileFileCont .= "<eapTls:TrustedRootCA>" . $certAuthority['sha1'] . "</eapTls:TrustedRootCA>\n";
195
                    }
196
                }
197
            }
198
            $profileFileCont .= '</eapTls:ServerValidation>
199
';
200
            if (isset($attr['eap-specific:tls_use_other_id']) && $attr['eap-specific:tls_use_other_id'][0] == 'on') {
201
                $profileFileCont .= '<eapTls:DifferentUsername>true</eapTls:DifferentUsername>';
202
                $this->tlsOtherUsername = 1;
203
            } else {
204
                $profileFileCont .= '<eapTls:DifferentUsername>false</eapTls:DifferentUsername>';
205
            }
206
            $profileFileCont .= '
207
</eapTls:EapType>
208
</baseEap:Eap>
209
</Config>
210
';
211
        } elseif ($this->selectedEap == \core\common\EAP::EAPTYPE_PEAP_MSCHAP2) {
212
            if (isset($attr['eap:enable_nea']) && $attr['eap:enable_nea'][0] == 'on') {
213
                $nea = 'true';
214
            } else {
215
                $nea = 'false';
216
            }
217
            $vistaExt = '<Config xmlns:eapUser="http://www.microsoft.com/provisioning/EapUserPropertiesV1" 
218
xmlns:baseEap="http://www.microsoft.com/provisioning/BaseEapConnectionPropertiesV1" 
219
  xmlns:msPeap="http://www.microsoft.com/provisioning/MsPeapConnectionPropertiesV1" 
220
  xmlns:msChapV2="http://www.microsoft.com/provisioning/MsChapV2ConnectionPropertiesV1">
221
<baseEap:Eap>
222
<baseEap:Type>25</baseEap:Type> 
223
<msPeap:EapType>
224
<msPeap:ServerValidation>
225
<msPeap:DisableUserPromptForServerValidation>true</msPeap:DisableUserPromptForServerValidation> 
226
<msPeap:ServerNames>' . $servers . '</msPeap:ServerNames>';
227
            if ($caArray) {
228
                foreach ($caArray as $certAuthority) {
229
                    if ($certAuthority['root']) {
230
                        $vistaExt .= "<msPeap:TrustedRootCA>" . $certAuthority['sha1'] . "</msPeap:TrustedRootCA>\n";
231
                    }
232
                }
233
            }
234
            $vistaExt .= '</msPeap:ServerValidation>
235
<msPeap:FastReconnect>true</msPeap:FastReconnect> 
236
<msPeap:InnerEapOptional>0</msPeap:InnerEapOptional> 
237
<baseEap:Eap>
238
<baseEap:Type>26</baseEap:Type>
239
<msChapV2:EapType>
240
<msChapV2:UseWinLogonCredentials>false</msChapV2:UseWinLogonCredentials> 
241
</msChapV2:EapType>
242
</baseEap:Eap>
243
<msPeap:EnableQuarantineChecks>' . $nea . '</msPeap:EnableQuarantineChecks>
244
<msPeap:RequireCryptoBinding>false</msPeap:RequireCryptoBinding>
245
</msPeap:EapType>
246
</baseEap:Eap>
247
</Config>
248
';
249
            $w7Ext = '<Config xmlns="http://www.microsoft.com/provisioning/EapHostConfig">
250
<Eap xmlns="http://www.microsoft.com/provisioning/BaseEapConnectionPropertiesV1">
251
<Type>25</Type>
252
<EapType xmlns="http://www.microsoft.com/provisioning/MsPeapConnectionPropertiesV1">
253
<ServerValidation>
254
<DisableUserPromptForServerValidation>true</DisableUserPromptForServerValidation>
255
<ServerNames>' . $servers . '</ServerNames>';
256
            if ($caArray) {
257
                foreach ($caArray as $certAuthority) {
258
                    if ($certAuthority['root']) {
259
                        $w7Ext .= "<TrustedRootCA>" . $certAuthority['sha1'] . "</TrustedRootCA>\n";
260
                    }
261
                }
262
            }
263
            $w7Ext .= '</ServerValidation>
264
<FastReconnect>true</FastReconnect> 
265
<InnerEapOptional>false</InnerEapOptional> 
266
<Eap xmlns="http://www.microsoft.com/provisioning/BaseEapConnectionPropertiesV1">
267
<Type>26</Type>
268
<EapType xmlns="http://www.microsoft.com/provisioning/MsChapV2ConnectionPropertiesV1">
269
<UseWinLogonCredentials>false</UseWinLogonCredentials> 
270
</EapType>
271
</Eap>
272
<EnableQuarantineChecks>' . $nea . '</EnableQuarantineChecks>
273
<RequireCryptoBinding>false</RequireCryptoBinding>
274
';
275
            if ($useAnon == 1) {
276
                $w7Ext .= '<PeapExtensions>
277
<IdentityPrivacy xmlns="http://www.microsoft.com/provisioning/MsPeapConnectionPropertiesV2">
278
<EnableIdentityPrivacy>true</EnableIdentityPrivacy>
279
<AnonymousUserName>' . $outerUser . '</AnonymousUserName>
280
</IdentityPrivacy>
281
</PeapExtensions>
282
            ';
283
            }
284
            $w7Ext .= '</EapType>
285
</Eap>
286
</Config>
287
';
288
        } elseif ($this->selectedEap == \core\common\EAP::EAPTYPE_PWD) {
289
            $profileFileCont .= '<ConfigBlob></ConfigBlob>';
290
        }
291
292
293
294
        $profileFileContEnd = '</EapHostConfig></EAPConfig>
295
';
296
        $returnArray = [];
297
        $returnArray['vista'] = $profileFileCont . $vistaExt . $profileFileContEnd;
298
        $returnArray['w7'] = $profileFileCont . $w7Ext . $profileFileContEnd;
299
        return $returnArray;
300
    }
301
302
    /**
303
     * produce PEAP, TLS and TTLS configuration files for Vista and Windows 7
304
     * 
305
     * @param string $wlanProfileName
306
     * @param string $ssid
307
     * @param string $auth can be one of "WPA", "WPA2"
308
     * @param string $encryption can be one of: "TKIP", "AES"
309
     * @param array $eapConfig XML configuration block with EAP config data (two entries, one for Vista, one for 7)
310
     * @param int $profileNumber counter, which profile number is this
311
     * @return string
312
     */
313
    private function writeWLANprofile($wlanProfileName, $ssid, $auth, $encryption, $eapConfig, $profileNumber) {
314
        $profileFileCont = '<?xml version="1.0"?>
315
<WLANProfile xmlns="http://www.microsoft.com/networking/WLAN/profile/v1">
316
<name>' . $wlanProfileName . '</name>
317
<SSIDConfig>
318
<SSID>
319
<name>' . $ssid . '</name>
320
</SSID>
321
<nonBroadcast>true</nonBroadcast>
322
</SSIDConfig>
323
<connectionType>ESS</connectionType>
324
<connectionMode>auto</connectionMode>
325
<autoSwitch>false</autoSwitch>
326
<MSM>
327
<security>
328
<authEncryption>
329
<authentication>' . $auth . '</authentication>
330
<encryption>' . $encryption . '</encryption>
331
<useOneX>true</useOneX>
332
</authEncryption>
333
';
334
        if ($auth == 'WPA2') {
335
            $profileFileCont .= '<PMKCacheMode>enabled</PMKCacheMode>
336
<PMKCacheTTL>720</PMKCacheTTL>
337
<PMKCacheSize>128</PMKCacheSize>
338
<preAuthMode>disabled</preAuthMode>
339
';
340
        }
341
        $profileFileCont .= '<OneX xmlns="http://www.microsoft.com/networking/OneX/v1">
342
<cacheUserData>true</cacheUserData>
343
<authMode>user</authMode>
344
';
345
346
        $closing = '
347
</OneX>
348
</security>
349
</MSM>
350
</WLANProfile>
351
';
352
353
        if (!is_dir('w7')) {
354
            mkdir('w7');
355
        }
356
        if (!is_dir('vista')) {
357
            mkdir('vista');
358
        }
359
        $vistaFileName = "vista/wlan_prof-$profileNumber.xml";
360
        file_put_contents($vistaFileName, $profileFileCont . $eapConfig['vista'] . $closing);
361
        $sevenFileName = "w7/wlan_prof-$profileNumber.xml";
362
        file_put_contents($sevenFileName, $profileFileCont . $eapConfig['w7'] . $closing);
363
        $this->loggerInstance->debug(2, "Installer has been written into directory $this->FPATH\n");
364
        $this->loggerInstance->debug(4, "WLAN_Profile:$wlanProfileName:$encryption\n");
365
        return("\"$wlanProfileName\" \"$encryption\"");
366
    }
367
368
    private function writeLANprofile($eapConfig) {
369
        $profileFileCont = '<?xml version="1.0"?>
370
<LANProfile xmlns="http://www.microsoft.com/networking/LAN/profile/v1">
371
<MSM>
372
<security>
373
<OneXEnforced>false</OneXEnforced>
374
<OneXEnabled>true</OneXEnabled>
375
<OneX xmlns="http://www.microsoft.com/networking/OneX/v1">
376
<cacheUserData>true</cacheUserData>
377
<authMode>user</authMode>
378
';
379
        $closing = '
380
</OneX>
381
</security>
382
</MSM>
383
</LANProfile>
384
';
385
        if (!is_dir('w7')) {
386
            mkdir('w7');
387
        }
388
        if (!is_dir('vista')) {
389
            mkdir('vista');
390
        }
391
        
392
        file_put_contents("vista/lan_prof.xml", $profileFileCont . $eapConfig['vista'] . $closing);
393
        file_put_contents("w7/lan_prof.xml", $profileFileCont . $eapConfig['w7'] . $closing);
394
        
395
    }
396
397
    private function writeMainNSH($eap, $attr) {
398
        $this->loggerInstance->debug(4, "writeMainNSH");
399
        $this->loggerInstance->debug(4, $attr);
400
        $this->loggerInstance->debug(4, "MYLANG=" . $this->lang . "\n");
401
402
        $eapOptions = [
403
            \core\common\EAP::PEAP => ['str' => 'PEAP', 'exec' => 'user'],
404
            \core\common\EAP::TLS => ['str' => 'TLS', 'exec' => 'user'],
405
// TODO for TW: the following line doesn't work - that constant is an array, which can't be a key for another array
406
// generated a PHP Warning but doesn't seem to have any catastrophic effect?
407
//           \core\common\EAP::EAPTYPE_SILVERBULLET => ['str' => 'TLS', 'exec' => 'user'],
408
            \core\common\EAP::TTLS => ['str' => 'GEANTLink', 'exec' => 'user'],
409
            \core\common\EAP::PWD => ['str' => 'PWD', 'exec' => 'user'],
410
        ];
411
        $fcontents = '';
412
        if (CONFIG_CONFASSISTANT['NSIS_VERSION'] >= 3) {
413
            $fcontents .= "Unicode true\n";
414
        }
415
416
// Uncomment the line below if you want this module to run under XP (only displaying a warning)
417
// $fcontents .= "!define ALLOW_XP\n";
418
// Uncomment the line below if you want this module to produce debugging messages on the client
419
// $fcontents .= "!define DEBUG_CAT\n";
420
        if ($this->tlsOtherUsername == 1) {
421
            $fcontents .= "!define PFX_USERNAME\n";
422
        }
423
        $execLevel = $eapOptions[$eap["OUTER"]]['exec'];
424
        $eapStr = $eapOptions[$eap["OUTER"]]['str'];
425
        if ($eap == \core\common\EAP::EAPTYPE_SILVERBULLET) {
426
            $fcontents .= "!define SILVERBULLET\n";
427
        }
428
        $this->loggerInstance->debug(4, "EAP_STR=$eapStr\n");
429
        $this->loggerInstance->debug(4, $eap);
430
431
        $fcontents .= '!define ' . $eapStr;
432
        $fcontents .= "\n" . '!define EXECLEVEL "' . $execLevel . '"';
433
        $fcontents .= $this->writeNsisDefines($attr);
434
        file_put_contents('main.nsh', $fcontents);
435
    }
436
437
    private function writeProfilesNSH($wlanProfiles, $caArray) {
438
        $this->loggerInstance->debug(4, "writeProfilesNSH");
439
        $this->loggerInstance->debug(4, $wlanProfiles);
440
        $contentWlan = '';
441
        foreach ($wlanProfiles as $wlanProfile) {
442
            $contentWlan .= "!insertmacro define_wlan_profile $wlanProfile\n";
443
        }
444
445
        file_put_contents('profiles.nsh', $contentWlan);
446
        
447
        $contentCerts = '';
448
        $fileHandleCerts = fopen('certs.nsh', 'w');
449
        if ($fileHandleCerts === FALSE) {
450
            throw new Exception("Unable to open new file certs.nsh to write CAs!");
451
        }
452
        foreach ($caArray as $certAuthority) {
453
            $store = $certAuthority['root'] ? "root" : "ca";
454
            $contentCerts .= '!insertmacro install_ca_cert "' . $certAuthority['file'] . '" "' . $certAuthority['sha1'] . '" "' . $store . "\"\n";
455
        }
456
        fwrite($fileHandleCerts, $contentCerts);
457
        fclose($fileHandleCerts);
458
    }
459
460
    private function copyFiles($eap) {
461
        $this->loggerInstance->debug(4, "copyFiles start\n");
462
        $this->loggerInstance->debug(4, "code_page=" . $this->codePage . "\n");
463
        $this->copyBasicFiles();
464
465
        switch ($eap["OUTER"]) {
466
            case \core\common\EAP::TTLS:
467
                $this->copyGeantLinkFiles();
468
                break;
469
            case \core\common\EAP::PWD:
470
                $this->copyPwdFiles();
471
                break;
472
            default:
473
                if (!$this->translateFile('peap_tls.inc', 'cat.NSI', $this->codePage)) {
474
                    throw new Exception("Translating needed file peap_tls.inc failed!");
475
                }
476
        }
477
        $this->loggerInstance->debug(4, "copyFiles end\n");
478
        return TRUE;
479
    }
480
481
    private $tlsOtherUsername = 0;
482
483
}
484