Test Setup Failed
Push — master ( b368d1...ac234d )
by Stefan
05:29
created

MobileconfigSuperclass::__construct()   A

Complexity

Conditions 4
Paths 3

Size

Total Lines 14
Code Lines 9

Duplication

Lines 0
Ratio 0 %

Importance

Changes 1
Bugs 0 Features 0
Metric Value
eloc 9
c 1
b 0
f 0
dl 0
loc 14
rs 9.9666
cc 4
nc 3
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 contains the installer for iOS devices and Apple 10.7 Lion
25
 *
26
 *
27
 * @author Stefan Winter <[email protected]>
28
 * @package Developer
29
 */
30
31
namespace devices\apple_mobileconfig;
32
33
use \Exception;
34
35
/**
36
 * This is the main implementation class of the module
37
 *
38
 * The class should only define one public method: writeInstaller.
39
 *
40
 * All other methods and properties should be private. This example sets zipInstaller method to protected, so that it can be seen in the documentation.
41
 *
42
 * @package Developer
43
 */
44
abstract class MobileconfigSuperclass extends \core\DeviceConfig
45
{
46
47
    /**
48
     * institution name in preferred language
49
     * 
50
     * @var string
51
     */
52
    private $instName;
53
    
54
    /**
55
     * profile name in preferred language
56
     * 
57
     * @var string
58
     */
59
    private $profileName;
60
    
61
    /**
62
     * institution name, massaged to make it fit into the XML payload descriptor
63
     * 
64
     * @var string
65
     */
66
    private $massagedInst;
67
    
68
    /**
69
     * profile name, massaged to make it fit into the XML payload descriptor
70
     * 
71
     * @var string
72
     */
73
    private $massagedProfile;
74
    
75
    /**
76
     * country name, massaged to make it fit into the XML payload descriptor
77
     * 
78
     * @var string
79
     */
80
    private $massagedCountry;
81
    
82
    /**
83
     * consortium name, massaged to make it fit into the XML payload descriptor
84
     * 
85
     * @var string
86
     */
87
    private $massagedConsortium;
88
    
89
    /**
90
     * current language, without any .CHARSET suffixes
91
     * 
92
     * @var string
93
     */
94
    private $lang;
95
    
96
    /**
97
     * if we include a client certificate (silverbullet), the UUID of the certificate
98
     * 
99
     * @var string
100
     */
101
    private $clientCertUUID;
102
103
    /**
104
     * iterator to uniquely identify every Wi-Fi payload with a suffix in the file
105
     * 
106
     * @var integer
107
     */
108
    private $serial;
109
    
110
    /**
111
     * iterator to uniquely identify every removal payload with a suffix in the file
112
     * @var integer
113
     */
114
    private $removeSerial;
115
    
116
    /**
117
     * iterator to uniquely identify evera CA payload with a suffix in the file
118
     * 
119
     * @var integer
120
     */
121
    private $caSerial;
122
    
123
    /**
124
     * we need to be cautious not to include a CA twice, even if the admin
125
     * included it twice in the CAT config. This variable takes note of all
126
     * CA certs we already added to the file.
127
     * 
128
     * @var array
129
     */
130
    private $CAsAccountedFor = [];
131
    
132
    /**
133
     * we need a globally valid domain anchor, independent of the consortium
134
     */
135
    const IPHONE_PAYLOAD_PREFIX = "org.1x-config";
136
    
137
138
    /**
139
     * construct with the standard set of EAP methods we support, and preload
140
     * specialities
141
     */
142
    public function __construct()
143
    {
144
        parent::__construct();
145
        \core\common\Entity::intoThePotatoes();
146
        // that's what all variants support. Sub-classes can change it.
147
        $this->setSupportedEapMethods([\core\common\EAP::EAPTYPE_PEAP_MSCHAP2, \core\common\EAP::EAPTYPE_TTLS_PAP, \core\common\EAP::EAPTYPE_TTLS_MSCHAP2, \core\common\EAP::EAPTYPE_SILVERBULLET]);
148
        foreach(\core\common\EAP::listKnownEAPTypes() as $eapType) {
149
            if ($eapType->isPasswordRequired() || $eapType->isPasswordOptional()) {
150
                $this->specialities['internal:verify_userinput_suffix'][serialize($eapType->getArrayRep())] = _("It is not possible to actively verify the user input for suffix match; but if there is no 'Terms of Use' configured, the installer will display a corresponding hint to the user instead.");
151
                $this->specialities['media:openroaming'][serialize($eapType->getArrayRep())] = _("OpenRoaming is not provisioned due to severe UI limitations during install time.");
152
                $this->specialities['media:consortium_OI'][serialize($eapType->getArrayRep())] = _("Passpoint networks are not provisioned due to severe UI limitations during install time.");
153
            }
154
        }
155
        \core\common\Entity::outOfThePotatoes();
156
    }
157
158
    /**
159
     * massage a name so that it becomes acceptable inside the plist XML
160
     * 
161
     * @param string $input the literal name
162
     * @return string
163
     */
164
    private function massageName($input)
165
    {
166
        return htmlspecialchars(strtolower(iconv("UTF-8", "US-ASCII//TRANSLIT", preg_replace(['/ /', '/\//'], '_', $input))), ENT_XML1, 'UTF-8');
167
    }
168
169
    /**
170
     * the general part of a mobileconfig file in plist format
171
     * @return string
172
     */
173
    private function generalPayload()
174
    {
175
        \core\common\Entity::intoThePotatoes();
176
        $tagline = sprintf(_("Network configuration profile '%s' of '%s' - provided by %s"), htmlspecialchars($this->profileName, ENT_XML1, 'UTF-8'), htmlspecialchars($this->instName, ENT_XML1, 'UTF-8'), \config\ConfAssistant::CONSORTIUM['display_name']);
177
178
        $eapType = $this->selectedEap;
179
        // simpler message for silverbullet
180
        if ($eapType['INNER'] == \core\common\EAP::NE_SILVERBULLET) {
181
            $tagline = sprintf(_("%s configuration for IdP '%s' - provided by %s"), \core\ProfileSilverbullet::PRODUCTNAME, htmlspecialchars($this->instName, ENT_XML1, 'UTF-8'), \config\ConfAssistant::CONSORTIUM['display_name']);
182
        }
183
184
        $retval = "
185
      <key>PayloadDescription</key>
186
         <string>$tagline</string>
187
      <key>PayloadDisplayName</key>
188
         <string>" . \config\ConfAssistant::CONSORTIUM['display_name'] . "</string>
189
      <key>PayloadIdentifier</key>
190
         <string>" . self::IPHONE_PAYLOAD_PREFIX . ".$this->massagedConsortium.$this->massagedCountry.$this->massagedInst.$this->massagedProfile.$this->lang</string>
191
      <key>PayloadOrganization</key>
192
         <string>" . htmlspecialchars(iconv("UTF-8", "UTF-8//IGNORE", $this->attributes['general:instname'][0]), ENT_XML1, 'UTF-8') . ( $this->attributes['internal:profile_count'][0] > 1 ? " (" . htmlspecialchars(iconv("UTF-8", "UTF-8//IGNORE", $this->attributes['profile:name'][0]), ENT_XML1, 'UTF-8') . ")" : "") . "</string>
193
      <key>PayloadType</key>
194
         <string>Configuration</string>
195
      <key>PayloadUUID</key>
196
         <string>" . \core\common\Entity::uuid('', self::IPHONE_PAYLOAD_PREFIX . $this->massagedConsortium . $this->massagedCountry . $this->massagedInst . $this->massagedProfile) . "</string>
197
      <key>PayloadVersion</key>
198
         <integer>1</integer>";
199
        \core\common\Entity::outOfThePotatoes();
200
        return $retval;
201
    }
202
203
    const FILE_START = "<?xml version=\"1.0\" encoding=\"utf-8\"?>
204
<!DOCTYPE plist PUBLIC \"-//Apple Computer//DTD PLIST 1.0//EN\"
205
\"http://www.apple.com/DTDs/PropertyList-1.0.dtd\">
206
<plist version=\"1.0\">
207
<dict>";
208
    const FILE_END = "</dict></plist>";
209
    const BUFFER_CONSENT_PRE = "
210
      <key>ConsentText</key>
211
         <dict>
212
            <key>default</key>
213
               <string>";
214
    const BUFFER_CONSENT_POST = "</string>
215
         </dict>
216
         ";
217
218
    /**
219
     * creates a ConsentText block if either Terms of Use are specified or the
220
     * user input hints should be displayed. Otherwise, produces nothing.
221
     * 
222
     * @return string
223
     */
224
    protected function consentBlock()
225
    {
226
        \core\common\Entity::intoThePotatoes();
227
        if (isset($this->attributes['support:info_file'])) {
228
            return MobileconfigSuperclass::BUFFER_CONSENT_PRE . htmlspecialchars(iconv("UTF-8", "UTF-8//TRANSLIT", $this->attributes['support:info_file'][0]), ENT_XML1, 'UTF-8') . MobileconfigSuperclass::BUFFER_CONSENT_POST;
229
        }
230
        if ($this->attributes['internal:verify_userinput_suffix'][0] != 0) {
231
            if ($this->attributes['internal:hint_userinput_suffix'][0] != 0) {
232
                $retval = MobileconfigSuperclass::BUFFER_CONSENT_PRE . sprintf(_("Important Notice: your username MUST end exactly with '...@%s' !"), $this->attributes['internal:realm'][0]) . MobileconfigSuperclass::BUFFER_CONSENT_POST;
233
                \core\common\Entity::outOfThePotatoes();
234
                return $retval;
235
            } else { 
236
            if (strlen($this->attributes['internal:realm'][0]) > 0) {
237
                /// note space between variable and exclamation mark - makes sure users don't mistakenly think the exclamation mark is part of the required username!
238
                $retval = MobileconfigSuperclass::BUFFER_CONSENT_PRE . sprintf(_("Important Notice: your username MUST contain an '@' and end with ...%s !"), $this->attributes['internal:realm'][0]) . MobileconfigSuperclass::BUFFER_CONSENT_POST;
239
                \core\common\Entity::outOfThePotatoes();
240
                return $retval;
241
            }
242
            $retval = MobileconfigSuperclass::BUFFER_CONSENT_PRE . _("Important Notice: your username MUST be in the form of xxx@yyy where the yyy is a common suffix identifying your Identity Provider. Please find out what to use there and enter the username in the correct format.") . MobileconfigSuperclass::BUFFER_CONSENT_POST;
243
            \core\common\Entity::outOfThePotatoes();
244
            return $retval;
245
            }
246
        }
247
        \core\common\Entity::outOfThePotatoes();
248
        return "";
249
    }
250
251
    /**
252
     * create the actual installer XML file
253
     * 
254
     * @return string filename of the generated installer
255
     */
256
    public function writeInstaller()
257
    {
258
        \core\common\Entity::intoThePotatoes();
259
260
        $this->loggerInstance->debug(4, "mobileconfig Module Installer start\n");
261
262
        // remove spaces and slashes (filename!), make sure it's simple ASCII only, then lowercase it
263
        // also escape htmlspecialchars
264
        // not all names and profiles have a name, so be prepared
265
266
        $this->loggerInstance->debug(5, "List of available attributes: " . var_export($this->attributes, TRUE));
267
268
        $this->instName = $this->attributes['general:instname'][0] ?? _("Unnamed Organisation");
269
        $this->profileName = $this->attributes['profile:name'][0] ?? _("Unnamed Profile");
270
271
        $this->massagedInst = $this->massageName($this->instName);
272
        $this->massagedProfile = $this->massageName($this->profileName);
273
        $this->massagedCountry = $this->massageName($this->attributes['internal:country'][0]);
274
        $this->massagedConsortium = $this->massageName(\config\ConfAssistant::CONSORTIUM['name']);
275
        $this->lang = preg_replace('/\..+/', '', setlocale(LC_ALL, "0"));
276
277
        $eapType = $this->selectedEap;
278
279
        $outputXml = self::FILE_START;
280
        $outputXml .= "<key>PayloadContent</key>
281
         <array>";
282
283
        // if we are in silverbullet, we will need a whole own block for the client credential
284
        // and also for the profile expiry
285
286
        $this->clientCertUUID = NULL;
287
        if ($eapType['INNER'] == \core\common\EAP::NE_SILVERBULLET) {
288
            $blockinfo = $this->clientP12Block();
289
            $outputXml .= $blockinfo['block'];
290
            $this->clientCertUUID = $blockinfo['UUID'];
291
        }
292
293
        $outputXml .= $this->allCA();
294
295
        $outputXml .= $this->allNetworkBlocks();
296
297
        $outputXml .= "</array>";
298
        $outputXml .= $this->generalPayload();
299
        $outputXml .= $this->consentBlock();
300
301
        if ($eapType['INNER'] == \core\common\EAP::NE_SILVERBULLET) {
302
            $outputXml .= $this->expiryBlock();
303
        }
304
        $outputXml .= self::FILE_END;
305
306
        file_put_contents('installer_profile', $outputXml);
307
308
        $fileName = $this->installerBasename . '.mobileconfig';
309
310
        if (!$this->sign) {
311
            rename("installer_profile", $fileName);
312
            \core\common\Entity::outOfThePotatoes();
313
            return $fileName;
314
        }
315
        // still here? Then we are signing.
316
        $signing = system($this->sign . " installer_profile '$fileName' > /dev/null");
317
        if ($signing === FALSE) {
318
            $this->loggerInstance->debug(2, "Signing the mobileconfig installer $fileName FAILED!\n");
319
        }
320
        \core\common\Entity::outOfThePotatoes();
321
        return $fileName;
322
    }
323
324
    /**
325
     * produces the HTML text to be displayed when clicking on the "help" button
326
     * besides the download button.
327
     * 
328
     * @return string
329
     */
330
    public function writeDeviceInfo()
331
    {
332
        \core\common\Entity::intoThePotatoes();
333
        $ssidCount = count($this->attributes['internal:SSID']);
334
        $certCount = count($this->attributes['internal:CAs'][0]);
335
        $out = "<p>" . _("For best results, please use the built-in browser (Safari) to open the configuration file.") . "</p>";
336
        $out .= "<p>";
337
        $out .= _("The profile will install itself after you click (or tap) the button. You will be asked for confirmation/input at several points:");
338
        $out .= "<ul>";
339
        $out .= "<li>" . _("to install the profile") . "</li>";
340
        $out .= "<li>" . ngettext("to accept the server certificate authority", "to accept the server certificate authorities", $certCount);
341
        if ($certCount > 1) {
342
            $out .= " " . sprintf(_("(%d times)"), $certCount);
343
        }
344
        $out .= "</li>";
345
        $out .= "<li>" . _("to enter the username and password you have been given by your organisation");
346
        if ($ssidCount > 1) {
347
            $out .= " " . sprintf(_("(%d times each, because %s is installed for %d SSIDs)"), $ssidCount, \config\ConfAssistant::CONSORTIUM['display_name'], $ssidCount);
348
        }
349
        $out .= "</li>";
350
        $out .= "</ul>";
351
        $out .= "</p>";
352
        \core\common\Entity::outOfThePotatoes();
353
        return $out;
354
    }
355
356
    /**
357
     * collates a list of the UUIDs of all the CAs which are to be included in
358
     * the mobileconfig file
359
     * 
360
     * @return array
361
     */
362
    private function listCAUuids()
363
    {
364
        $retval = [];
365
        foreach ($this->attributes['internal:CAs'][0] as $ca) {
366
            $retval[] = $ca['uuid'];
367
        }
368
        return $retval;
369
    }
370
371
    /**
372
     * This is the XML structure subtree of a Network block which contains the
373
     * settings specific to Passpoint
374
     * 
375
     * @param array  $consortiumOi list of consortiumOi to put into structure
376
     * @param string $oiName       the pretty-print name of the RCOI
377
     * @return string
378
     */
379
    private function passPointBlock($consortiumOi, $oiName)
380
    {
381
        $retval = "
382
               <key>IsHotspot</key>
383
               <true/>
384
               <key>ServiceProviderRoamingEnabled</key>
385
               <true/>
386
               <key>DisplayedOperatorName</key>
387
               <string>" . $oiName . "</string>";
388
        // if we don't know the realm, omit the entire DomainName key
389
        if (isset($this->attributes['internal:realm'])) {
390
            $retval .= "<key>DomainName</key>
391
               <string>";
392
            $retval .= $this->attributes['internal:realm'][0];
393
            $retval .= "</string>
394
                ";
395
        }
396
        $retval .= "                <key>RoamingConsortiumOIs</key>
397
                <array>";
398
399
        foreach ($consortiumOi as $oneCons) {
400
            $retval .= "<string>" . strtoupper($oneCons) . "</string>";
401
        }
402
403
        $retval .= "</array>";
404
        // this is an undocumented value found on the net. Does it do something useful?
405
        $retval .= "<key>_UsingHotspot20</key>
406
                <true/>
407
                ";
408
        // do we need to set NAIRealmName ? In Rel 1, probably yes, in Rel 2, 
409
        // no because ConsortiumOI is enough.
410
        // but which release is OS X doing? And what should we fill in, given
411
        // that we have thousands of realms? Try just eduroam.org
412
        // 
413
        // tests from Hideaki suggest it's better not to set it; if Roaming
414
        // consortium OI and NAIRealmNames are both set, connecting to a hotspot
415
        // with just RCOI does not work
416
        /* if (\config\ConfAssistant::CONSORTIUM['name'] == "eduroam") {
417
            $retval .= "<key>NAIRealmNames</key>
418
                <array>
419
                    <string>eduroam.org</string>
420
                </array>";
421
        }*/
422
        return $retval;
423
    }
424
425
    /**
426
     * produces the EAP sub-block of a Network block
427
     * 
428
     * @param array $eapType EAP type in array notation
429
     * @return string
430
     */
431
    private function eapBlock($eapType)
432
    {
433
        $realm = $this->determineOuterIdString();
434
        $retval = "<key>EAPClientConfiguration</key>
435
                  <dict>
436
                      <key>AcceptEAPTypes</key>
437
                         <array>
438
                            <integer>" . $eapType['OUTER'] . "</integer>
439
                         </array>
440
                      <key>EAPFASTProvisionPAC</key>
441
                            <true />
442
                      <key>EAPFASTUsePAC</key>
443
                            <true />
444
                      <key>EAPFastProvisionPACAnonymously</key>
445
                            <false />
446
                      <key>OneTimeUserPassword</key>
447
                            <false />
448
";
449
        if ($realm !== NULL) {
450
            $retval .= "<key>OuterIdentity</key>
451
                                    <string>" . htmlspecialchars($realm, ENT_XML1, 'UTF-8') . "</string>
452
";
453
        }
454
        $retval .= "<key>PayloadCertificateAnchorUUID</key>
455
                         <array>";
456
        foreach ($this->listCAUuids() as $uuid) {
457
            if (in_array($uuid, $this->CAsAccountedFor)) {
458
                $retval .= "
459
<string>$uuid</string>";
460
            }
461
        }
462
        $retval .= "
463
                         </array>
464
                      <key>TLSAllowTrustExceptions</key>
465
                         <false />
466
                      <key>TLSTrustedServerNames</key>
467
                         <array>";
468
        foreach ($this->attributes['eap:server_name'] as $commonName) {
469
            $retval .= "
470
<string>$commonName</string>";
471
        }
472
        $retval .= "
473
                         </array>";
474
        if ($eapType['INNER'] == \core\common\EAP::NE_SILVERBULLET) {
475
            $retval .= "<key>UserName</key><string>" . $this->clientCert["certObject"]->username . "</string>";
476
        }
477
        $retval .= "
478
                      <key>TTLSInnerAuthentication</key>
479
                         <string>" . ($eapType['INNER'] == \core\common\EAP::NE_PAP ? "PAP" : "MSCHAPv2") . "</string>
480
                   </dict>";
481
        return $retval;
482
    }
483
484
    /**
485
     * produces the Proxy sub-block of a Network block
486
     * 
487
     * @return string
488
     */
489
    protected function proxySettings()
490
    {
491
        $buffer = "<key>ProxyType</key>";
492
        if (isset($this->attributes['media:force_proxy'])) {
493
            // find the port delimiter. In case of IPv6, there are multiple ':' 
494
            // characters, so we have to find the LAST one
495
            $serverAndPort = explode(':', strrev($this->attributes['media:force_proxy'][0]), 2);
496
            // characters are still reversed, invert on use!
497
            $buffer .= "<string>Manual</string>
498
                  <key>ProxyServer</key>
499
                  <string>" . strrev($serverAndPort[1]) . "</string>
500
                  <key>ProxyServerPort</key>
501
                  <integer>" . strrev($serverAndPort[0]) . "</integer>
502
                  <key>ProxyPACFallbackAllowed</key>
503
                  <false/>";
504
        } else {
505
            $buffer .= "<string>Auto</string>
506
                  <key>ProxyPACFallbackAllowed</key>
507
                  <true/>";
508
        }
509
        return $buffer;
510
    }
511
512
    /**
513
     * iOS 8 introduced the new value "WPA2" to lock out WPA ("1"). Make sure
514
     * we use it for the most recent gen of mobileconfig for iOS.
515
     * 
516
     * According to reports on the eduroam dev ML, also recent macOS supports it
517
     * so add it there, too (spec is silent on macOS versions).
518
     * 
519
     * @return string either "WPA" or "WPA2
520
     */
521
    private function encryptionString() {
522
        if (
523
                get_class($this) == "devices\apple_mobileconfig\DeviceMobileconfigIos12plus" || 
524
                get_class($this) == "devices\apple_mobileconfig\DeviceMobileconfigOsX"
525
           ) {
526
                    return "WPA2";
527
                } else {
528
                    return "WPA";
529
                }
530
    }
531
    
532
    /**
533
     * produces an entire Network block
534
     * 
535
     * @param int                  $blocktype      which type of network block is this?
536
     * @param string|array|boolean $toBeConfigured variable part of the config. Single SSID or list of ConsortiumOi
537
     * @param string               $prettyName     name with which to present the network to users
538
     * @return string
539
     * @throws Exception
540
     */
541
    private function networkBlock($blocktype, $toBeConfigured, $prettyName)
542
    {
543
        \core\common\Entity::intoThePotatoes();
544
        $eapType = $this->selectedEap;
545
        switch ($blocktype) {
546
            case MobileconfigSuperclass::NETWORK_BLOCK_TYPE_SSID:
547
                if (!is_string($toBeConfigured)) {
548
                    throw new Exception("SSID must be a string!");
549
                }
550
                $escapedSSID = htmlspecialchars($toBeConfigured, ENT_XML1, 'UTF-8');
551
                $payloadIdentifier = "wifi." . $this->serial;
552
                $payloadShortName = sprintf(_("%s - SSID %s"), $prettyName, $escapedSSID);
553
                $payloadName = sprintf(_("%s configuration for network name %s"), $prettyName, $escapedSSID);
554
                $encryptionTypeString = $this->encryptionString();
555
                $setupModesString = "";
556
                $wifiNetworkIdentification = "<key>SSID_STR</key>
557
                  <string>$escapedSSID</string>";
558
                break;
559
            case MobileconfigSuperclass::NETWORK_BLOCK_TYPE_WIRED:
560
                if (!is_bool($toBeConfigured)) {
561
                    throw new Exception("We expected a TRUE here!");
562
                }
563
                $payloadIdentifier = "firstactiveethernet";
564
                $payloadShortName = sprintf(_("%s - Wired Network"), $prettyName);
565
                $payloadName = sprintf(_("%s configuration for wired network"), $prettyName);
566
                $encryptionTypeString = "any";
567
                $setupModesString = "
568
               <key>SetupModes</key>
569
                  <array>
570
                     <string>System</string>
571
                  </array>";
572
                $wifiNetworkIdentification = "";
573
                break;
574
            case MobileconfigSuperclass::NETWORK_BLOCK_TYPE_CONSORTIUMOIS:
575
                if (!is_array($toBeConfigured)) {
576
                    throw new Exception("ConsortiumOI must be an array!");
577
                }
578
                if (count($toBeConfigured) == 0) {
579
                    return "";
580
                }
581
                $payloadIdentifier = "hs20.".implode('-',$toBeConfigured);
582
                $payloadShortName = sprintf(_("%s - RCOI"), $prettyName);
583
                $payloadName = sprintf(_("%s configuration (Passpoint RCOI)"),$prettyName);
584
                $encryptionTypeString = $this->encryptionString();
585
                $setupModesString = "";
586
                $wifiNetworkIdentification = $this->passPointBlock($toBeConfigured, $prettyName);
587
                break;
588
            default:
589
                throw new Exception("This type of network block is unknown!");
590
        }
591
        $retval = "<dict>";
592
        $retval .= $this->eapBlock($eapType);
593
        $retval .= "<key>EncryptionType</key>
594
                  <string>$encryptionTypeString</string>
595
               <key>HIDDEN_NETWORK</key>
596
                  <true />
597
               <key>PayloadDescription</key>
598
                  <string>$payloadName</string>
599
               <key>PayloadDisplayName</key>
600
                  <string>$payloadShortName</string>
601
               <key>PayloadIdentifier</key>
602
                  <string>" . self::IPHONE_PAYLOAD_PREFIX . ".$this->massagedConsortium.$this->massagedCountry.$this->massagedInst.$this->massagedProfile.$this->lang.$payloadIdentifier</string>
603
               <key>PayloadOrganization</key>
604
                  <string>" . $this->massagedConsortium . ".1x-config.org</string>
605
               <key>PayloadType</key>
606
                  <string>com.apple." . ($blocktype == MobileconfigSuperclass::NETWORK_BLOCK_TYPE_WIRED ? "firstactiveethernet" : "wifi") . ".managed</string>";
607
        $retval .= $this->proxySettings();
608
        $retval .= $setupModesString;
609
        if ($eapType['INNER'] == \core\common\EAP::NE_SILVERBULLET) {
610
            if ($this->clientCertUUID === NULL) {
611
                throw new Exception("Silverbullet REQUIRES a client certificate and we need to know the UUID!");
612
            }
613
            $retval .= "<key>PayloadCertificateUUID</key>
614
                        <string>$this->clientCertUUID</string>";
615
        }
616
        $retval .= "
617
               <key>PayloadUUID</key>
618
                  <string>" . \core\common\Entity::uuid() . "</string>
619
               <key>PayloadVersion</key>
620
                  <integer>1</integer>
621
                  $wifiNetworkIdentification</dict>";
622
        $this->serial = $this->serial + 1;
623
        \core\common\Entity::outOfThePotatoes();
624
        return $retval;
625
    }
626
627
    /**
628
     * Produces a Network block which sets a network to manual join (we don't
629
     * get any closer to removing a network in mobileconfig)
630
     * 
631
     * @param string $ssid the SSID to set to manual join only
632
     * @return string
633
     */
634
    private function removenetworkBlock($ssid)
635
    {
636
        \core\common\Entity::intoThePotatoes();
637
        $retval = "
638
<dict>
639
	<key>AutoJoin</key>
640
	<false/>
641
	<key>EncryptionType</key>
642
	<string>None</string>
643
	<key>HIDDEN_NETWORK</key>
644
	<false/>
645
	<key>IsHotspot</key>
646
	<false/>
647
	<key>PayloadDescription</key>
648
	<string>" . sprintf(_("This SSID should not be used after bootstrapping %s"), \config\ConfAssistant::CONSORTIUM['display_name']) . "</string>
649
	<key>PayloadDisplayName</key>
650
	<string>" . _("Disabled WiFi network") . "</string>
651
	<key>PayloadIdentifier</key>
652
	<string>" . self::IPHONE_PAYLOAD_PREFIX . ".$this->massagedConsortium.$this->massagedCountry.$this->massagedInst.$this->massagedProfile.$this->lang.wifi.disabled.$this->removeSerial</string>
653
	<key>PayloadType</key>
654
	<string>com.apple.wifi.managed</string>
655
	<key>PayloadUUID</key>
656
	<string>" . \core\common\Entity::uuid() . "</string>
657
	<key>PayloadVersion</key>
658
	<real>1</real>";
659
        $retval .= $this->proxySettings();
660
        $retval .= "<key>SSID_STR</key>
661
	<string>$ssid</string>
662
</dict>
663
";
664
        \core\common\Entity::outOfThePotatoes();
665
        return $retval;
666
    }
667
668
    const NETWORK_BLOCK_TYPE_SSID = 100;
669
    const NETWORK_BLOCK_TYPE_CONSORTIUMOIS = 101;
670
    const NETWORK_BLOCK_TYPE_WIRED = 102;
671
672
    /**
673
     * produces the entire series of Network blocks; all for SSID-based, 
674
     * Passpoint-based, wired, and manual-select only SSIDs
675
     * 
676
     * @return string
677
     */
678
    private function allNetworkBlocks()
679
    {
680
        $retval = "";
681
        $this->serial = 0;
682
        foreach ($this->attributes['internal:networks'] as $netName => $netDefinition) {
683
            // mobileconfig network blocks can only hold one SSID each, so iterate here
684
            foreach ($netDefinition['ssid'] as $ssid) {
685
                $retval .= $this->networkBlock(MobileconfigSuperclass::NETWORK_BLOCK_TYPE_SSID, $ssid, $netName);
686
            }
687
            // mobileconfig network blocks can accomodate a list of RCOIs in one statement, so just call it
688
            if ($this->selectedEapObject->isPasswordRequired() === FALSE) {
689
                $retval .= $this->networkBlock(MobileconfigSuperclass::NETWORK_BLOCK_TYPE_CONSORTIUMOIS, $netDefinition['oi'], $netName);
690
            }
691
        }
692
        if (isset($this->attributes['media:wired']) && get_class($this) == "devices\apple_mobileconfig\DeviceMobileconfigOsX") {
693
            $retval .= $this->networkBlock(MobileconfigSuperclass::NETWORK_BLOCK_TYPE_WIRED, TRUE, \config\ConfAssistant::CONSORTIUM['display_name']);
694
        }
695
        if (isset($this->attributes['media:remove_SSID'])) {
696
            $this->removeSerial = 0;
697
            foreach ($this->attributes['media:remove_SSID'] as $removeSSID) {
698
                $retval .= $this->removenetworkBlock($removeSSID);
699
                $this->removeSerial = $this->removeSerial + 1;
700
            }
701
        }
702
        return $retval;
703
    }
704
705
    /**
706
     * collates a block with all CAs that are to be included in the mobileconfig
707
     * 
708
     * @return string
709
     */
710
    private function allCA()
711
    {
712
        $retval = "";
713
        $this->caSerial = 0;
714
        foreach ($this->attributes['internal:CAs'][0] as $ca) {
715
            $retval .= $this->caBlob($ca);
716
            $this->caSerial = $this->caSerial + 1;
717
        }
718
        return $retval;
719
    }
720
721
    /**
722
     * creates a Cert block containing a client certificate (used in SB only)
723
     * @return array the block itself, and the UUID of the certificate
724
     * @throws Exception
725
     */
726
    private function clientP12Block()
727
    {
728
        \core\common\Entity::intoThePotatoes();
729
        if (count($this->clientCert) == 0) {
730
            throw new Exception("the client block was called but there is no client certificate!");
731
        }
732
        $binaryBlob = $this->clientCert["certdata_nointermediate"];
733
        $mimeBlob = base64_encode($binaryBlob);
734
        $mimeFormatted = chunk_split($mimeBlob, 52, "\r\n");
735
        $payloadUUID = \core\common\Entity::uuid('', $mimeBlob);
736
        $retArray = ["block" => "<dict>" .
737
            // we don't include the import password. It's displayed on screen, and should be input by the user.
738
            // <key>Password</key>
739
            //   <string>" . $this->clientCert['password'] . "</string>
740
            "<key>PayloadCertificateFileName</key>
741
                     <string>" . $this->massagedConsortium . ".pfx</string>
742
                  <key>PayloadContent</key>
743
                     <data>
744
$mimeFormatted
745
                     </data>
746
                  <key>PayloadDescription</key>
747
                     <string>MIME Base-64 encoded PKCS#12 Client Certificate</string>
748
                  <key>PayloadDisplayName</key>
749
                     <string>" . _("User certificate") . "</string>
750
                  <key>PayloadIdentifier</key>
751
                     <string>com.apple.security.pkcs12.$payloadUUID</string>
752
                  <key>PayloadType</key>
753
                     <string>com.apple.security.pkcs12</string>
754
                  <key>PayloadUUID</key>
755
                     <string>$payloadUUID</string>
756
                  <key>PayloadVersion</key>
757
                     <integer>1</integer>
758
                </dict>",
759
            "UUID" => $payloadUUID,];
760
        \core\common\Entity::outOfThePotatoes();
761
        return $retArray;
762
    }
763
764
    /**
765
     * creates an Expiry block. This is only done in SB; the profile expires
766
     * when the client cert expires.
767
     * 
768
     * @return string
769
     * @throws Exception
770
     */
771
    private function expiryBlock() {
772
        if (count($this->clientCert) == 0) {
773
            throw new Exception("the expiry block was called but there is no client certificate!");
774
        }
775
        $expiryTime = new \DateTime($this->clientCert['certObject']->expiry);
776
        return "<key>RemovalDate</key>
777
        <date>" . $expiryTime->format("Y-m-d") . "T" . $expiryTime->format("H:i:s") . "Z</date>";
778
    }
779
780
    /**
781
     * creates a block for one single CA
782
     * 
783
     * @param array $ca the CA for which to generate the XML block
784
     * @return string
785
     */
786
    private function caBlob($ca)
787
    {
788
        \core\common\Entity::intoThePotatoes();
789
        $stream = "";
790
        if (!in_array($ca['uuid'], $this->CAsAccountedFor)) { // skip if this is a duplicate
791
            // cut lines with CERTIFICATE
792
            $stage1 = preg_replace('/-----BEGIN CERTIFICATE-----/', '', $ca['pem']);
793
            $stage2 = preg_replace('/-----END CERTIFICATE-----/', '', $stage1);
794
            $trimmedPem = trim($stage2);
795
796
            $stream = "
797
            <dict>
798
               <key>PayloadCertificateFileName</key>
799
               <string>" . $ca['uuid'] . ".der</string>
800
               <key>PayloadContent</key>
801
               <data>
802
" . $trimmedPem . "</data>
803
               <key>PayloadDescription</key>
804
               <string>" . sprintf(_("The %s Certification Authority"), \core\common\Entity::$nomenclature_inst) . "</string>
805
               <key>PayloadDisplayName</key>
806
               <string>" . 
807
                    /// example: "Identity Provider CA #1 (Root)"
808
                    sprintf(_("%s CA #%d (%s)" ), 
809
                            \core\common\Entity::$nomenclature_inst, 
810
                            count($this->CAsAccountedFor)+1, 
811
                            ($ca['root'] ? _("Root") : _("Intermediate"))) . 
812
              "</string>
813
               <key>PayloadIdentifier</key>
814
               <string>" . self::IPHONE_PAYLOAD_PREFIX . ".$this->massagedConsortium.$this->massagedCountry.$this->massagedInst.$this->massagedProfile.credential.$this->caSerial</string>
815
               <key>PayloadOrganization</key>
816
               <string>" . $this->massagedConsortium . ".1x-config.org</string>
817
               <key>PayloadType</key>
818
               <string>com.apple.security.root</string>
819
               <key>PayloadUUID</key><string>" . $ca['uuid'] . "</string>
820
               <key>PayloadVersion</key>
821
               <integer>1</integer>
822
            </dict>";
823
            $this->CAsAccountedFor[] = $ca['uuid'];
824
        }
825
        \core\common\Entity::outOfThePotatoes();
826
        return $stream;
827
    }
828
829
}
830