Passed
Pull Request — master (#45)
by
unknown
02:48
created

UrlTrait::parseQueryParameters()   A

Complexity

Conditions 6
Paths 12

Size

Total Lines 19
Code Lines 10

Duplication

Lines 0
Ratio 0 %

Importance

Changes 3
Bugs 0 Features 0
Metric Value
eloc 10
c 3
b 0
f 0
dl 0
loc 19
rs 9.2222
cc 6
nc 12
nop 2
1
<?php
2
3
declare(strict_types=1);
4
5
namespace SimpleSAML\Module\casserver\Controller\Traits;
6
7
use SimpleSAML\CAS\Constants as C;
8
use SimpleSAML\Configuration;
9
use SimpleSAML\Logger;
10
use SimpleSAML\Module\casserver\Cas\ServiceValidator;
11
use SimpleSAML\Module\casserver\Cas\TicketValidator;
12
use SimpleSAML\Module\casserver\Http\XmlResponse;
13
use Symfony\Component\HttpFoundation\Request;
14
use Symfony\Component\HttpFoundation\Response;
15
16
trait UrlTrait
17
{
18
    /**
19
     * @deprecated
20
     * @see ServiceValidator
21
     * @param string $service
22
     * @param array $legal_service_urls
23
     * @return bool
24
     */
25
    public function checkServiceURL(string $service, array $legal_service_urls): bool
26
    {
27
        //delegate to ServiceValidator until all references to this can be cleaned up
28
        $config = Configuration::loadFromArray(['legal_service_urls' => $legal_service_urls]);
29
        $serviceValidator = new ServiceValidator($config);
30
        return $serviceValidator->checkServiceURL($service) !== null;
31
    }
32
33
    /**
34
     * @param string $parameter
35
     * @return string
36
     */
37
    public function sanitize(string $parameter): string
38
    {
39
        return TicketValidator::sanitize($parameter);
40
    }
41
42
    /**
43
     * Parse the query Parameters from $_GET global and return them in an array.
44
     *
45
     * @param   Request     $request
46
     * @param   array|null  $sessionTicket
47
     *
48
     * @return array
49
     */
50
    public function parseQueryParameters(Request $request, ?array $sessionTicket): array
51
    {
52
        $forceAuthn = $this->getRequestParam($request, 'renew');
53
        $sessionRenewId = !empty($sessionTicket['renewId']) ? $sessionTicket['renewId'] : null;
54
55
        $queryParameters = $request->query->all();
56
        $requestParameters = $request->request->all();
57
58
        $query = array_merge($requestParameters, $queryParameters);
59
60
        if ($sessionRenewId && $forceAuthn) {
61
            $query['renewId'] = $sessionRenewId;
62
        }
63
64
        if (isset($query['language'])) {
65
            $query['language'] = is_string($query['language']) ? $query['language'] : null;
66
        }
67
68
        return $query;
69
    }
70
71
    /**
72
     * @param   Request  $request
73
     * @param   string   $paramName
74
     *
75
     * @return mixed
76
     */
77
    public function getRequestParam(Request $request, string $paramName): mixed
78
    {
79
        return $request->query->get($paramName) ?? $request->request->get($paramName) ?? null;
80
    }
81
82
    /**
83
     * @param   Request      $request
84
     * @param   string       $method
85
     * @param   bool         $renew
86
     * @param   string|null  $target
87
     * @param   string|null  $ticket
88
     * @param   string|null  $service
89
     * @param   string|null  $pgtUrl
90
     *
91
     * @return XmlResponse
92
     */
93
    public function validate(
94
        Request $request,
95
        string $method,
96
        bool $renew = false,
97
        ?string $target = null,
98
        ?string $ticket = null,
99
        ?string $service = null,
100
        ?string $pgtUrl = null,
101
    ): XmlResponse {
102
        $forceAuthn = $renew;
103
        $serviceUrl = $service ?? $target ?? null;
104
105
        // Check if any of the required query parameters are missing
106
        if ($serviceUrl === null || $ticket === null) {
107
            $messagePostfix = $serviceUrl === null ? 'service' : 'ticket';
108
            $message        = "casserver: Missing {$messagePostfix} parameter: [{$messagePostfix}]";
109
            Logger::debug($message);
110
111
            return new XmlResponse(
112
                (string)$this->cas20Protocol->getValidateFailureResponse(C::ERR_INVALID_SERVICE, $message),
113
                Response::HTTP_BAD_REQUEST,
114
            );
115
        }
116
117
        try {
118
            // Get the service ticket
119
            // `getTicket` uses the unserializable method and Objects may throw Throwables in their
120
            // un-serialization handlers.
121
            $serviceTicket = $this->ticketStore->getTicket($ticket);
122
        } catch (\Exception $e) {
123
            $messagePostfix = '';
124
            if (!empty($e->getMessage())) {
125
                $messagePostfix = ': ' . var_export($e->getMessage(), true);
126
            }
127
            $message = 'casserver:serviceValidate: internal server error' . $messagePostfix;
128
            Logger::error($message);
129
130
            return new XmlResponse(
131
                (string)$this->cas20Protocol->getValidateFailureResponse(C::ERR_INVALID_SERVICE, $message),
132
                Response::HTTP_INTERNAL_SERVER_ERROR,
133
            );
134
        }
135
136
        $failed  = false;
137
        $message = '';
138
        // Below, we do not have a ticket or the ticket does not meet the very basic criteria that allow
139
        // any further handling
140
        if (empty($serviceTicket)) {
141
            // No ticket
142
            $message = 'Ticket ' . var_export($ticket, true) . ' not recognized';
143
            $failed  = true;
144
        } elseif ($method === 'proxyValidate' && !$this->ticketFactory->isProxyTicket($serviceTicket)) {
145
            // proxyValidate but not a proxy ticket
146
            $message = 'Ticket ' . var_export($ticket, true) . ' is not a proxy ticket.';
147
            $failed  = true;
148
        } elseif ($method === 'serviceValidate' && !$this->ticketFactory->isServiceTicket($serviceTicket)) {
149
            // serviceValidate but not a service ticket
150
            $message = 'Ticket ' . var_export($ticket, true) . ' is not a service ticket.';
151
            $failed  = true;
152
        }
153
154
        if ($failed) {
155
            $finalMessage = 'casserver:validate: ' . $message;
156
            Logger::error($finalMessage);
157
158
            return new XmlResponse(
159
                (string)$this->cas20Protocol->getValidateFailureResponse(C::ERR_INVALID_SERVICE, $message),
160
                Response::HTTP_BAD_REQUEST,
161
            );
162
        }
163
164
        // Delete the ticket
165
        $this->ticketStore->deleteTicket($ticket);
166
167
        // Check if the ticket
168
        // - has expired
169
        // - does not pass sanitization
170
        // - forceAutnn criteria are not met
171
        if ($this->ticketFactory->isExpired($serviceTicket)) {
172
            // the ticket has expired
173
            $message = 'Ticket ' . var_export($ticket, true) . ' has expired';
174
            $failed  = true;
175
        } elseif ($this->sanitize($serviceTicket['service']) !== $this->sanitize($serviceUrl)) {
176
            // The service url we passed to the query parameters does not match the one in the ticket.
177
            $message = 'Mismatching service parameters: expected ' .
178
                var_export($serviceTicket['service'], true) .
179
                ' but was: ' . var_export($serviceUrl, true);
180
            $failed  = true;
181
        } elseif ($forceAuthn && !$serviceTicket['forceAuthn']) {
182
            // If `forceAuthn` is required but not set in the ticket
183
            $message = 'Ticket was issued from single sign on session';
184
            $failed  = true;
185
        }
186
187
        if ($failed) {
188
            $finalMessage = 'casserver:validate: ' . $message;
189
            Logger::error($finalMessage);
190
191
            return new XmlResponse(
192
                (string)$this->cas20Protocol->getValidateFailureResponse(C::ERR_INVALID_SERVICE, $message),
193
                Response::HTTP_BAD_REQUEST,
194
            );
195
        }
196
197
        $attributes = $serviceTicket['attributes'];
198
        $this->cas20Protocol->setAttributes($attributes);
199
200
        if (isset($pgtUrl)) {
201
            $sessionTicket = $this->ticketStore->getTicket($serviceTicket['sessionId']);
202
            if (
203
                $sessionTicket !== null
204
                && $this->ticketFactory->isSessionTicket($sessionTicket)
205
                && !$this->ticketFactory->isExpired($sessionTicket)
206
            ) {
207
                $proxyGrantingTicket = $this->ticketFactory->createProxyGrantingTicket(
208
                    [
209
                        'userName' => $serviceTicket['userName'],
210
                        'attributes' => $attributes,
211
                        'forceAuthn' => false,
212
                        'proxies' => array_merge(
213
                            [$serviceUrl],
214
                            $serviceTicket['proxies'],
215
                        ),
216
                        'sessionId' => $serviceTicket['sessionId'],
217
                    ],
218
                );
219
                try {
220
                    // Here we assume that the fetch will throw on any error.
221
                    // The generation of the proxy-granting-ticket or the corresponding proxy granting ticket IOU may
222
                    // fail due to the proxy callback url failing to meet the minimum security requirements such as
223
                    // failure to establish trust between peers or unresponsiveness of the endpoint, etc.
224
                    // In case of failure, no proxy-granting ticket will be issued and the CAS service response
225
                    // as described in Section 2.5.2 MUST NOT contain a <proxyGrantingTicket> block.
226
                    // At this point, the issuance of a proxy-granting ticket is halted and service ticket
227
                    // validation will fail.
228
                    $data = $this->httpUtils->fetch(
229
                        $pgtUrl . '?pgtIou=' . $proxyGrantingTicket['iou'] . '&pgtId=' . $proxyGrantingTicket['id'],
230
                    );
231
                    Logger::debug(__METHOD__ . '::data: ' . var_export($data, true));
232
                    $this->cas20Protocol->setProxyGrantingTicketIOU($proxyGrantingTicket['iou']);
233
                    $this->ticketStore->addTicket($proxyGrantingTicket);
234
                } catch (\Exception $e) {
235
                    return new XmlResponse(
236
                        (string)$this->cas20Protocol->getValidateFailureResponse(
237
                            C::ERR_INVALID_SERVICE,
238
                            'Proxy callback url is failing.',
239
                        ),
240
                        Response::HTTP_BAD_REQUEST,
241
                    );
242
                }
243
            }
244
        }
245
246
        return new XmlResponse(
247
            (string)$this->cas20Protocol->getValidateSuccessResponse($serviceTicket['userName']),
248
            Response::HTTP_OK,
249
        );
250
    }
251
}
252