sendRequestToCa()   F
last analyzed

Complexity

Conditions 14
Paths 691

Size

Total Lines 125
Code Lines 88

Duplication

Lines 0
Ratio 0 %

Importance

Changes 3
Bugs 1 Features 0
Metric Value
eloc 88
c 3
b 1
f 0
dl 0
loc 125
rs 2.2851
cc 14
nc 691
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
                $altArray[] = "DNS:" . $oneAltName;
143
            }
144
            $soapPub = $this->initEduPKISoapSession("PUBLIC");
145
            $this->loggerInstance->debug(5, "FIRST ACTUAL SOAP REQUEST (Public, newRequest)!\n");
146
            $this->loggerInstance->debug(5, "PARAM_1: " . $this->eduPkiRaId . "\n");
147
            $this->loggerInstance->debug(5, "PARAM_2: " . $csr["CSR_STRING"] . "\n");
148
            $this->loggerInstance->debug(5, "PARAM_3: ");
149
            $this->loggerInstance->debug(5, $altArray);
150
            $this->loggerInstance->debug(5, "PARAM_4: " . $profile . "\n");
151
            $this->loggerInstance->debug(5, "PARAM_5: " . sha1("notused") . "\n");
152
            $this->loggerInstance->debug(5, "PARAM_6: " . $csr["USERNAME"] . "\n");
153
            $this->loggerInstance->debug(5, "PARAM_7: " . $csr["USERMAIL"] . "\n");
154
            $this->loggerInstance->debug(5, "PARAM_8: " . ProfileSilverbullet::PRODUCTNAME . "\n");
155
            $this->loggerInstance->debug(5, "PARAM_9: false\n");
156
            $soapNewRequest = $soapPub->newRequest(
157
                    $this->eduPkiRaId, # RA-ID
158
                    $csr["CSR_STRING"], # Request im PEM-Format
159
                    $altArray, # altNames
160
                    $profile, # Zertifikatprofil
161
                    sha1($revocationPin), # PIN
162
                    $csr["USERNAME"], # Name des Antragstellers
163
                    $csr["USERMAIL"], # Kontakt-E-Mail
164
                    ProfileSilverbullet::PRODUCTNAME, # Organisationseinheit des Antragstellers
165
                    false                   # Veröffentlichen des Zertifikats?
166
            );
167
            $this->loggerInstance->debug(5, $soapPub->__getLastRequest());
168
            $this->loggerInstance->debug(5, $soapPub->__getLastResponse());
169
            if ($soapNewRequest == 0) {
170
                throw new Exception("Error when sending SOAP request (request serial number was zero). No further details available.");
171
            }
172
            $soapReqnum = intval($soapNewRequest);
173
        } catch (Exception $e) {
174
            // PHP 7.1 can do this much better
175
            if (is_soap_fault($e)) {
176
                throw new Exception("Error when sending SOAP request: " . "{$e->faultcode}:  {
177
                    $e->faultstring
178
                }\n");
179
            }
180
            throw new Exception("Something odd happened while doing the SOAP request:" . $e->getMessage());
181
        }
