-
Notifications
You must be signed in to change notification settings - Fork 2
/
Copy pathmatrix-token.patch
375 lines (374 loc) · 12.3 KB
/
matrix-token.patch
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
287
288
289
290
291
292
293
294
295
296
297
298
299
300
301
302
303
304
305
306
307
308
309
310
311
312
313
314
315
316
317
318
319
320
321
322
323
324
325
326
327
328
329
330
331
332
333
334
335
336
337
338
339
340
341
342
343
344
345
346
347
348
349
350
351
352
353
354
355
356
357
358
359
360
361
362
363
364
365
366
367
368
369
370
371
372
373
374
375
--- /dev/null
+++ b/usr/share/perl5/Lemonldap/NG/Common/Matrix.pm
@@ -0,0 +1,279 @@
+package Lemonldap::NG::Common::Matrix;
+
+use strict;
+use JSON;
+use Lemonldap::NG::Common::FormEncode;
+use Lemonldap::NG::Common::UserAgent;
+use Mouse::Role;
+use Net::DNS;
+use Regexp::Common 'net';
+use Regexp::Common::URI::RFC2396 '$hostname';
+
+# Check IP:port or IP. Captures IP and port
+my $isIpLiteral = qr/^($RE{net}{IPv6}|$RE{net}{IPv4})(?:(?<!:):(\d+))?$/;
+
+# Check hostname:port or hostname. Cpatures hostname and port
+my $isHostname = qr/^($hostname)(?:(?<!:):(\d+))?$/;
+
+has ua => (
+ is => 'rw',
+ lazy => 1,
+ builder => sub {
+
+ # TODO : LWP options to use a proxy for example
+ my $ua = Lemonldap::NG::Common::UserAgent->new( $_[0]->{conf} );
+ $ua->env_proxy();
+ return $ua;
+ }
+);
+
+has dnsResolver => (
+ is => 'rw',
+ lazy => 1,
+ builder => sub {
+ return Net::DNS::Resolver->new;
+ }
+);
+
+# MATRIX SERVER RESOLUTION
+#
+# main method: serverResolve
+
+sub serverResolve {
+ my ( $self, $name ) = @_;
+
+ # From Matrix spec 1.9
+ #
+ # If the hostname is an IP literal, then that IP address should be used,
+ # together with the given port number, or 8448 if no port is given.
+ return "https://$1:" . ( $2 || '8448' ) . '/'
+ if $name =~ $isIpLiteral;
+
+ unless ( $name =~ $isHostname ) {
+ $self->logger->error("Bad hostname $name");
+ return;
+ }
+
+ # If the hostname is not an IP literal, and the server name includes an
+ # explicit port, resolve the hostname to an IP address using CNAME, AAAA
+ # or A records
+ return "https://$1:$2/" if $2;
+
+ # If the hostname is not an IP literal, a regular HTTPS request is made
+ # to https://<hostname>/.well-known/matrix/server
+ my $resp = $self->ua->get("https://$name/.well-known/matrix/server");
+ if ( $resp->is_success ) {
+ my $content = eval { JSON::from_json( $resp->decoded_content ) };
+ unless ($@) {
+ if ( ref($content)
+ and ref($content) eq 'HASH'
+ and my $delegated = $content->{'m.server'} )
+ {
+ # If <delegated_hostname> is an IP literal, then that IP
+ # address should be used together with the <delegated_port>
+ # or 8448 if no port is provided
+ return "https://$1:" . ( $2 || '8448' ) . '/'
+ if $delegated =~ $isIpLiteral;
+
+ unless ( $delegated =~ $isHostname ) {
+ $self->logger->error("Bad hostname $name");
+ return;
+ }
+
+ # If <delegated_hostname> is not an IP literal, and
+ # <delegated_port> is present, an IP address is discovered by
+ # looking up CNAME, AAAA or A records for <delegated_hostname>
+ return "https://$1:$2/" if $2;
+
+ # ALL NEXT CASES ARE EXACTLY THE SAME DNS SEARCH THAN IF NO
+ # .well-known IS VALID BUT USING ${delegated} INSTEAD OF
+ # ${name}
+
+ # If <delegated_hostname> is not an IP literal and no
+ # <delegated_port> is present, an SRV record is looked up for
+ # _matrix-fed._tcp.<delegated_hostname>. This may result in
+ # another hostname (to be resolved using AAAA or A records) and
+ # port.
+ #
+ # [Deprecated] If <delegated_hostname> is not an IP literal, no
+ # <delegated_port> is present, and a
+ # _matrix-fed._tcp.<delegated_hostname> SRV record was not
+ # found, an SRV record is looked up for
+ # _matrix._tcp.<delegated_hostname>. This may result in another
+ # hostname # (to be resolved using AAAA or A records) and port.
+ #
+ # If no SRV record is found, an IP address is resolved using
+ # CNAME, # AAAA or A records. Requests are then made to the
+ # resolve IP address # and a port of 8448, using a Host header
+ # of <delegated_hostname>
+ return $self->_dnsResolve($delegated);
+ }
+ }
+ }
+ return $self->_dnsResolve($name);
+}
+
+sub _dnsResolve {
+ my ( $self, $name ) = @_;
+ my @res;
+
+ # If the /.well-known request resulted in an error response, a server is
+ # found by resolving an SRV record for _matrix-fed._tcp.<hostname>. This
+ # may result in a hostname (to be resolved using AAAA or A records) and
+ # port
+ @res = $self->dnsSrvResolve("_matrix-fed._tcp.$name");
+
+ # [Deprecated] If the /.well-known request resulted in an error response,
+ # and a _matrix-fed._tcp.<hostname> SRV record was not found, a server is
+ # found by resolving an SRV record for _matrix._tcp.<hostname>
+ @res = $self->dnsSrvResolve("_matrix._tcp.$name") unless @res;
+
+ return ( wantarray ? @res : shift(@res) ) if @res;
+
+ # If the /.well-known request returned an error response, and the
+ # SRV record was not found, an IP address is resolved using CNAME,
+ # AAAA and A records. Requests are made to the resolved IP address
+ # using port 8448 and a Host header containing the <hostname>
+ if ( rr($name) ) {
+ return "https://$name:8448/";
+ }
+ else {
+ $self->logger->error("Unable to resolve Matrix name $name");
+ return;
+ }
+}
+
+sub dnsSrvResolve {
+ my ( $self, $name ) = @_;
+ my $reply = $self->dnsResolver->query( $name, 'SRV' );
+ return unless $reply;
+ return map { 'https://' . $_->target . ':' . $_->port . '/' }
+ sort { $b->priority <=> $a->priority } $reply->answer;
+}
+
+# MATRIX TOKEN VALIDATION
+#
+# main method: validateMatrixToken
+
+sub validateMatrixToken {
+ my ( $self, $matrixBaseUrl, $accessToken ) = @_;
+ $matrixBaseUrl =~ s#/+$##;
+ my $resp =
+ $self->ua->get( "$matrixBaseUrl/_matrix/federation/v1/openid/userinfo?"
+ . build_urlencoded( access_token => $accessToken ) );
+ if ( $resp->is_success ) {
+ my $content = eval { JSON::from_json( $resp->decoded_content ) };
+ if ($@) {
+ $self->logger->error("Bad response from $matrixBaseUrl: $@");
+ return;
+ }
+ if ( ref $content eq 'HASH' and my $sub = $content->{sub} ) {
+ unless ( $sub =~ /^\@(.*):(.*)$/ ) {
+ $self->logger->error(
+ "Bad 'sub' received from $matrixBaseUrl: $sub");
+ return;
+ }
+ return wantarray ? ( $sub, $1, $2 ) : $sub;
+ }
+ else {
+ $self->logger->error(
+ "Bad response from $matrixBaseUrl: " . $resp->decoded_content );
+ return;
+ }
+ }
+ else {
+ $self->userLogger->error(
+ "Token $accessToken refused by $matrixBaseUrl: "
+ . $resp->status_line );
+ return;
+ }
+}
+
+1;
+__END__
+
+=head1 NAME
+
+=encoding utf8
+
+Lemonldap::NG::Common::Matrix - Library to interact with Matrix servers
+
+=head1 SYNOPSIS
+
+ use Mouse;
+ with 'Lemonldap::NG::Common::Matrix';
+ #
+ # Server resolution
+ #
+ my $baseUrl = $self->serverResolve('matrix.org');
+ # Gives: https://matrix-federation.matrix.org.cdn.cloudflare.net:8443/
+ #
+ # Token validation
+ #
+ my $subject = $self->validateMatrixToken( $baseUrl, 'federationToken' );
+ # or
+ my ( $subject, $username, $domain) =
+ $self->validateMatrixToken( $baseUrl, 'federationToken' );
+ # Gives the Matrix address of this user
+
+
+=head1 DESCRIPTION
+
+Lemonldap::NG::Common::Matrix is a L<Mouse::Role> that provides additional
+methods to interact with Matrix servers.
+
+=head1 METHODS
+
+=head2 serverResolve
+
+Return the base URL corresponding to the given Matrix "Servername", following
+L<Matrix specifications|https://spec.matrix.org/v1.9/server-server-api/#server-discovery>
+
+=head2 validateMatrixToken
+
+Verify the given "federation token" and return the matrix address.
+
+The "federation token" isn't the Matrix C<access_token> but a token that user
+can get by calling C</_matrix/client/v3/user/$USER_ID/openid/request_token>
+on its Matrix server.
+
+=head1 SEE ALSO
+
+L<Lemonldap::NG::Manager>, L<Lemonldap::NG::Portal>, L<Lemonldap::NG::Handler>
+
+=head1 AUTHORS
+
+=over
+
+=item LemonLDAP::NG team L<http://lemonldap-ng.org/team>
+
+=back
+
+=head1 BUG REPORT
+
+Use OW2 system to report bug or ask for features:
+L<https://gitlab.ow2.org/lemonldap-ng/lemonldap-ng/issues>
+
+=head1 DOWNLOAD
+
+Lemonldap::NG is available at
+L<https://lemonldap-ng.org/download>
+
+=head1 COPYRIGHT AND LICENSE
+
+See COPYING file for details.
+
+This library is free software; you can redistribute it and/or modify
+it under the terms of the GNU General Public License as published by
+the Free Software Foundation; either version 2, or (at your option)
+any later version.
+
+This program is distributed in the hope that it will be useful,
+but WITHOUT ANY WARRANTY; without even the implied warranty of
+MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
+GNU General Public License for more details.
+
+You should have received a copy of the GNU General Public License
+along with this program. If not, see L<http://www.gnu.org/licenses/>.
+
+=cut
diff --git a/usr/share/perl5/Lemonldap/NG/Portal/Main/Plugins.pm b/usr/share/perl5/Lemonldap/NG/Portal/Main/Plugins.pm
index bc2b8e867..9e51457c1 100644
--- a/usr/share/perl5/Lemonldap/NG/Portal/Main/Plugins.pm
+++ b/usr/share/perl5/Lemonldap/NG/Portal/Main/Plugins.pm
@@ -49,6 +49,8 @@ our @pList = (
'::Plugins::AuthOidcPkce',
'or::oidcRPMetaDataOptions/*/oidcRPMetaDataOptionsTokenXAuthorizedRP' =>
'::Plugins::OIDCInternalTokenExchange',
+ 'or::oidcRPMetaDataOptions/*/oidcRPMetaDataOptionsTokenXAuthorizedMatrix'
+ => '::Plugins::MatrixTokenExchange',
);
##@method list enabledPlugins
diff --git a/usr/share/perl5/Lemonldap/NG/Portal/Plugins/MatrixTokenExchange.pm b/usr/share/perl5/Lemonldap/NG/Portal/Plugins/MatrixTokenExchange.pm
new file mode 100644
index 000000000..cf2072cfe
--- /dev/null
+++ b/usr/share/perl5/Lemonldap/NG/Portal/Plugins/MatrixTokenExchange.pm
@@ -0,0 +1,74 @@
+package Lemonldap::NG::Portal::Plugins::MatrixTokenExchange;
+
+use strict;
+use Mouse;
+
+extends 'Lemonldap::NG::Portal::Lib::OIDCTokenExchange';
+
+with 'Lemonldap::NG::Common::Matrix';
+
+sub validateAudience {
+ my ( $self, $req, $rp, $target, $requestedTokenType ) = @_;
+
+ if ( $requestedTokenType and $requestedTokenType ne 'access_token' ) {
+ $self->logger->debug("Requested token isn't declared as access_token");
+ return 0;
+ }
+
+ unless ( $target->{audience} ) {
+ $target->{rp} = $rp;
+ return 1;
+ }
+
+ unless ( $target->{rp} ) {
+ $self->logger->debug(
+ "Token exchange request for an unexistent RP $target->{audience}");
+ return 0;
+ }
+
+ return 1 if $target->{rp} eq $rp;
+
+ my $list = $self->oidc->rpOptions->{ $target->{rp} }
+ ->{oidcRPMetaDataOptionsTokenXAuthorizedMatrix};
+ my $subject_issuer = $req->param('subject_issuer');
+ unless ($subject_issuer) {
+ $self->logger->debug('Request without subject_issuer');
+ return 0;
+ }
+ unless ( $list and grep { $_ eq $subject_issuer } split /[,;\s]+/, $list ) {
+ $self->logger->debug(
+"Token exchange for an unauthorized Matrix server ($subject_issuer => $target->{rp})"
+ );
+ return 0;
+ }
+ return 1;
+}
+
+sub getUid {
+ my ( $self, $req, $rp, $subjectToken, $subjectTokenType ) = @_;
+
+ if ( $subjectTokenType and $subjectTokenType ne 'access_token' ) {
+ $self->logger->debug(
+ "Matrix given token isn't declared as access_token");
+ return 0;
+ }
+
+ my $subject_issuer = $req->param('subject_issuer');
+ $subject_issuer = $self->serverResolve($subject_issuer);
+
+ # 2. Validate Matrix token against given Matrix server
+ $self->logger->debug(
+ "Token exchange asked for Matrix token $subjectToken on $subject_issuer"
+ );
+
+ my ( $matrixSub, $uid, $domain ) =
+ $self->validateMatrixToken( $subject_issuer, $subjectToken );
+
+ unless ($matrixSub) {
+ $self->logger->debug("Matrix token rejected by $subject_issuer");
+ return 0;
+ }
+ return $uid;
+}
+
+1;