Test Setup Failed
Push — master ( dad7bc...2b638e )
by Tomasz
05:58
created

DeviceLinux::writeDeviceInfo()   A

Complexity

Conditions 3
Paths 3

Size

Total Lines 19
Code Lines 15

Duplication

Lines 0
Ratio 0 %

Importance

Changes 1
Bugs 0 Features 0
Metric Value
eloc 15
c 1
b 0
f 0
dl 0
loc 19
rs 9.7666
cc 3
nc 3
nop 0
1
<?php
2
/*
3
 * *****************************************************************************
4
 * Contributions to this work were made on behalf of the GÉANT project, a 
5
 * project that has received funding from the European Union’s Framework 
6
 * Programme 7 under Grant Agreements No. 238875 (GN3) and No. 605243 (GN3plus),
7
 * Horizon 2020 research and innovation programme under Grant Agreements No. 
8
 * 691567 (GN4-1) and No. 731122 (GN4-2).
9
 * On behalf of the aforementioned projects, GEANT Association is the sole owner
10
 * of the copyright in all material which was developed by a member of the GÉANT
11
 * project. GÉANT Vereniging (Association) is registered with the Chamber of 
12
 * Commerce in Amsterdam with registration number 40535155 and operates in the 
13
 * UK as a branch of GÉANT Vereniging.
14
 * 
15
 * Registered office: Hoekenrode 3, 1102BR Amsterdam, The Netherlands. 
16
 * UK branch address: City House, 126-130 Hills Road, Cambridge CB2 1PQ, UK
17
 *
18
 * License: see the web/copyright.inc.php file in the file structure or
19
 *          <base_url>/copyright.php after deploying the software
20
 */
21
22
/**
23
 * This file creates Linux installers
24
 *
25
 * @author Tomasz Wolniewicz <[email protected]>
26
 *
27
 * @package ModuleWriting
28
 */
29
namespace devices\linux;
30
use Exception;
31
/**
32
 * This class creates Linux installers. It supports NetworkManager and raw
33
 * wpa_supplicant files.
34
 *
35
 * @author Tomasz Wolniewicz <[email protected]>
36
 * @author Michał Gasewicz <[email protected]> (Network Manager support)
37
 *
38
 * @package ModuleWriting
39
 */