182
        try {
183
            $soap = $this->initEduPKISoapSession("RA");
184
            // tell the CA the desired expiry date of the new certificate
185
            $expiry = new \DateTime();
186
            $expiry->modify("+$expiryDays day");
187
            $expiry->setTimezone(new \DateTimeZone("UTC"));
188
            $soapExpiryChange = $soap->setRequestParameters(
189
                    $soapReqnum, [
190
                "RaID" => $this->eduPkiRaId,
191
                "Role" => $profile,
192
                "Subject" => $csr['SUBJECT'],
193
                "SubjectAltNames" => $altArray,
194
                "NotBefore" => (new \DateTime())->format('c'),
195
                "NotAfter" => $expiry->format('c'),
196
                    ]
197
            );
198
            if ($soapExpiryChange === FALSE) {
199
                throw new Exception("Error when sending SOAP request (unable to change expiry date).");
200
            }
201
            // retrieve the raw request to prepare for signature and approval
202
            // this seems to come out base64-decoded already; maybe PHP
203
            // considers this "convenience"? But we need it as sent on
204
            // the wire, so re-encode it!
205
            $soapCleartext = $soap->getRawRequest($soapReqnum);
206
207
            $this->loggerInstance->debug(2, "Actual received SOAP response for getRawRequest was:\n\n");
208
            $this->loggerInstance->debug(2, $soap->__getLastResponse());
209
            // for obnoxious reasons, we have to dump the request into a file and let pkcs7_sign read from the file
210
            // rather than just using the string. Grr.
211
            $tempdir = \core\common\Entity::createTemporaryDirectory("test");
212
            file_put_contents($tempdir['dir'] . "/content.txt", $soapCleartext);
213
            // retrieve our RA cert from filesystem                    
214
            // the RA certificates are not needed right now because we
215
            // have resorted to S/MIME signatures with openssl command-line
216
            // rather than the built-in functions. But that may change in
217
            // the future, so let's park these two lines for future use.
218
            // $raCertFile = file_get_contents(ROOT . "/config/SilverbulletClientCerts/edupki-test-ra.pem");
219
            // $raCert = openssl_x509_read($raCertFile);
220
            // $raKey = openssl_pkey_get_private("file://" . ROOT . "/config/SilverbulletClientCerts/edupki-test-ra.clearkey");
221
            // sign the data, using cmdline because openssl_pkcs7_sign produces strange results
222
            // -binary didn't help, nor switch -md to sha1 sha256 or sha512
223
            $this->loggerInstance->debug(2, "Actual content to be signed is this:\n  $soapCleartext\n");
224
            $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;
225
            $this->loggerInstance->debug(2, "Calling openssl smime with following cmdline:   $execCmd\n");
226
            $output = [];
227
            $return = 999;
228
            exec($execCmd, $output, $return);
229
            if ($return !== 0) {
230
                throw new Exception("Non-zero return value from openssl smime!");
231
            }
232
            // and get the signature blob back from the filesystem
233
            $detachedSig = trim(file_get_contents($tempdir['dir'] . "/signature.txt"));
234
            $this->loggerInstance->debug(5, "Request for server approveRequest has parameters:\n");
235
            $this->loggerInstance->debug(5, $soapReqnum . "\n");
236
            $this->loggerInstance->debug(5, $soapCleartext . "\n"); // PHP magically encodes this as base64 while sending!
237
            $this->loggerInstance->debug(5, $detachedSig . "\n");
238
            $soapIssueCert = $soap->approveRequest($soapReqnum, $soapCleartext, $detachedSig);
239
            $this->loggerInstance->debug(5, "approveRequest Request was: \n" . $soap->__getLastRequest());
240
            $this->loggerInstance->debug(5, "approveRequest Response was: \n" . $soap->__getLastResponse());
241
            if ($soapIssueCert === FALSE) {
242
                throw new Exception("The locally approved request was NOT processed by the CA.");
243
            }
244
        } catch (SoapFault $e) {
245
            throw new Exception("SoapFault: Error when sending or receiving SOAP message: " . "{$e->faultcode}: {$e->faultname}: {$e->faultstring}: {$e->faultactor}: {$e->detail}: {$e->headerfault}\n");
246
        } catch (Exception $e) {
247
            throw new Exception("Exception: Something odd happened between the SOAP requests:" . $e->getMessage());
248
        }
249
        return $soapReqnum;
250
    }
251
252
    /**
253
     * Polls the CA regularly until it gets the certificate for the request at hand. Gives up after 5 minutes.
254
     * 
255
     * @param int  $soapReqnum the certificate request for which the cert should be picked up
256
     * @param bool $wait       whether to wait until the cert is issued or return immediately
257
     * @return array|false the certificate along with some meta info, or false if we did not want to wait or got a timeout
258
     * @throws Exception
259
     */
