Passed
Push — release_2_1 ( 645d9f...61624e )
by Stefan
08:41
created

CertificationAuthorityEduPkiServer::triggerNewOCSPStatement()   A

Complexity

Conditions 1
Paths 1

Size

Total Lines 4
Code Lines 2

Duplication

Lines 0
Ratio 0 %

Importance

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