40
class DeviceLinux extends \core\DeviceConfig {
41
42
    /**
43
     * constructor. Sets supported EAP methods.
44
     */
45
    final public function __construct() {
46
        parent::__construct();
47
        $this->setSupportedEapMethods([\core\common\EAP::EAPTYPE_PEAP_MSCHAP2, \core\common\EAP::EAPTYPE_TTLS_PAP, \core\common\EAP::EAPTYPE_TTLS_MSCHAP2, \core\common\EAP::EAPTYPE_TLS, \core\common\EAP::EAPTYPE_SILVERBULLET]);
48
        $this->specialities['media:openroaming'] = _("This device does not support provisioning of OpenRoaming.");
49
        $this->specialities['media:consortium_OI'] = _("This device does not support provisioning of Passpoint networks.");
50
51
    }
52
53
    /**
54
     * create the actual installer script
55
     * 
56
     * @return string filename of the generated installer
57
     * @throws Exception
58
     *
59
     */
60
    public function writeInstaller() {
61
        $installerPath = $this->installerBasename . ".py";
62
        $this->copyFile("main.py", $installerPath);
63
        $installer = fopen($installerPath,"a");
64
        if ($installer === FALSE) {
65
            throw new Exception("Unable to open installer file for writing!");
66
        }
67
        fwrite($installer, "\n\n");
68
        $this->writeMessages($installer);
69
        $this->writeConfigVars($installer);
70
        fwrite($installer, "\n\n");
71
        fwrite($installer, "if __name__ == '__main__':\n");
72
        fwrite($installer, "    run_installer()\n");
73
        fclose($installer);
74
        return($installerPath);
75
    }
76
    
77
    /**
78
     * produces the HTML text to be displayed when clicking on the "help" button
79
     * besides the download button.
80
     * 
81
     * @return string
82
     */
83
    public function writeDeviceInfo() {
84
        \core\common\Entity::intoThePotatoes();
85
        $out = sprintf(_("The installer is in the form of a Python script. It will try to configure %s under NetworkManager and if this is either not appropriate for your system or your version of NetworkManager is too old, a wpa_supplicant config file will be created instead."), \config\ConfAssistant::CONSORTIUM['display_name']);
86
        $out .= "<p>"._("The installer will configure access to:")." <strong>";
87
        $out .= implode('</strong>, <strong>', array_keys($this->attributes['internal:networks']));
88
        $out .= '</strong><p>';
89
90
        $out .= _("The installer will create cat_installer sub-directory in your config directory (possubly the .config in your home directory) and will copy your server certificates there.");
91
        if ($this->selectedEap == \core\common\EAP::EAPTYPE_TLS) {
92
            $out .= _("In order to connect to the network you will need a personal certificate in the form of a p12 file. You should obtain this certificate from your organisation. Consult the support page to find out how this certificate can be obtained. Such certificate files are password protected. You should have both the file and the password available during the installation process. Your p12 file will also be copied to the cat_installer directory.");
93
        } elseif ($this->selectedEap != \core\common\EAP::EAPTYPE_SILVERBULLET) {
94
            $out .= _("In order to connect to the network you will need an account from your organisation. You should consult the support page to find out how this account can be obtained. It is very likely that your account is already activated.");
95
            $out .= "<p>";
96
            $out .= _("You will be requested to enter your account credentials during the installation. This information will be saved so that you will reconnect to the network automatically each time you are in the range.");
97
        }
98
        // nothing to say if we are doing silverbullet.
99
        $out .= "<p>";
100
        \core\common\Entity::outOfThePotatoes();
101
        return $out;
102
    }
103
    
104
    /**
105
     * writes a line of Python code into the installer script
106
     * 
107
     * @param resource $file   the file handle
108
     * @param string   $prefix prefix to write
109
     * @param string   $name   config item to write
110
     * @param string   $text   text to write
111
     * @return void
112
     */
113
    private function writeConfigLine($file, $prefix, $name, $text) {
114
        $out = $prefix . $name . ' = "' . $text;
115
        fwrite($file, wordwrap($out, 70, " \" \\\n    \"") . "\n");
116
    }
117
    
118
    /**
119
     * localises the user messages and writes them into the file
120
     * 
121
     * @param resource $file the file resource of the installer script
122
     * @return void
123
     */
124
    private function writeMessages($file) {
125
        \core\common\Entity::intoThePotatoes();
126
        $messages = [
127
        'quit'=> _("Really quit?"),
128
        'username_prompt'=> _("enter your userid"),
129
        'enter_password' => _("enter password"),
130
        'enter_import_password' => _("enter your import password"),
131
        'incorrect_password' => _("incorrect password"),
132
        'repeat_password' => _("repeat your password"),
133
        'passwords_differ'=> _("passwords do not match"),
134
        'installation_finished' => _("Installation successful"),
135
        'cat_dir_exisits' => _("Directory {} exists; some of its files may be overwritten."),
136
        'cont' => _("Continue?"),
137
        'nm_not_supported' => _("This NetworkManager version is not supported"),
138
        'cert_error' => _("Certificate file not found, looks like a CAT error"),
139
        'unknown_version' => _("Unknown version"),
140
        'dbus_error' => _("DBus connection problem, a sudo might help"),
141
        'yes' => _("Y"),
142
        'no' => _("N"),
143
        'p12_filter' => _("personal certificate file (p12 or pfx)"),
144
        'all_filter' => _("All files"),
145
        'p12_title' => _("personal certificate file (p12 or pfx)"),
146
        'save_wpa_conf' => _("NetworkManager configuration failed, but we may generate a wpa_supplicant configuration file if you wish. Be warned that your connection password will be saved in this file as clear text."),
147
        'save_wpa_confirm' => _("Write the file"),
148
        'wrongUsernameFormat' =>_("Error: Your username must be of the form 'xxx@institutionID' e.g. '[email protected]'!"),
149
        'wrong_realm' => _("Error: your username must be in the form of 'xxx@{}'. Please enter the username in the correct format."),
150
        'wrong_realm_suffix' => _("Error: your username must be in the form of 'xxx@institutionID' and end with '{}'. Please enter the username in the correct format."),
151
        'user_cert_missing' => _("personal certificate file not found"),
152
        ];
153
        foreach ($messages as $name => $value) {
154
            $this->writeConfigLine($file, 'Messages.', $name, $value . '"');
155
        }
156
        \core\common\Entity::outOfThePotatoes();
157
    }
158
159
    /**
160
     * writes configuration variables into the installer script
161
     * 
162
     * @param resource $file the file handle
163
     * @return void
164
     */
165
    private function writeConfigVars($file) {
166
        $eapMethod = \core\common\EAP::eapDisplayName($this->selectedEap);
167
        $contacts = $this->mkSupportContacts();
168
        $tou = $this->mkUserConsent();
169
        $outerId = $this->determineOuterIdString();
170
        $config = [
171
            'instname' => $this->attributes['general:instname'][0],
172
            'profilename' => $this->attributes['profile:name'][0],
173
            'url' => $contacts['url'],
174
            'email' => $contacts['email'],
175
            'title' => "eduroam CAT",
176
            'server_match' => $this->glueServerNames(),
177
            'eap_outer' => $eapMethod['OUTER'],
178
            'eap_inner' => $eapMethod['INNER'],
179
            'init_info' => $this->mkIntro(),
180
            'init_confirmation' => $this->mkProfileConfirmation(),
181
//            'sb_user_file' => $this->mkSbUserFile(),
182
        ];
183
        
184
        $configRaw = [
185
            'ssids' => $this->mkSsidList(),
186
            'del_ssids' => $this->mkDelSsidList(),
187
            'servers' => $this->mkSubjectAltNameList(),
188
        ];
189
            
190
        if ($this->selectedEap == \core\common\EAP::EAPTYPE_TLS && isset($this->attributes['eap-specific:tls_use_other_id']) && $this->attributes['eap-specific:tls_use_other_id'][0] == 'on') {
191
            $configRaw['use_other_tls_id'] = "True";
192
        }
193
        else {
194
            $configRaw['use_other_tls_id'] = "False";
195
        }
196
197
        if ($outerId !== NULL) {
198
            $configRaw['anonymous_identity'] = '"' . $outerId . '"';
199
        }
200
201
        if (!empty($this->attributes['internal:realm'][0])) {
202
           $config['user_realm'] = $this->attributes['internal:realm'][0];
203
        }
204
        
205
        if(!empty($this->attributes['internal:hint_userinput_suffix'][0]) && $this->attributes['internal:hint_userinput_suffix'][0] == 1) {
206
            $configRaw['hint_user_input'] = "True";
207
        }
208
        
209
        if(!empty($this->attributes['internal:verify_userinput_suffix'][0]) && $this->attributes['internal:verify_userinput_suffix'][0] == 1) {
210
            $configRaw['verify_user_realm_input'] = "True";
211
        }
212
        
213
        foreach ($config as $name => $value) {
214
            $this->writeConfigLine($file, 'Config.', $name, $value . '"');
215
        }
216
        
217
        foreach ($configRaw as $name => $value) {
218
            fwrite($file, 'Config.' . $name . ' = ' . $value . "\n");
219
        }
220
        
221
        if ($tou === '') {
222
            fwrite($file, 'Config.tou = ""' . "\n");
223
        } else {
224
            fwrite($file, 'Config.tou = """' . $tou . '"""' . "\n");
225
        }
226
        
227
        fwrite($file, 'Config.CA = """' . $this->mkCAfile() . '"""' . "\n");
228
        $sbUserFile = $this->mkSbUserFile();
229
        if ($sbUserFile !== '') {
230
            fwrite($file, 'Config.sb_user_file = """' . $sbUserFile . '"""' . "\n");
231
        }
232
    }
233
234
    /**
235
     * coerces the list of EAP server names into a single string
236
     * 
237
     * @return string
238
     */
239
    private function glueServerNames() {
240
        $serverList = $this->attributes['eap:server_name'];        
241
        if (!$serverList) {
242
            return '';
243
        }
244
        $A0 = array_reverse(explode('.', array_shift($serverList)));
245
        $B = $A0;
246
        foreach ($serverList as $oneServer) {
247
            $A = array_reverse(explode('.', $oneServer));
248
            $B = array_intersect_assoc($A0, $A);
249
            $A0 = $B;
250
        }
251
        return implode('.', array_reverse($B));
252
    }
253
254
    /**
255
     * generates the list of support contacts
256
     * 
257
     * @return array
258
     */
259
    private function mkSupportContacts() {
260
        $url = (!empty($this->attributes['support:url'][0])) ? $this->attributes['support:url'][0] : $this->support_url_substitute;
261
        $email = (!empty($this->attributes['support:email'][0])) ? $this->attributes['support:email'][0] : $this->support_email_substitute;
262
        return ['url'=>$url, 'email'=>$email];
263
    }   
264
    
265
    /**
266
     * generates the list of subjectAltNames to configure
267
     * 
268
     * @return string
269
     */
270
    private function mkSubjectAltNameList() {
271
        $serverList = $this->attributes['eap:server_name'];
272
        if (!$serverList) {
273
            return '';
274
        }
275
        $out = '';
276
        foreach ($serverList as $oneServer) {
277
            if ($out) {
278
                $out .= ', ';
279
            }
280
            $out .= "'DNS:$oneServer'";
281
        }
282
        return "[" . $out. "]";
283
    }
284
285
    /**
286
     * generates the list of SSIDs to configure
287
     * 
288
     * @return string
289
     */
290
    private function mkSsidList() {
291
        $networks = $this->attributes['internal:networks'];
292
        $outArray = [];
293
        foreach ($networks as $network => $networkDetails) {
294
            if (!empty($networkDetails['ssid'])) {
295
                $outArray = array_merge($outArray, $networkDetails['ssid']);
296
            }
297
        }
298
        return "['" . implode("', '", $outArray) . "']";
299
    }
300
    
301
    /**
302
     * generates the list of SSIDs to delete from the system
303
     * 
304
     * @return string
305
     */
306
    private function mkDelSsidList() {
307
        $outArray = [];
308
        $delSSIDs = $this->attributes['internal:remove_SSID'];
309
        foreach ($delSSIDs as $ssid => $cipher) {
310
            if ($cipher == 'DEL') {
311
                $outArray[] = "'$ssid'";
312
            }
313
        }
314
        return '[' . implode(', ', $outArray) . ']';
315
    }
316
    
317
    /**
318
     * creates a blob containing all CA certificates
319
     * 
320
     * @return string
321
     */
322
    private function mkCAfile(){
323
        $out = '';
324
        $cAlist = $this->attributes['internal:CAs'][0];
325
        foreach ($cAlist as $oneCa) {
326
            $out .= $oneCa['pem'];
327
        }
328
        return $out;
329
    }
330
    
331
    /**
332
     * generates the welcome text
333
     * 
334
     * @return string
335
     */
336
    private function mkIntro() {
337
        \core\common\Entity::intoThePotatoes();
338
        $out = _("This installer has been prepared for {0}") . '\n\n' . _("More information and comments:") . '\n\nEMAIL: {1}\nWWW: {2}\n\n' .
339
            _("Installer created with software from the GEANT project.");
340
        \core\common\Entity::outOfThePotatoes();
341
        return $out;
342
    }
343
    
344
    /**
345
     * generates text for the user consent dialog box, if any
346
     * 
347
     * @return string
348
     */
349
    private function mkUserConsent() {
350
        $out = '';
351
        if (isset($this->attributes['support:info_file'])) {
352
            if ($this->attributes['internal:info_file'][0]['mime'] == 'txt') {
353
                $out = $this->attributes['support:info_file'][0];
354
            }
355
        }
356
        return $out;
357
    }
358
    
359
    /**
360
     * generates the warning that the account will only work for inst members
361
     * 
362
     * @return string
363
     */
364
    private function mkProfileConfirmation() {
365
        \core\common\Entity::intoThePotatoes();
366
        if ($this->attributes['internal:profile_count'][0] > 1) {
367
            $out = _("This installer will only work properly if you are a member of {0} and the user group: {1}.");
368
        } else {
369
            $out = _("This installer will only work properly if you are a member of {0}.");
370
        }
371
        \core\common\Entity::outOfThePotatoes();
372
        return $out;
373
    }
374
    
375
376
    /**
377
     * generates the client certificate data for Silberbullet installers
378
     * 
379
     * @return string
380
     */
381
    private function mkSbUserFile() {
382
        if ($this->selectedEap == \core\common\EAP::EAPTYPE_SILVERBULLET) {
383
            return chunk_split(base64_encode($this->clientCert["certdata"]), 64, "\n");
384
        }
385
        return "";
386
    }
387
    
388
}
389