260
    public function pickupFinalCert($soapReqnum, $wait)
261
    {
262
        try {
263
            $soap = $this->initEduPKISoapSession("RA");
264
            $counter = 0;
265
            $parsedCert = FALSE;
266
            $x509 = new common\X509();
267
            while ($parsedCert === FALSE && $counter < 300) {
268
                $soapCert = $soap->getCertificateByRequestSerial($soapReqnum);
269
270
                if (strlen($soapCert) > 10) { // we got the cert
271
                    $parsedCert = $x509->processCertificate($soapCert);
272
                } elseif ($wait) { // let's wait five seconds and try again
273
                    $counter += 5;
274
                    sleep(5);
275
                } else {
276
                    return FALSE; // don't wait, abort without result
277
                }
278
            }
279
            // we should now have an array
280
            if ($parsedCert === FALSE) {
281
                throw new Exception("We did not actually get a certificate after waiting for 5 minutes.");
282
            }
283
            // let's get the CA certificate chain
284
285
            $caInfo = $soap->getCAInfo();
286
            $certList = $x509->splitCertificate($caInfo->CAChain[0]);
287
            // find the root
288
            $theRoot = "";
289
            foreach ($certList as $oneCert) {
290
                $content = $x509->processCertificate($oneCert);
291
                if ($content['root'] == 1) {
292
                    $theRoot = $content;
293
                }
294
            }
295
            if ($theRoot == "") {
296
                throw new Exception("CAInfo has no root certificate for us!");
297
            }
298
        } catch (SoapFault $e) {
299
            throw new Exception("SoapFault: Error when sending or receiving SOAP message: " . "{$e->faultcode}: {$e->faultname}: {$e->faultstring}: {$e->faultactor}: {$e->detail}: {$e->headerfault}\n");
300
        } catch (Exception $e) {
301
            throw new Exception("Exception: Something odd happened between the SOAP requests:" . $e->getMessage());
302
        }
303
        return [
304
            "CERT" => openssl_x509_read($parsedCert['pem']),
305
            "SERIAL" => $parsedCert['full_details']['serialNumber'],
306
            "ISSUER" => $theRoot,
307
            "ROOT" => $theRoot,
308
        ];
309
    }
310
311
    /**
312
     * revokes a certificate
313
     * 
314
     * @param string $serial the serial, as a string because it is a 128 bit number
315
     * @return void
316
     * @throws Exception
317
     */
318
    public function revokeCertificate($serial): void
319
    {
320
        try {
321
            $soap = $this->initEduPKISoapSession("RA");
322
            $soapRevocationSerial = $soap->newRevocationRequest(["Serial", $serial], "");
323
            if ($soapRevocationSerial == 0) {
324
                throw new Exception("Unable to create revocation request, serial number was zero.");
325
            }
326
            // retrieve the raw request to prepare for signature and approval
327
            $soapRawRevRequest = $soap->getRawRevocationRequest($soapRevocationSerial);
328
            if (strlen($soapRawRevRequest) < 10) { // very basic error handling
329
                throw new Exception("Suspiciously short data to sign!");
330
            }
331
            // for obnoxious reasons, we have to dump the request into a file and let pkcs7_sign read from the file
332
            // rather than just using the string. Grr.
333
            $tempdir = \core\common\Entity::createTemporaryDirectory("test");
334
            file_put_contents($tempdir['dir'] . "/content.txt", $soapRawRevRequest);
335
            // retrieve our RA cert from filesystem
336
            // sign the data, using cmdline because openssl_pkcs7_sign produces strange results
337
            // -binary didn't help, nor switch -md to sha1 sha256 or sha512
338
            $this->loggerInstance->debug(5, "Actual content to be signed is this:\n$soapRawRevRequest\n");
339
        $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;
340
            $this->loggerInstance->debug(2, "Calling openssl smime with following cmdline: $execCmd\n");
341
            $output = [];
342
            $return = 999;
343
            exec($execCmd, $output, $return);
344
            if ($return !== 0) {
345
                throw new Exception("Non-zero return value from openssl smime!");
346
            }
347
            // and get the signature blob back from the filesystem
348
            $detachedSig = trim(file_get_contents($tempdir['dir'] . "/signature.txt"));
349
            $soapIssueRev = $soap->approveRevocationRequest($soapRevocationSerial, $soapRawRevRequest, $detachedSig);
350
            if ($soapIssueRev === FALSE) {
351
                throw new Exception("The locally approved revocation request was NOT processed by the CA.");
352
            }
353
        } catch (Exception $e) {
354
            // PHP 7.1 can do this much better
355
            if (is_soap_fault($e)) {
356
                throw new Exception("Error when sending SOAP request: " . "{$e->faultcode}: {$e->faultstring}\n");
357
            }
358
            throw new Exception("Something odd happened while doing the SOAP request:" . $e->getMessage());
359
        }
360
    }
