Passed
Push — release_2_1 ( 486317...21e7c1 )
by Stefan
26:06 queued 10s
created

updateFreshness()   A

Complexity

Conditions 1
Paths 1

Size

Total Lines 2
Code Lines 0

Duplication

Lines 0
Ratio 0 %

Importance

Changes 0
Metric Value
eloc 0
c 0
b 0
f 0
dl 0
loc 2
rs 10
cc 1
nc 1
nop 0
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 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
28
    
29
    private const LOCATION_RA_CERT = ROOT . "/config/SilverbulletClientCerts/edupki-test-ra.pem";
30
    private const LOCATION_RA_KEY = ROOT . "/config/SilverbulletClientCerts/edupki-test-ra.clearkey";
31
    private const LOCATION_WEBROOT = ROOT . "/config/SilverbulletClientCerts/eduPKI-webserver-root.pem";
32
    private const EDUPKI_RA_ID = 700;
33
    private const EDUPKI_CERT_PROFILE_BOTH = "Radius Server SOAP";
34
    private const EDUPKI_CERT_PROFILE_IDP = "Radius Server SOAP";
35
    private const EDUPKI_CERT_PROFILE_SP = "Radius Server SOAP";
36
    private const EDUPKI_RA_PKEY_PASSPHRASE = "...";
37
38
    /**
39
     * sets up the environment so that we can talk to eduPKI
40
     * 
41
     * @throws Exception
42
     */
43
    public function __construct()
44
    {
45
        $this->databaseType = "INST";
46
        parent::__construct();
47
48
        if (stat(CertificationAuthorityEduPkiServer::LOCATION_RA_CERT) === FALSE) {
49
            throw new Exception("RA operator PEM file not found: " . CertificationAuthorityEduPkiServer::LOCATION_RA_CERT);
50
        }
51
        if (stat(CertificationAuthorityEduPkiServer::LOCATION_RA_KEY) === FALSE) {
52
            throw new Exception("RA operator private key file not found: " . CertificationAuthorityEduPkiServer::LOCATION_RA_KEY);
53
        }
54
        if (stat(CertificationAuthorityEduPkiServer::LOCATION_WEBROOT) === FALSE) {
55
            throw new Exception("CA website root CA file not found: " . CertificationAuthorityEduPkiServer::LOCATION_WEBROOT);
56
        }
57
    }
58
59
    /**
60
     * Creates an updated OCSP statement. Nothing to be done here - eduPKI have
61
     * their own OCSP responder and the certs point to it. So we are not in the 
62
     * loop.
63
     * 
64
     * @param string $serial serial number of the certificate. Serials are 128 bit, so forcibly a string.
65
     * @return string a dummy string instead of a real statement
66
     */
67
    public function triggerNewOCSPStatement($serial): string
68
    {
69
        unset($serial); // not needed
70
        return "EXTERNAL";
71
    }
72
73
    /**
74
     * signs a CSR and returns the certificate (blocking wait)
75
     * 
76
     * @param array  $csr        the request metadata
77
     * @param integer $expiryDays how many days should the certificate be valid
78
     * @return array the certificate with some meta info
79
     * @throws Exception
80
     */
81
    public function signRequest($csr, $expiryDays): array
82
    {
83
        if ($csr["CSR_STRING"] === NULL) {
84
            throw new Exception("This CA needs the CSR in a string (PEM)!");
85
        }
86
        $revocationPin = common\Entity::randomString(10, "abcdefghijklmnopqrstuvwxyzABCDEFGHIJKLMNOPQRSTUVWXYZ0123456789");
87
        $soapReqnum = $this->sendRequestToCa($csr, $revocationPin, $expiryDays);
88
        sleep(55);
89
        // now, get the actual cert from the CA
90
        $returnValue = $this->pickupFinalCert($soapReqnum, TRUE);
91
        if ($returnValue === FALSE) {
92
            throw new Exception("We wanted to wait, but still got no cert!");
93
        }
94
        return $returnValue;
95
    }
96
97
    /**
98
     * sends the request to the CA and asks for the certificate. Does not block
99
     * until the certificate is issued, it needs to be picked up seperately
100
     * using its request number.
101
     * 
102
     * @param array  $csr           the CSR to sign. The member $csr['CSR'] must contain the CSR in *PEM* format
103
     * @param string $revocationPin a PIN to be able to revoke the cert later on
104
     * @param int    $expiryDays    how many days should the certificate be valid
105
     * @return int the request serial number
106
     * @throws Exception
107
     */
108
    public function sendRequestToCa($csr, $revocationPin, $expiryDays): int
0 ignored issues
show
Unused Code introduced by
The parameter $expiryDays is not used and could be removed. ( Ignorable by Annotation )

If this is a false-positive, you can also ignore this issue in your code via the ignore-unused  annotation

108
    public function sendRequestToCa($csr, $revocationPin, /** @scrutinizer ignore-unused */ $expiryDays): int

This check looks for parameters that have been defined for a function or method, but which are not used in the method body.

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