sendRequestToCa()   F
last analyzed

Complexity

Conditions 16
Paths 1117

Size

Total Lines 133
Code Lines 92

Duplication

Lines 0
Ratio 0 %

Importance

Changes 3
Bugs 1 Features 0
Metric Value
eloc 92
c 3
b 1
f 0
dl 0
loc 133
rs 1.2945
cc 16
nc 1117
nop 3

How to fix   Long Method    Complexity   

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
namespace core;
13
14
use \Exception;
0 ignored issues
show
Bug introduced by
The type \Exception was not found. Maybe you did not declare it correctly or list all dependencies?

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

filter:
    dependency_paths: ["lib/*"]

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

Loading history...
15
use \SoapFault;
0 ignored issues
show
Bug introduced by
The type \SoapFault was not found. Maybe you did not declare it correctly or list all dependencies?

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

filter:
    dependency_paths: ["lib/*"]

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

Loading history...
16
17
class CertificationAuthorityEduPkiServer extends EntityWithDBProperties implements CertificationAuthorityInterface
18
{
19
    private $locationRaCert;
20
    private $locationRaKey;
21
    private $locationWebRoot;
22
    private $eduPkiRaId;
23
    private $eduPkiCertProfileBoth;
24
    private $eduPkiCertProfileIdp;
25
    private $eduPkiCertProfileSp;
26
    private $eduPkiRaPkeyPassphrase;
27
    private $eduPkiEndpointPublic;
28
    private $eduPkiEndpointRa;
29
30
    /**
31
     * sets up the environment so that we can talk to eduPKI
32
     * 
33
     * @throws Exception
34
     */
35
    public function __construct()
36
    {
37
            
38
        if ( \config\ConfAssistant::eduPKI['testing'] === true ) {
39
            $this->locationRaCert = ROOT . "/config/SilverbulletClientCerts/edupki-test-ra.pem";
40
            $this->locationRaKey = ROOT . "/config/SilverbulletClientCerts/edupki-test-ra.clearkey";
41
            $this->locationWebRoot = ROOT . "/config/SilverbulletClientCerts/eduPKI-webserver-root.pem";
42
            $this->eduPkiRaId = 700;
43
            $this->eduPkiCertProfileBoth = "Radius Server SOAP";
44
            $this->eduPkiCertProfileIdp = "Radius Server SOAP";
45
            $this->eduPkiCertProfileSp = "Radius Server SOAP";
46
            $this->eduPkiRaPkeyPassphrase = "...";
47
            $this->eduPkiEndpointPublic = "https://pki.edupki.org/edupki-test-ca/cgi-bin/pub/soap?wsdl=1";
48
            $this->eduPkiEndpointRa = "https://ra.edupki.org/edupki-test-ca/cgi-bin/ra/soap?wsdl=1";
49
        } else {
50
            $this->locationRaCert = ROOT . "/config/SilverbulletClientCerts/edupki-prod-ra.pem";
51
            $this->locationRaKey = ROOT . "/config/SilverbulletClientCerts/edupki-prod-ra.clearkey";
52
            $this->locationWebRoot = ROOT . "/config/SilverbulletClientCerts/eduPKI-webserver-root.pem";
53
            $this->eduPkiRaId = 100;
54
            $this->eduPkiCertProfileBoth = "eduroam IdP and SP";
55
            $this->eduPkiCertProfileIdp = "eduroam IdP";
56
            $this->eduPkiCertProfileSp = "eduroam SP";
57
            $this->eduPkiRaPkeyPassphrase = "...";
58
            $this->eduPkiEndpointPublic = "https://pki.edupki.org/edupki-ca/cgi-bin/pub/soap?wsdl=1";
59
            $this->eduPkiEndpointRa = "https://ra.edupki.org/edupki-ca/cgi-bin/ra/soap?wsdl=1";        
60
        }
61
        
62
        $this->databaseType = "INST";
63
        parent::__construct();
64
65
        if (stat($this->locationRaCert) === FALSE) {
66
            throw new Exception("RA operator PEM file not found: " . $this->locationRaCert);
67
        }
68
        if (stat($this->locationRaKey) === FALSE) {
69
            throw new Exception("RA operator private key file not found: " . $this->locationRaKey);
70
        }
71
        if (stat($this->locationWebRoot) === FALSE) {
72
            throw new Exception("CA website root CA file not found: " . $this->locationWebRoot);
73
        }
74
    }
75
76
    /**
77
     * Creates an updated OCSP statement. Nothing to be done here - eduPKI have
78
     * their own OCSP responder and the certs point to it. So we are not in the 
79
     * loop.
80
     * 
81
     * @param string $serial serial number of the certificate. Serials are 128 bit, so forcibly a string.
82
     * @return string a dummy string instead of a real statement
83
     */
84
    public function triggerNewOCSPStatement($serial): string
85
    {
86
        unset($serial); // not needed
87
        return "EXTERNAL";
88
    }
89
90
    /**
91
     * signs a CSR and returns the certificate (blocking wait)
92
     * 
93
     * @param array  $csr        the request metadata
94
     * @param integer $expiryDays how many days should the certificate be valid
95
     * @return array the certificate with some meta info
96
     * @throws Exception
97
     */
98
    public function signRequest($csr, $expiryDays): array
99
    {
100
        if ($csr["CSR_STRING"] === NULL) {
101
            throw new Exception("This CA needs the CSR in a string (PEM)!");
102
        }
103
        $revocationPin = common\Entity::randomString(10, "abcdefghijklmnopqrstuvwxyzABCDEFGHIJKLMNOPQRSTUVWXYZ0123456789");
104
        $soapReqnum = $this->sendRequestToCa($csr, $revocationPin, $expiryDays);
105
        sleep(55);
106
        // now, get the actual cert from the CA
107
        $returnValue = $this->pickupFinalCert($soapReqnum, TRUE);
108
        if ($returnValue === FALSE) {
109
            throw new Exception("We wanted to wait, but still got no cert!");
110
        }
111
        return $returnValue;
112
    }
113
114
    /**
115
     * sends the request to the CA and asks for the certificate. Does not block
116
     * until the certificate is issued, it needs to be picked up separately
117
     * using its request number.
118
     * 
119
     * @param array  $csr           the CSR to sign. The member $csr['CSR'] must contain the CSR in *PEM* format
120
     * @param string $revocationPin a PIN to be able to revoke the cert later on
121
     * @param int    $expiryDays    how many days should the certificate be valid
122
     * @return int the request serial number
123
     * @throws Exception
124
     */
125
    public function sendRequestToCa($csr, $revocationPin, $expiryDays): int
126
    {
127
        // initialise connection to eduPKI CA / eduroam RA and send the request to them
128
        try {            
129
            if (in_array("eduroam IdP", $csr["POLICIES"]) && in_array("eduroam SP", $csr["POLICIES"])) {
130
                $profile = $this->eduPkiCertProfileBoth;
131
            } elseif (in_array("eduroam IdP", $csr["POLICIES"])) {
132
                $profile = $this->eduPkiCertProfileIdp;
133
            } elseif (in_array("eduroam SP", $csr["POLICIES"])) {
134
                $profile = $this->eduPkiCertProfileSp;
135
            } else {
136
                throw new Exception("Unexpected policies requested.");
137
            }
138
            $altArray = [# Array mit den Subject Alternative Names
139
                "email:" . $csr["USERMAIL"]
140
            ];
141
            foreach ($csr["ALTNAMES"] as $oneAltName) {
142
                if (!empty($oneAltName) && preg_match('/(?=^.{1,254}$)(^(?:(?!\d|-)[a-z0-9\-]{1,63}(?<!-)\.)+(?:[a-z]{2,})$)/i', $oneAltName) > 0) {
143
                    $altArray[] = "DNS:" . $oneAltName;
144
                } else {
145
                    $altArray[] = "IP:" . $oneAltName;
146
                }
147
            }
148
            $soapPub = $this->initEduPKISoapSession("PUBLIC");
149
            $this->loggerInstance->debug(5, "FIRST ACTUAL SOAP REQUEST (Public, newRequest)!\n");
150
            $this->loggerInstance->debug(5, "PARAM_1: " . $this->eduPkiRaId . "\n");
151
            $this->loggerInstance->debug(5, "PARAM_2: " . $csr["CSR_STRING"] . "\n");
152
            $this->loggerInstance->debug(5, "PARAM_3: ");
153
            $this->loggerInstance->debug(5, $altArray);
154
            $this->loggerInstance->debug(5, "PARAM_4: " . $profile . "\n");
155
            $this->loggerInstance->debug(5, "PARAM_5: " . sha1("notused") . "\n");
156
            $this->loggerInstance->debug(5, "PARAM_6: " . $csr["USERNAME"] . "\n");
157
            $this->loggerInstance->debug(5, "PARAM_7: " . $csr["USERMAIL"] . "\n");
158
            $this->loggerInstance->debug(5, "PARAM_8: " . ProfileSilverbullet::PRODUCTNAME . "\n");
159
            $this->loggerInstance->debug(5, "PARAM_9: false\n");
160
            
161
            $soapNewRequest = $soapPub->newRequest(
162
                    $this->eduPkiRaId, # RA-ID
163
                    $csr["CSR_STRING"], # Request im PEM-Format
164
                    $altArray, # altNames
165
                    $profile, # Zertifikatprofil
166
                    sha1($revocationPin), # PIN
167
                    $csr["USERNAME"], # Name des Antragstellers
168
                    $csr["USERMAIL"], # Kontakt-E-Mail
169
                    ProfileSilverbullet::PRODUCTNAME, # Organisationseinheit des Antragstellers
170
                    false                   # Veröffentlichen des Zertifikats?
171
            );
172
            $this->loggerInstance->debug(5, $soapPub->__getLastRequest());
173
            $this->loggerInstance->debug(5, $soapPub->__getLastResponse());
174
            if ($soapNewRequest == 0) {
175
                throw new Exception("Error when sending SOAP request (request serial number was zero). No further details available.");
176
            }
177
            $soapReqnum = intval($soapNewRequest);
178
        } catch (Exception $e) {
179
            // PHP 7.1 can do this much better
180
            if (is_soap_fault($e)) {
181
                $_SESSION['CSR_ERRORS'] = 'SOAP_ERROR';
182
                $_SESSION['csr_faultcode'] = $e->faultstring;
183
                #throw new Exception("Error when sending SOAP request: " . "{$e->faultcode}:  {
184
                #    $e->faultstring
185
                #}\n");
186
                return 0;
187
            }
188
            throw new Exception("Something odd happened while doing the SOAP request:" . $e->getMessage());
189
        }
190
        try {
191
            $soap = $this->initEduPKISoapSession("RA");
192
            // tell the CA the desired expiry date of the new certificate
193
            $expiry = new \DateTime();
194
            $expiry->modify("+$expiryDays day");
195
            $expiry->setTimezone(new \DateTimeZone("UTC"));
196
            $soapExpiryChange = $soap->setRequestParameters(
197
                    $soapReqnum, [
198
                "RaID" => $this->eduPkiRaId,
199
                "Role" => $profile,
200
                "Subject" => $csr['SUBJECT'],
201
                "SubjectAltNames" => $altArray,
202
                "NotBefore" => (new \DateTime())->format('c'),
203
                "NotAfter" => $expiry->format('c'),
204
                    ]
205
            );
206
            if ($soapExpiryChange === FALSE) {
207
                throw new Exception("Error when sending SOAP request (unable to change expiry date).");
208
            }
209
            // retrieve the raw request to prepare for signature and approval
210
            // this seems to come out base64-decoded already; maybe PHP
211
            // considers this "convenience"? But we need it as sent on
212
            // the wire, so re-encode it!
213
            $soapCleartext = $soap->getRawRequest($soapReqnum);
214
215
            $this->loggerInstance->debug(2, "Actual received SOAP response for getRawRequest was:\n\n");
216
            $this->loggerInstance->debug(2, $soap->__getLastResponse());
217
            // for obnoxious reasons, we have to dump the request into a file and let pkcs7_sign read from the file
218
            // rather than just using the string. Grr.
219
            $tempdir = \core\common\Entity::createTemporaryDirectory("test");
220
            file_put_contents($tempdir['dir'] . "/content.txt", $soapCleartext);
221
            // retrieve our RA cert from filesystem                    
222
            // the RA certificates are not needed right now because we
223
            // have resorted to S/MIME signatures with openssl command-line
224
            // rather than the built-in functions. But that may change in
225
            // the future, so let's park these two lines for future use.
226
            // $raCertFile = file_get_contents(ROOT . "/config/SilverbulletClientCerts/edupki-test-ra.pem");
227
            // $raCert = openssl_x509_read($raCertFile);
228
            // $raKey = openssl_pkey_get_private("file://" . ROOT . "/config/SilverbulletClientCerts/edupki-test-ra.clearkey");
229
            // sign the data, using cmdline because openssl_pkcs7_sign produces strange results
230
            // -binary didn't help, nor switch -md to sha1 sha256 or sha512
231
            $this->loggerInstance->debug(2, "Actual content to be signed is this:\n  $soapCleartext\n");
232
            $execCmd = \config\Master::PATHS['openssl'] . " smime -sign -binary -in " . $tempdir['dir'] . "/content.txt -out " . $tempdir['dir'] . "/signature.txt -outform pem -inkey " . $this->locationRaKey . " -signer " . $this->locationRaCert;
233
            $this->loggerInstance->debug(2, "Calling openssl smime with following cmdline:   $execCmd\n");
234
            $output = [];
235
            $return = 999;
236
            exec($execCmd, $output, $return);
237
            if ($return !== 0) {
238
                throw new Exception("Non-zero return value from openssl smime!");
239
            }
240
            // and get the signature blob back from the filesystem
241
            $detachedSig = trim(file_get_contents($tempdir['dir'] . "/signature.txt"));
242
            $this->loggerInstance->debug(5, "Request for server approveRequest has parameters:\n");
243
            $this->loggerInstance->debug(5, $soapReqnum . "\n");
244
            $this->loggerInstance->debug(5, $soapCleartext . "\n"); // PHP magically encodes this as base64 while sending!
245
            $this->loggerInstance->debug(5, $detachedSig . "\n");
246
            $soapIssueCert = $soap->approveRequest($soapReqnum, $soapCleartext, $detachedSig);
247
            $this->loggerInstance->debug(5, "approveRequest Request was: \n" . $soap->__getLastRequest());
248
            $this->loggerInstance->debug(5, "approveRequest Response was: \n" . $soap->__getLastResponse());
249
            if ($soapIssueCert === FALSE) {
250
                throw new Exception("The locally approved request was NOT processed by the CA.");
251
            }
252
        } catch (SoapFault $e) {
253
            throw new Exception("SoapFault: Error when sending or receiving SOAP message: " . "{$e->faultcode}: {$e->faultname}: {$e->faultstring}: {$e->faultactor}: {$e->detail}: {$e->headerfault}\n");
254
        } catch (Exception $e) {
255
            throw new Exception("Exception: Something odd happened between the SOAP requests:" . $e->getMessage());
256
        }
257
        return $soapReqnum;
258
    }
259
260
    /**
261
     * Polls the CA regularly until it gets the certificate for the request at hand. Gives up after 5 minutes.
262
     * 
263
     * @param int  $soapReqnum the certificate request for which the cert should be picked up
264
     * @param bool $wait       whether to wait until the cert is issued or return immediately
265
     * @return array|false the certificate along with some meta info, or false if we did not want to wait or got a timeout
266
     * @throws Exception
267
     */
268
    public function pickupFinalCert($soapReqnum, $wait)
269
    {
270
        try {
271
            $soap = $this->initEduPKISoapSession("RA");
272
            $counter = 0;
273
            $parsedCert = FALSE;
274
            $x509 = new common\X509();
275
            while ($parsedCert === FALSE && $counter < 300) {
276
                $soapCert = $soap->getCertificateByRequestSerial($soapReqnum);
277
278
                if (strlen($soapCert) > 10) { // we got the cert
279
                    $parsedCert = $x509->processCertificate($soapCert);
280
                } elseif ($wait) { // let's wait five seconds and try again
281
                    $counter += 5;
282
                    sleep(5);
283
                } else {
284
                    return FALSE; // don't wait, abort without result
285
                }
286
            }
287
            // we should now have an array
288
            if ($parsedCert === FALSE) {
289
                throw new Exception("We did not actually get a certificate after waiting for 5 minutes.");
290
            }
291
            // let's get the CA certificate chain
292
293
            $caInfo = $soap->getCAInfo();
294
            $certList = $x509->splitCertificate($caInfo->CAChain[0]);
295
            // find the root
296
            $theRoot = "";
297
            foreach ($certList as $oneCert) {
298
                $content = $x509->processCertificate($oneCert);
299
                if ($content['root'] == 1) {
300
                    $theRoot = $content;
301
                }
302
            }
303
            if ($theRoot == "") {
304
                throw new Exception("CAInfo has no root certificate for us!");
305
            }
306
        } catch (SoapFault $e) {
307
            throw new Exception("SoapFault: Error when sending or receiving SOAP message: " . "{$e->faultcode}: {$e->faultname}: {$e->faultstring}: {$e->faultactor}: {$e->detail}: {$e->headerfault}\n");
308
        } catch (Exception $e) {
309
            throw new Exception("Exception: Something odd happened between the SOAP requests:" . $e->getMessage());
310
        }
311
        return [
312
            "CERT" => openssl_x509_read($parsedCert['pem']),
313
            "SERIAL" => $parsedCert['full_details']['serialNumber'],
314
            "ISSUER" => $theRoot,
315
            "ROOT" => $theRoot,
316
        ];
317
    }
318
319
    /**
320
     * revokes a certificate
321
     * 
322
     * @param string $serial the serial, as a string because it is a 128 bit number
323
     * @return void
324
     * @throws Exception
325
     */
326
    public function revokeCertificate($serial): void
327
    {
328
        try {
329
            $soap = $this->initEduPKISoapSession("RA");
330
            $soapRevocationSerial = $soap->newRevocationRequest(["Serial", $serial], "");
331
            if ($soapRevocationSerial == 0) {
332
                throw new Exception("Unable to create revocation request, serial number was zero.");
333
            }
334
            // retrieve the raw request to prepare for signature and approval
335
            $soapRawRevRequest = $soap->getRawRevocationRequest($soapRevocationSerial);
336
            if (strlen($soapRawRevRequest) < 10) { // very basic error handling
337
                throw new Exception("Suspiciously short data to sign!");
338
            }
339
            // for obnoxious reasons, we have to dump the request into a file and let pkcs7_sign read from the file
340
            // rather than just using the string. Grr.
341
            $tempdir = \core\common\Entity::createTemporaryDirectory("test");
342
            file_put_contents($tempdir['dir'] . "/content.txt", $soapRawRevRequest);
343
            // retrieve our RA cert from filesystem
344
            // sign the data, using cmdline because openssl_pkcs7_sign produces strange results
345
            // -binary didn't help, nor switch -md to sha1 sha256 or sha512
346
            $this->loggerInstance->debug(5, "Actual content to be signed is this:\n$soapRawRevRequest\n");
347
        $execCmd = \config\Master::PATHS['openssl'] . " smime -sign -binary -in " . $tempdir['dir'] . "/content.txt -out " . $tempdir['dir'] . "/signature.txt -outform pem -inkey " . $this->locationRaKey . " -signer " . $this->locationRaCert;
348
            $this->loggerInstance->debug(2, "Calling openssl smime with following cmdline: $execCmd\n");
349
            $output = [];
350
            $return = 999;
351
            exec($execCmd, $output, $return);
352
            if ($return !== 0) {
353
                throw new Exception("Non-zero return value from openssl smime!");
354
            }
355
            // and get the signature blob back from the filesystem
356
            $detachedSig = trim(file_get_contents($tempdir['dir'] . "/signature.txt"));
357
            $soapIssueRev = $soap->approveRevocationRequest($soapRevocationSerial, $soapRawRevRequest, $detachedSig);
358
            if ($soapIssueRev === FALSE) {
359
                throw new Exception("The locally approved revocation request was NOT processed by the CA.");
360
            }
361
        } catch (Exception $e) {
362
            // PHP 7.1 can do this much better
363
            if (is_soap_fault($e)) {
364
                throw new Exception("Error when sending SOAP request: " . "{$e->faultcode}: {$e->faultstring}\n");
365
            }
366
            throw new Exception("Something odd happened while doing the SOAP request:" . $e->getMessage());
367
        }
368
    }
369
370
    /**
371
     * sets up a connection to the eduPKI SOAP interfaces
372
     * There is a public interface and an RA-restricted interface;
373
     * the latter needs an RA client certificate to identify the operator
374
     * 
375
     * @param string $type to which interface should we connect to - "PUBLIC" or "RA"
376
     * @return \SoapClient the connection object
377
     * @throws Exception
378
     */
379
    private function initEduPKISoapSession($type)
380
    {
381
        // set context parameters common to both endpoints
382
        $context_params = [
383
            'http' => [
384
                'timeout' => 60,
385
                'user_agent' => 'Stefan',
386
                'header'=> "Accept-language: en",
387
                'protocol_version' => 1.1
388
            ],
389
            
390
            'ssl' => [
391
                'verify_peer' => true,
392
                'verify_peer_name' => true,
393
                // below is the CA "/C=DE/O=Deutsche Telekom AG/OU=T-TeleSec Trust Center/CN=Deutsche Telekom Root CA 2"
394
                'cafile' => $this->locationWebRoot,
395
                'verify_depth' => 5,
396
                'capture_peer_cert' => true,
397
            ],
398
        ];
399
        $url = "";
400
        switch ($type) {
401
            case "PUBLIC":
402
                $url = $this->eduPkiEndpointPublic;
403
                $context_params['ssl']['peer_name'] = 'pki.edupki.org';
404
                break;
405
            case "RA":
406
                $url = $this->eduPkiEndpointRa;
407
                $context_params['ssl']['peer_name'] = 'ra.edupki.org';
408
                break;
409
            default:
410
                throw new Exception("Unknown type of eduPKI interface requested.");
411
        }
412
        if ($type == "RA") { // add client auth parameters to the context
413
            $context_params['ssl']['local_cert'] = $this->locationRaCert;
414
            $context_params['ssl']['local_pk'] = $this->locationRaKey;
415
            // $context_params['ssl']['passphrase'] = SilverbulletCertificate::EDUPKI_RA_PKEY_PASSPHRASE;
416
        }
417
        // initialise connection to eduPKI CA / eduroam RA
418
        $soap = new \SoapClient($url, [
419
            'soap_version' => SOAP_1_1,
420
            'trace' => TRUE,
421
            'exceptions' => TRUE,
422
            'connection_timeout' => 5, // if can't establish the connection within 5 sec, something's wrong
423
            'cache_wsdl' => WSDL_CACHE_NONE,
424
            'user_agent' => 'eduroam CAT to eduPKI SOAP Interface',
425
            'features' => SOAP_SINGLE_ELEMENT_ARRAYS,
426
            'stream_context' => stream_context_create($context_params),
427
            'typemap' => [
428
                [
429
                    'type_ns' => 'http://www.w3.org/2001/XMLSchema',
430
                    'type_name' => 'integer',
431
                    'from_xml' => 'core\CertificationAuthorityEduPkiServer::soapFromXmlInteger',
432
                    'to_xml' => 'core\CertificationAuthorityEduPkiServer::soapToXmlInteger',
433
                ],
434
            ],
435
                ]
436
        );
437
        return $soap;
438
    }
439
440
    /**
441
     * a function that converts integers beyond PHP_INT_MAX to strings for
442
     * sending in XML messages
443
     *
444
     * taken and adapted from 
445
     * https://www.uni-muenster.de/WWUCA/de/howto-special-phpsoap.html
446
     * 
447
     * @param string $x the integer as an XML fragment
448
     * @return array the integer in array notation
449
     */
450
    public function soapFromXmlInteger($x)
451
    {
452
        $y = simplexml_load_string($x);
453
        return array(
454
            $y->getName(),
455
            $y->__toString()
456
        );
457
    }
458
459
    /**
460
     * a function that converts integers beyond PHP_INT_MAX to strings for
461
     * sending in XML messages
462
     * 
463
     * @param array $x the integer in array notation
464
     * @return string the integer as string in an XML fragment
465
     */
466
    public function soapToXmlInteger($x)
467
    {
468
        return '<' . $x[0] . '>'
469
                . htmlentities($x[1], ENT_NOQUOTES | ENT_XML1)
470
                . '</' . $x[0] . '>';
471
    }
472
473
    /**
474
     * generates a CSR which eduPKI likes (DC components etc.)
475
     * 
476
     * @param \OpenSSLAsymmetricKey $privateKey a private key
477
     * @param string                $fed        name of the federation, for C= field
478
     * @param string                $username   username, for CN= field
479
     * @return array the CSR along with some meta information
480
     * @throws Exception
481
     */
482
    public function generateCompatibleCsr($privateKey, $fed, $username): array
483
    {
484
        $tempdirArray = \core\common\Entity::createTemporaryDirectory("test");
485
        $tempdir = $tempdirArray['dir'];
486
        // dump private key into directory
487
        $outstring = "";
488
        openssl_pkey_export($privateKey, $outstring);
489
        file_put_contents($tempdir . "/pkey.pem", $outstring);
490
        // PHP can only do one DC in the Subject. But we need three.
491
        $execCmd = \config\Master::PATHS['openssl'] . " req -new -sha256 -key $tempdir/pkey.pem -out $tempdir/request.csr -subj /DC=test/DC=test/DC=eduroam/C=$fed/O=" . \config\ConfAssistant::CONSORTIUM['name'] . "/OU=$fed/CN=$username/emailAddress=$username";
492
        $this->loggerInstance->debug(2, "Calling openssl req with following cmdline: $execCmd\n");
493
        $output = [];
494
        $return = 999;
495
        exec($execCmd, $output, $return);
496
        if ($return !== 0) {
497
            throw new Exception("Non-zero return value from openssl req!");
498
        }
499
        $newCsr = file_get_contents("$tempdir/request.csr");
500
        // remove the temp dir!
501
        unlink("$tempdir/pkey.pem");
502
        unlink("$tempdir/request.csr");
503
        rmdir($tempdir);
504
        if ($newCsr === FALSE) {
505
            throw new Exception("Unable to create a CSR!");
506
        }
507
        return [
508
            "CSR_STRING" => $newCsr, // a string
509
            "CSR_OBJECT" => NULL,
510
            "USERNAME" => $username,
511
            "FED" => $fed
512
        ];
513
    }
514
515
    /**
516
     * generates a private key eduPKI can handle
517
     * 
518
     * @return \OpenSSLAsymmetricKey the key
519
     * @throws Exception
520
     */
521
    public function generateCompatiblePrivateKey()
522
    {
523
        $key = openssl_pkey_new(['private_key_bits' => 2048, 'private_key_type' => OPENSSL_KEYTYPE_RSA, 'encrypt_key' => FALSE]);
524
        if ($key === FALSE || is_resource($key)) {
525
            throw new Exception("Unable to generate a private key / not a PHP8 object.");
526
        }
527
        return $key;
528
    }
529
530
    /**
531
     * CAs don't have any local caching or other freshness issues
532
     * 
533
     * @return void
534
     */
535
    public function updateFreshness()
536
    {
537
        // nothing to be done here.
538
    }
539
}
540