361
362
    /**
363
     * sets up a connection to the eduPKI SOAP interfaces
364
     * There is a public interface and an RA-restricted interface;
365
     * the latter needs an RA client certificate to identify the operator
366
     * 
367
     * @param string $type to which interface should we connect to - "PUBLIC" or "RA"
368
     * @return \SoapClient the connection object
369
     * @throws Exception
370
     */
371
    private function initEduPKISoapSession($type)
372
    {
373
        // set context parameters common to both endpoints
374
        $context_params = [
375
            'http' => [
376
                'timeout' => 60,
377
                'user_agent' => 'Stefan',
378
                'protocol_version' => 1.1
379
            ],
380
            'ssl' => [
381
                'verify_peer' => true,
382
                'verify_peer_name' => true,
383
                // below is the CA "/C=DE/O=Deutsche Telekom AG/OU=T-TeleSec Trust Center/CN=Deutsche Telekom Root CA 2"
384
                'cafile' => $this->locationWebRoot,
385
                'verify_depth' => 5,
386
                'capture_peer_cert' => true,
387
            ],
388
        ];
389
        $url = "";
390
        switch ($type) {
391
            case "PUBLIC":
392
                $url = $this->eduPkiEndpointPublic;
393
                $context_params['ssl']['peer_name'] = 'pki.edupki.org';
394
                break;
395
            case "RA":
396
                $url = $this->eduPkiEndpointRa;
397
                $context_params['ssl']['peer_name'] = 'ra.edupki.org';
398
                break;
399
            default:
400
                throw new Exception("Unknown type of eduPKI interface requested.");
401
        }
402
        if ($type == "RA") { // add client auth parameters to the context
403
            $context_params['ssl']['local_cert'] = $this->locationRaCert;
404
            $context_params['ssl']['local_pk'] = $this->locationRaKey;
405
            // $context_params['ssl']['passphrase'] = SilverbulletCertificate::EDUPKI_RA_PKEY_PASSPHRASE;
406
        }
407
        // initialise connection to eduPKI CA / eduroam RA
408
        $soap = new \SoapClient($url, [
409
            'soap_version' => SOAP_1_1,
410
            'trace' => TRUE,
411
            'exceptions' => TRUE,
412
            'connection_timeout' => 5, // if can't establish the connection within 5 sec, something's wrong
413
            'cache_wsdl' => WSDL_CACHE_NONE,
414
            'user_agent' => 'eduroam CAT to eduPKI SOAP Interface',
415
            'features' => SOAP_SINGLE_ELEMENT_ARRAYS,
416
            'stream_context' => stream_context_create($context_params),
417
            'typemap' => [
418
                [
419
                    'type_ns' => 'http://www.w3.org/2001/XMLSchema',
420
                    'type_name' => 'integer',
421
                    'from_xml' => 'core\CertificationAuthorityEduPkiServer::soapFromXmlInteger',
422
                    'to_xml' => 'core\CertificationAuthorityEduPkiServer::soapToXmlInteger',
423
                ],
424
            ],
425
                ]
426
        );
427
        return $soap;
428
    }
429
430
    /**
431
     * a function that converts integers beyond PHP_INT_MAX to strings for
432
     * sending in XML messages
433
     *
434
     * taken and adapted from 
435
     * https://www.uni-muenster.de/WWUCA/de/howto-special-phpsoap.html
436
     * 
437
     * @param string $x the integer as an XML fragment
438
     * @return array the integer in array notation
439
     */
440
    public function soapFromXmlInteger($x)
441
    {
442
        $y = simplexml_load_string($x);
443
        return array(
444
            $y->getName(),
445
            $y->__toString()
446
        );
447
    }
448
449
    /**
450
     * a function that converts integers beyond PHP_INT_MAX to strings for
451
     * sending in XML messages
452
     * 
453
     * @param array $x the integer in array notation
454
     * @return string the integer as string in an XML fragment
455
     */
456
    public function soapToXmlInteger($x)
457
    {
458
        return '<' . $x[0] . '>'
459
                . htmlentities($x[1], ENT_NOQUOTES | ENT_XML1)
460
                . '</' . $x[0] . '>';
461
    }
462
463
    /**
464
     * generates a CSR which eduPKI likes (DC components etc.)
465
     * 
466
     * @param \OpenSSLAsymmetricKey $privateKey a private key
467
     * @param string                $fed        name of the federation, for C= field
468
     * @param string                $username   username, for CN= field
469
     * @return array the CSR along with some meta information
470
     * @throws Exception
471
     */
472
    public function generateCompatibleCsr($privateKey, $fed, $username): array
473
    {
474
        $tempdirArray = \core\common\Entity::createTemporaryDirectory("test");
475
        $tempdir = $tempdirArray['dir'];
476
        // dump private key into directory
477
        $outstring = "";
478
        openssl_pkey_export($privateKey, $outstring);
479
        file_put_contents($tempdir . "/pkey.pem", $outstring);
480
        // PHP can only do one DC in the Subject. But we need three.
481
        $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";
482
        $this->loggerInstance->debug(2, "Calling openssl req with following cmdline: $execCmd\n");
483
        $output = [];
484
        $return = 999;
485
        exec($execCmd, $output, $return);
486
        if ($return !== 0) {
487
            throw new Exception("Non-zero return value from openssl req!");
488
        }
489
        $newCsr = file_get_contents("$tempdir/request.csr");
490
        // remove the temp dir!
491
        unlink("$tempdir/pkey.pem");
492
        unlink("$tempdir/request.csr");
493
        rmdir($tempdir);
494
        if ($newCsr === FALSE) {
495
            throw new Exception("Unable to create a CSR!");
496
        }
497
        return [
498
            "CSR_STRING" => $newCsr, // a string
499
            "CSR_OBJECT" => NULL,
500
            "USERNAME" => $username,
501
            "FED" => $fed
502
        ];
503
    }
504
505
    /**
506
     * generates a private key eduPKI can handle
507
     * 
508
     * @return \OpenSSLAsymmetricKey the key
509
     * @throws Exception
510
     */
511
    public function generateCompatiblePrivateKey()
512
    {
513
        $key = openssl_pkey_new(['private_key_bits' => 2048, 'private_key_type' => OPENSSL_KEYTYPE_RSA, 'encrypt_key' => FALSE]);
514
        if ($key === FALSE || is_resource($key)) {
515
            throw new Exception("Unable to generate a private key / not a PHP8 object.");
516
        }
517
        return $key;
518
    }
519
520
    /**
521
     * CAs don't have any local caching or other freshness issues
522
     * 
523
     * @return void
524
     */
525
    public function updateFreshness()
526
    {
527
        // nothing to be done here.
528
    }
529
}
530