-
Notifications
You must be signed in to change notification settings - Fork 24
/
http_openid.pl
1559 lines (1361 loc) · 53.5 KB
/
http_openid.pl
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
376
377
378
379
380
381
382
383
384
385
386
387
388
389
390
391
392
393
394
395
396
397
398
399
400
401
402
403
404
405
406
407
408
409
410
411
412
413
414
415
416
417
418
419
420
421
422
423
424
425
426
427
428
429
430
431
432
433
434
435
436
437
438
439
440
441
442
443
444
445
446
447
448
449
450
451
452
453
454
455
456
457
458
459
460
461
462
463
464
465
466
467
468
469
470
471
472
473
474
475
476
477
478
479
480
481
482
483
484
485
486
487
488
489
490
491
492
493
494
495
496
497
498
499
500
501
502
503
504
505
506
507
508
509
510
511
512
513
514
515
516
517
518
519
520
521
522
523
524
525
526
527
528
529
530
531
532
533
534
535
536
537
538
539
540
541
542
543
544
545
546
547
548
549
550
551
552
553
554
555
556
557
558
559
560
561
562
563
564
565
566
567
568
569
570
571
572
573
574
575
576
577
578
579
580
581
582
583
584
585
586
587
588
589
590
591
592
593
594
595
596
597
598
599
600
601
602
603
604
605
606
607
608
609
610
611
612
613
614
615
616
617
618
619
620
621
622
623
624
625
626
627
628
629
630
631
632
633
634
635
636
637
638
639
640
641
642
643
644
645
646
647
648
649
650
651
652
653
654
655
656
657
658
659
660
661
662
663
664
665
666
667
668
669
670
671
672
673
674
675
676
677
678
679
680
681
682
683
684
685
686
687
688
689
690
691
692
693
694
695
696
697
698
699
700
701
702
703
704
705
706
707
708
709
710
711
712
713
714
715
716
717
718
719
720
721
722
723
724
725
726
727
728
729
730
731
732
733
734
735
736
737
738
739
740
741
742
743
744
745
746
747
748
749
750
751
752
753
754
755
756
757
758
759
760
761
762
763
764
765
766
767
768
769
770
771
772
773
774
775
776
777
778
779
780
781
782
783
784
785
786
787
788
789
790
791
792
793
794
795
796
797
798
799
800
801
802
803
804
805
806
807
808
809
810
811
812
813
814
815
816
817
818
819
820
821
822
823
824
825
826
827
828
829
830
831
832
833
834
835
836
837
838
839
840
841
842
843
844
845
846
847
848
849
850
851
852
853
854
855
856
857
858
859
860
861
862
863
864
865
866
867
868
869
870
871
872
873
874
875
876
877
878
879
880
881
882
883
884
885
886
887
888
889
890
891
892
893
894
895
896
897
898
899
900
901
902
903
904
905
906
907
908
909
910
911
912
913
914
915
916
917
918
919
920
921
922
923
924
925
926
927
928
929
930
931
932
933
934
935
936
937
938
939
940
941
942
943
944
945
946
947
948
949
950
951
952
953
954
955
956
957
958
959
960
961
962
963
964
965
966
967
968
969
970
971
972
973
974
975
976
977
978
979
980
981
982
983
984
985
986
987
988
989
990
991
992
993
994
995
996
997
998
999
1000
/* Part of SWI-Prolog
Author: Jan Wielemaker
E-mail: [email protected]
WWW: http://www.swi-prolog.org
Copyright (c) 2010-2015, University of Amsterdam,
VU University Amsterdam
All rights reserved.
Redistribution and use in source and binary forms, with or without
modification, are permitted provided that the following conditions
are met:
1. Redistributions of source code must retain the above copyright
notice, this list of conditions and the following disclaimer.
2. Redistributions in binary form must reproduce the above copyright
notice, this list of conditions and the following disclaimer in
the documentation and/or other materials provided with the
distribution.
THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS
"AS IS" AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT
LIMITED TO, THE IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS
FOR A PARTICULAR PURPOSE ARE DISCLAIMED. IN NO EVENT SHALL THE
COPYRIGHT OWNER OR CONTRIBUTORS BE LIABLE FOR ANY DIRECT, INDIRECT,
INCIDENTAL, SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES (INCLUDING,
BUT NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES;
LOSS OF USE, DATA, OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER
CAUSED AND ON ANY THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT
LIABILITY, OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN
ANY WAY OUT OF THE USE OF THIS SOFTWARE, EVEN IF ADVISED OF THE
POSSIBILITY OF SUCH DAMAGE.
*/
:- module(http_openid,
[ openid_login/1, % +OpenID
openid_logout/1, % +OpenID
openid_logged_in/1, % -OpenID
% transparent login
openid_user/3, % +Request, -User, +Options
% low-level primitives
openid_verify/2, % +Options, +Request
openid_authenticate/4, % +Request, -Server, -Identity, -ReturnTo
openid_associate/3, % +OpenIDServer, -Handle, -Association
openid_associate/4, % +OpenIDServer, -Handle, -Association,
% +Options
openid_server/2, % +Options, +Request
openid_server/3, % ?OpenIDLogin, ?OpenID, ?Server
openid_grant/1, % +Request
openid_login_form//2, % +ReturnTo, +Options, //
openid_current_url/2, % +Request, -URL
openid_current_host/3 % +Request, -Host, -Port
]).
:- use_module(library(http/http_open)).
:- use_module(library(http/html_write)).
:- use_module(library(http/http_parameters)).
:- use_module(library(http/http_dispatch)).
:- use_module(library(http/http_session)).
:- use_module(library(http/http_host)).
:- use_module(library(http/http_path)).
:- use_module(library(http/html_head)).
:- use_module(library(http/http_server_files), []).
:- use_module(library(http/yadis)).
:- use_module(library(http/ax)).
:- use_module(library(utf8)).
:- use_module(library(error)).
:- use_module(library(xpath)).
:- use_module(library(sgml)).
:- use_module(library(uri)).
:- use_module(library(occurs)).
:- use_module(library(base64)).
:- use_module(library(debug)).
:- use_module(library(record)).
:- use_module(library(option)).
:- use_module(library(sha)).
:- use_module(library(lists)).
:- use_module(library(settings)).
:- predicate_options(openid_login_form/4, 2,
[ action(atom),
buttons(list),
show_stay(boolean)
]).
:- predicate_options(openid_server/2, 1,
[ expires_in(any)
]).
:- predicate_options(openid_user/3, 3,
[ login_url(atom)
]).
:- predicate_options(openid_verify/2, 1,
[ return_to(atom),
trust_root(atom),
realm(atom),
ax(any)
]).
/** <module> OpenID consumer and server library
This library implements the OpenID protocol (http://openid.net/). OpenID
is a protocol to share identities on the network. The protocol itself
uses simple basic HTTP, adding reliability using digitally signed
messages.
Steps, as seen from the _consumer_ (or _|relying partner|_).
1. Show login form, asking for =openid_identifier=
2. Get HTML page from =openid_identifier= and lookup
=|<link rel="openid.server" href="server">|=
3. Associate to _server_
4. Redirect browser (302) to server using mode =checkid_setup=,
asking to validate the given OpenID.
5. OpenID server redirects back, providing digitally signed
conformation of the claimed identity.
6. Validate signature and redirect to the target location.
A *consumer* (an application that allows OpenID login) typically uses
this library through openid_user/3. In addition, it must implement the
hook http_openid:openid_hook(trusted(OpenId, Server)) to define accepted
OpenID servers. Typically, this hook is used to provide a white-list of
acceptable servers. Note that accepting any OpenID server is possible,
but anyone on the internet can setup a dummy OpenID server that simply
grants and signs every request. Here is an example:
==
:- multifile http_openid:openid_hook/1.
http_openid:openid_hook(trusted(_, OpenIdServer)) :-
( trusted_server(OpenIdServer)
-> true
; throw(http_reply(moved_temporary('/openid/trustedservers')))
).
trusted_server('http://www.myopenid.com/server').
==
By default, information who is logged on is maintained with the session
using http_session_assert/1 with the term openid(Identity). The hooks
login/logout/logged_in can be used to provide alternative administration
of logged-in users (e.g., based on client-IP, using cookies, etc.).
To create a *server*, you must do four things: bind the handlers
openid_server/2 and openid_grant/1 to HTTP locations, provide a
user-page for registered users and define the grant(Request, Options)
hook to verify your users. An example server is provided in in
<plbase>/doc/packages/examples/demo_openid.pl
*/
/*******************************
* CONFIGURATION *
*******************************/
http:location(openid, root(openid), [priority(-100)]).
%! openid_hook(+Action)
%
% Call hook on the OpenID management library. Defined hooks are:
%
% * login(+OpenID)
% Consider OpenID logged in.
%
% * logout(+OpenID)
% Logout OpenID
%
% * logged_in(?OpenID)
% True if OpenID is logged in
%
% * grant(+Request, +Options)
% Server: Reply positive on OpenID
%
% * trusted(+OpenID, +Server)
% True if Server is a trusted OpenID server
%
% * ax(Values)
% Called if the server provided AX attributes
%
% * x_parameter(+Server, -Name, -Value)
% Called to find additional HTTP parameters to send with the
% OpenID verify request.
:- multifile
openid_hook/1. % +Action
/*******************************
* DIRECT LOGIN/OUT *
*******************************/
%! openid_login(+OpenID) is det.
%
% Associate the current HTTP session with OpenID. If another
% OpenID is already associated, this association is first removed.
openid_login(OpenID) :-
openid_hook(login(OpenID)),
!,
handle_stay_signed_in(OpenID).
openid_login(OpenID) :-
openid_logout(_),
http_session_assert(openid(OpenID)),
handle_stay_signed_in(OpenID).
%! openid_logout(+OpenID) is det.
%
% Remove the association of the current session with any OpenID
openid_logout(OpenID) :-
openid_hook(logout(OpenID)),
!.
openid_logout(OpenID) :-
http_session_retractall(openid(OpenID)).
%! openid_logged_in(-OpenID) is semidet.
%
% True if session is associated with OpenID.
openid_logged_in(OpenID) :-
openid_hook(logged_in(OpenID)),
!.
openid_logged_in(OpenID) :-
http_in_session(_SessionId), % test in session
http_session_data(openid(OpenID)).
/*******************************
* TOPLEVEL *
*******************************/
%! openid_user(+Request:http_request, -OpenID:url, +Options) is det.
%
% True if OpenID is a validated OpenID associated with the current
% session. The scenario for which this predicate is designed is to
% allow an HTTP handler that requires a valid login to
% use the transparent code below.
%
% ==
% handler(Request) :-
% openid_user(Request, OpenID, []),
% ...
% ==
%
% If the user is not yet logged on a sequence of redirects will
% follow:
%
% 1. Show a page for login (default: page /openid/login),
% predicate reply_openid_login/1)
% 2. By default, the OpenID login page is a form that is
% submitted to the =verify=, which calls openid_verify/2.
% 3. openid_verify/2 does the following:
% - Find the OpenID claimed identity and server
% - Associate to the OpenID server
% - redirects to the OpenID server for validation
% 4. The OpenID server will redirect here with the authetication
% information. This is handled by openid_authenticate/4.
%
% Options:
%
% * login_url(Login)
% (Local) URL of page to enter OpenID information. Default
% is the handler for openid_login_page/1
%
% @see openid_authenticate/4 produces errors if login is invalid
% or cancelled.
:- http_handler(openid(login), openid_login_page, [priority(-10)]).
:- http_handler(openid(verify), openid_verify([]), []).
:- http_handler(openid(authenticate), openid_authenticate, []).
:- http_handler(openid(xrds), openid_xrds, []).
openid_user(_Request, OpenID, _Options) :-
openid_logged_in(OpenID),
!.
openid_user(Request, _OpenID, Options) :-
http_link_to_id(openid_login_page, [], DefLoginPage),
option(login_url(LoginPage), Options, DefLoginPage),
openid_current_url(Request, Here),
redirect_browser(LoginPage,
[ 'openid.return_to' = Here
]).
%! openid_xrds(Request)
%
% Reply to a request for "Discovering OpenID Relying Parties".
% This may happen as part of the provider verification procedure.
% The provider will do a Yadis discovery request on
% =openid.return= or =openid.realm=. This is picked up by
% openid_user/3, pointing the provider to openid(xrds). Now, we
% reply with the locations marked =openid= and the locations that
% have actually been doing OpenID validations.
openid_xrds(Request) :-
http_link_to_id(openid_authenticate, [], Autheticate),
public_url(Request, Autheticate, Public),
format('Content-type: text/xml\n\n'),
format('<?xml version="1.0" encoding="UTF-8"?>\n'),
format('<xrds:XRDS\n'),
format(' xmlns:xrds="xri://$xrds"\n'),
format(' xmlns="xri://$xrd*($v*2.0)">\n'),
format(' <XRD>\n'),
format(' <Service>\n'),
format(' <Type>http://specs.openid.net/auth/2.0/return_to</Type>\n'),
format(' <URI>~w</URI>\n', [Public]),
format(' </Service>\n'),
format(' </XRD>\n'),
format('</xrds:XRDS>\n').
%! openid_login_page(+Request) is det.
%
% Present a login-form for OpenID. There are two ways to redefine
% this default login page. One is to provide the option
% =login_url= to openid_user/3 and the other is to define a new
% handler for =|/openid/login|= using http_handler/3.
openid_login_page(Request) :-
http_open_session(_, []),
http_parameters(Request,
[ 'openid.return_to'(Target, [])
]),
reply_html_page([ title('OpenID login')
],
[ \openid_login_form(Target, [])
]).
%! openid_login_form(+ReturnTo, +Options)// is det.
%
% Create the OpenID form. This exported as a separate DCG,
% allowing applications to redefine /openid/login and reuse this
% part of the page. Options processed:
%
% - action(Action)
% URL of action to call. Default is the handler calling
% openid_verify/1.
% - buttons(+Buttons)
% Buttons is a list of =img= structures where the =href=
% points to an OpenID 2.0 endpoint. These buttons are
% displayed below the OpenID URL field. Clicking the
% button sets the URL field and submits the form. Requires
% Javascript support.
%
% If the =href= is _relative_, clicking it opens the given
% location after adding 'openid.return_to' and `stay'.
% - show_stay(+Boolean)
% If =true=, show a checkbox that allows the user to stay
% logged on.
openid_login_form(ReturnTo, Options) -->
{ http_link_to_id(openid_verify, [], VerifyLocation),
option(action(Action), Options, VerifyLocation),
http_session_retractall(openid(_)),
http_session_retractall(openid_login(_,_,_,_)),
http_session_retractall(ax(_))
},
html(div([ class('openid-login')
],
[ \openid_title,
form([ name(login),
id(login),
action(Action),
method('GET')
],
[ \hidden('openid.return_to', ReturnTo),
div([ input([ class('openid-input'),
name(openid_url),
id(openid_url),
size(30),
placeholder('Your OpenID URL')
]),
input([ type(submit),
value('Verify!')
])
]),
\buttons(Options),
\stay_logged_on(Options)
])
])).
stay_logged_on(Options) -->
{ option(show_stay(true), Options) },
!,
html(div(class('openid-stay'),
[ input([ type(checkbox), id(stay), name(stay), value(yes)]),
'Stay signed in'
])).
stay_logged_on(_) --> [].
buttons(Options) -->
{ option(buttons(Buttons), Options),
Buttons \== []
},
html(div(class('openid-buttons'),
[ 'Sign in with '
| \prelogin_buttons(Buttons)
])).
buttons(_) --> [].
prelogin_buttons([]) --> [].
prelogin_buttons([H|T]) --> prelogin_button(H), prelogin_buttons(T).
%! prelogin_button(+Image)// is det.
%
% Handle OpenID 2.0 and other pre-login buttons. If the image has
% a =href= attribute that is absolute, it is taken as an OpenID
% 2.0 endpoint. Otherwise it is taken as a link on the current
% server. This allows us to present non-OpenId logons in the same
% screen. The dedicated handler is passed the HTTP parameters
% =openid.return_to= and =stay=.
prelogin_button(img(Attrs)) -->
{ select_option(href(HREF), Attrs, RestAttrs),
uri_is_global(HREF), !
},
html(img([ onClick('javascript:{$("#openid_url").val("'+HREF+'");'+
'$("form#login").submit();}'
)
| RestAttrs
])).
prelogin_button(img(Attrs)) -->
{ select_option(href(HREF), Attrs, RestAttrs)
},
html(img([ onClick('window.location = "'+HREF+
'?openid.return_to="'+
'+encodeURIComponent($("#return_to").val())'+
'+"&stay="'+
'+$("#stay").val()')
| RestAttrs
])).
/*******************************
* HTTP REPLIES *
*******************************/
%! openid_verify(+Options, +Request)
%
% Handle the initial login form presented to the user by the
% relying party (consumer). This predicate discovers the OpenID
% server, associates itself with this server and redirects the
% user's browser to the OpenID server, providing the extra
% openid.X name-value pairs. Options is, against the conventions,
% placed in front of the Request to allow for smooth cooperation
% with http_dispatch.pl. Options processes:
%
% * return_to(+URL)
% Specifies where the OpenID provider should return to.
% Normally, that is the current location.
% * trust_root(+URL)
% Specifies the =openid.trust_root= attribute. Defaults to
% the root of the current server (i.e., =|http://host[.port]/|=).
% * realm(+URL)
% Specifies the =openid.realm= attribute. Default is the
% =trust_root=.
% * ax(+Spec)
% Request the exchange of additional attributes from the
% identity provider. See http_ax_attributes/2 for details.
%
% The OpenId server will redirect to the =openid.return_to= URL.
%
% @throws http_reply(moved_temporary(Redirect))
openid_verify(Options, Request) :-
http_parameters(Request,
[ openid_url(URL, [length>1]),
'openid.return_to'(ReturnTo0, [optional(true)]),
stay(Stay, [optional(true), default(no)])
]),
( option(return_to(ReturnTo1), Options) % Option
-> openid_current_url(Request, CurrentLocation),
global_url(ReturnTo1, CurrentLocation, ReturnTo)
; nonvar(ReturnTo0)
-> ReturnTo = ReturnTo0 % Form-data
; openid_current_url(Request, CurrentLocation),
ReturnTo = CurrentLocation % Current location
),
public_url(Request, /, CurrentRoot),
option(trust_root(TrustRoot), Options, CurrentRoot),
option(realm(Realm), Options, TrustRoot),
openid_resolve(URL, OpenIDLogin, OpenID, Server, ServerOptions),
trusted(OpenID, Server),
openid_associate(Server, Handle, _Assoc),
assert_openid(OpenIDLogin, OpenID, Server, ReturnTo),
stay(Stay),
option(ns(NS), Options, 'http://specs.openid.net/auth/2.0'),
( realm_attribute(NS, RealmAttribute)
-> true
; domain_error('openid.ns', NS)
),
findall(P=V, openid_hook(x_parameter(Server, P, V)), XAttrs, AXAttrs),
debug(openid(verify), 'XAttrs: ~p', [XAttrs]),
ax_options(ServerOptions, Options, AXAttrs),
http_link_to_id(openid_authenticate, [], AuthenticateLoc),
public_url(Request, AuthenticateLoc, Authenticate),
redirect_browser(Server, [ 'openid.ns' = NS,
'openid.mode' = checkid_setup,
'openid.identity' = OpenID,
'openid.claimed_id' = OpenID,
'openid.assoc_handle' = Handle,
'openid.return_to' = Authenticate,
RealmAttribute = Realm
| XAttrs
]).
realm_attribute('http://specs.openid.net/auth/2.0', 'openid.realm').
realm_attribute('http://openid.net/signon/1.1', 'openid.trust_root').
%! stay(+Response)
%
% Called if the user ask to stay signed in. This is called
% _before_ control is handed to the OpenID server. It leaves the
% data openid_stay_signed_in(true) in the current session.
stay(yes) :-
!,
http_session_assert(openid_stay_signed_in(true)).
stay(_).
%! handle_stay_signed_in(+OpenID)
%
% Handle stay_signed_in option after the user has logged on
handle_stay_signed_in(OpenID) :-
http_session_retract(openid_stay_signed_in(true)),
!,
http_set_session(timeout(0)),
ignore(openid_hook(stay_signed_in(OpenID))).
handle_stay_signed_in(_).
%! assert_openid(+OpenIDLogin, +OpenID, +Server, +Target) is det.
%
% Associate the OpenID as typed by the user, the OpenID as
% validated by the Server with the current HTTP session.
%
% @param OpenIDLogin Canonized OpenID typed by user
% @param OpenID OpenID verified by Server.
assert_openid(OpenIDLogin, OpenID, Server, Target) :-
openid_identifier_select_url(OpenIDLogin),
openid_identifier_select_url(OpenID),
!,
assert_openid_in_session(openid_login(Identity, Identity, Server, Target)).
assert_openid(OpenIDLogin, OpenID, Server, Target) :-
assert_openid_in_session(openid_login(OpenIDLogin, OpenID, Server, Target)).
assert_openid_in_session(Term) :-
( http_in_session(Session)
-> debug(openid(verify), 'Assert ~p in ~p', [Term, Session])
; debug(openid(verify), 'No session!', [])
),
http_session_assert(Term).
%! openid_server(?OpenIDLogin, ?OpenID, ?Server) is nondet.
%
% True if OpenIDLogin is the typed id for OpenID verified by
% Server.
%
% @param OpenIDLogin ID as typed by user (canonized)
% @param OpenID ID as verified by server
% @param Server URL of the OpenID server
openid_server(OpenIDLogin, OpenID, Server) :-
openid_server(OpenIDLogin, OpenID, Server, _Target).
openid_server(OpenIDLogin, OpenID, Server, Target) :-
http_in_session(Session),
( http_session_data(openid_login(OpenIDLogin, OpenID, Server, Target))
-> true
; http_session_data(openid_login(OpenIDLogin1, OpenID1, Server1, Target1)),
debug(openid(verify), '~p \\== ~p',
[ openid_login(OpenIDLogin, OpenID, Server, Target),
openid_login(OpenIDLogin1, OpenID1, Server1, Target1)
]),
fail
; debug(openid(verify), 'No openid_login/4 term in session ~p', [Session]),
fail
).
%! public_url(+Request, +Path, -URL) is det.
%
% True when URL is a publically useable URL that leads to Path on
% the current server.
public_url(Request, Path, URL) :-
openid_current_host(Request, Host, Port),
setting(http:public_scheme, Scheme),
set_port(Scheme, Port, AuthC),
uri_authority_data(host, AuthC, Host),
uri_authority_components(Auth, AuthC),
uri_data(scheme, Components, Scheme),
uri_data(authority, Components, Auth),
uri_data(path, Components, Path),
uri_components(URL, Components).
set_port(Scheme, Port, _) :-
scheme_port(Scheme, Port),
!.
set_port(_, Port, AuthC) :-
uri_authority_data(port, AuthC, Port).
scheme_port(http, 80).
scheme_port(https, 443).
%! openid_current_url(+Request, -URL) is det.
%
% Find the public URL for Request that we can make available to our
% identity provider. This must be an absolute URL where we can be
% contacted. Before trying a configured version through
% http_public_url/2, we try to see wether the login message contains a
% referer parameter or wether the browser provided one.
openid_current_url(Request, URL) :-
option(request_uri(URI), Request),
uri_components(URI, Components),
uri_data(path, Components, Path),
( uri_data(search, Components, QueryString),
nonvar(QueryString),
uri_query_components(QueryString, Query),
memberchk(referer=Base, Query)
-> true
; option(referer(Base), Request)
), !,
uri_normalized(Path, Base, URL).
openid_current_url(Request, URL) :-
http_public_url(Request, URL).
%! openid_current_host(Request, Host, Port)
%
% Find current location of the server.
%
% @deprecated New code should use http_current_host/4 with the
% option global(true).
openid_current_host(Request, Host, Port) :-
http_current_host(Request, Host, Port,
[ global(true)
]).
%! redirect_browser(+URL, +FormExtra)
%
% Generate a 302 temporary redirect to URL, adding the extra form
% information from FormExtra. The specs says we must retain the
% search specification already attached to the URL.
redirect_browser(URL, FormExtra) :-
uri_components(URL, C0),
uri_data(search, C0, Search0),
( var(Search0)
-> uri_query_components(Search, FormExtra)
; uri_query_components(Search0, Form0),
append(FormExtra, Form0, Form),
uri_query_components(Search, Form)
),
uri_data(search, C0, Search, C),
uri_components(Redirect, C),
throw(http_reply(moved_temporary(Redirect))).
/*******************************
* RESOLVE *
*******************************/
%! openid_resolve(+URL, -OpenIDOrig, -OpenID, -Server, -ServerOptions)
%
% True if OpenID is the claimed OpenID that belongs to URL and
% Server is the URL of the OpenID server that can be asked to
% verify this claim.
%
% @param URL The OpenID typed by the user
% @param OpenIDOrig Canonized OpenID typed by user
% @param OpenID Possibly delegated OpenID
% @param Server OpenID server that must validate OpenID
% @param ServerOptions provides additional XRDS information about
% the server. Currently supports xrds_types(Types).
% @tbd Implement complete URL canonization as defined by the
% OpenID 2.0 proposal.
openid_resolve(URL, OpenID, OpenID, Server, [xrds_types(Types)]) :-
xrds_dom(URL, DOM),
xpath(DOM, //(_:'Service'), Service),
findall(Type, xpath(Service, _:'Type'(text), Type), Types),
memberchk('http://specs.openid.net/auth/2.0/server', Types),
xpath(Service, _:'URI'(text), Server),
!,
debug(openid(yadis), 'Yadis: server: ~q, types: ~q', [Server, Types]),
( xpath(Service, _:'LocalID'(text), OpenID)
-> true
; openid_identifier_select_url(OpenID)
).
openid_resolve(URL, OpenID0, OpenID, Server, []) :-
debug(openid(resolve), 'Opening ~w ...', [URL]),
dtd(html, DTD),
setup_call_cleanup(
http_open(URL, Stream,
[ final_url(OpenID0),
cert_verify_hook(ssl_verify)
]),
load_structure(Stream, Term,
[ dtd(DTD),
dialect(sgml),
shorttag(false),
syntax_errors(quiet)
]),
close(Stream)),
debug(openid(resolve), 'Scanning HTML document ...', []),
contains_term(element(head, _, Head), Term),
( link(Head, 'openid.server', Server)
-> debug(openid(resolve), 'OpenID Server=~q', [Server])
; debug(openid(resolve), 'No server in ~q', [Head]),
fail
),
( link(Head, 'openid.delegate', OpenID)
-> debug(openid(resolve), 'OpenID = ~q (delegated)', [OpenID])
; OpenID = OpenID0,
debug(openid(resolve), 'OpenID = ~q', [OpenID])
).
openid_identifier_select_url(
'http://specs.openid.net/auth/2.0/identifier_select').
:- public ssl_verify/5.
%! ssl_verify(+SSL, +ProblemCert, +AllCerts, +FirstCert, +Error)
%
% Accept all certificates. We do not care too much. Only the user
% cares s/he is not entering her credentials with a spoofed side.
% As we redirect, the browser will take care of this.
ssl_verify(_SSL,
_ProblemCertificate, _AllCertificates, _FirstCertificate,
_Error).
link(DOM, Type, Target) :-
sub_term(element(link, Attrs, []), DOM),
memberchk(rel=Type, Attrs),
memberchk(href=Target, Attrs).
/*******************************
* AUTHENTICATE *
*******************************/
%! openid_authenticate(+Request)
%
% HTTP handler when redirected back from the OpenID provider.
openid_authenticate(Request) :-
memberchk(accept(Accept), Request),
Accept = [media(application/'xrds+xml',_,_,_)],
!,
http_link_to_id(openid_xrds, [], XRDSLocation),
http_absolute_uri(XRDSLocation, XRDSServer),
debug(openid(yadis), 'Sending XRDS server: ~q', [XRDSServer]),
format('X-XRDS-Location: ~w\n', [XRDSServer]),
format('Content-type: text/plain\n\n').
openid_authenticate(Request) :-
openid_authenticate(Request, _OpenIdServer, OpenID, _ReturnTo),
openid_server(User, OpenID, _, Target),
openid_login(User),
redirect_browser(Target, []).
%! openid_authenticate(+Request, -Server:url, -OpenID:url,
%! -ReturnTo:url) is semidet.
%
% Succeeds if Request comes from the OpenID server and confirms
% that User is a verified OpenID user. ReturnTo provides the URL
% to return to.
%
% After openid_verify/2 has redirected the browser to the OpenID
% server, and the OpenID server did its magic, it redirects the
% browser back to this address. The work is fairly trivial. If
% =mode= is =cancel=, the OpenId server denied. If =id_res=, the
% OpenId server replied positive, but we must verify what the
% server told us by checking the HMAC-SHA signature.
%
% This call fails silently if their is no =|openid.mode|= field in
% the request.
%
% @throws openid(cancel)
% if request was cancelled by the OpenId server
% @throws openid(signature_mismatch)
% if the HMAC signature check failed
openid_authenticate(Request, OpenIdServer, Identity, ReturnTo) :-
memberchk(method(get), Request),
http_parameters(Request,
[ 'openid.mode'(Mode, [optional(true)])
]),
( var(Mode)
-> fail
; Mode == cancel
-> throw(openid(cancel))
; Mode == id_res
-> debug(openid(authenticate), 'Mode=id_res, validating response', []),
http_parameters(Request,
[ 'openid.identity'(Identity, []),
'openid.assoc_handle'(Handle, []),
'openid.return_to'(ReturnTo, []),
'openid.signed'(AtomFields, []),
'openid.sig'(Base64Signature, []),
'openid.invalidate_handle'(Invalidate,
[optional(true)])
],
[ form_data(Form)
]),
atomic_list_concat(SignedFields, ',', AtomFields),
check_obligatory_fields(SignedFields),
signed_pairs(SignedFields,
[ mode-Mode,
identity-Identity,
assoc_handle-Handle,
return_to-ReturnTo,
invalidate_handle-Invalidate
],
Form,
SignedPairs),
( openid_associate(OpenIdServer, Handle, Assoc)
-> signature(SignedPairs, Assoc, Sig),
atom_codes(Base64Signature, Base64SigCodes),
phrase(base64(Signature), Base64SigCodes),
( Sig == Signature
-> true
; throw(openid(signature_mismatch))
)
; check_authentication(Request, Form)
),
ax_store(Form)
).
%! signed_pairs(+FieldNames, +Pairs:list(Field-Value),
%! +Form, -SignedPairs) is det.
%
% Extract the signed field in the order they appear in FieldNames.
signed_pairs([], _, _, []).
signed_pairs([Field|T0], Pairs, Form, [Field-Value|T]) :-
memberchk(Field-Value, Pairs),
!,
signed_pairs(T0, Pairs, Form, T).
signed_pairs([Field|T0], Pairs, Form, [Field-Value|T]) :-
atom_concat('openid.', Field, OpenIdField),
memberchk(OpenIdField=Value, Form),
!,
signed_pairs(T0, Pairs, Form, T).
signed_pairs([Field|T0], Pairs, Form, T) :-
format(user_error, 'Form = ~p~n', [Form]),
throw(error(existence_error(field, Field),
context(_, 'OpenID Signed field is not present'))),
signed_pairs(T0, Pairs, Form, T).
%! check_obligatory_fields(+SignedFields:list) is det.
%
% Verify fields from obligatory_field/1 are in the signed field
% list.
%
% @error existence_error(field, Field)
check_obligatory_fields(Fields) :-
( obligatory_field(Field),
( memberchk(Field, Fields)
-> true
; throw(error(existence_error(field, Field),
context(_, 'OpenID field is not in signed fields')))
),
fail
; true
).
obligatory_field(identity).
%! check_authentication(+Request, +Form) is semidet.
%
% Implement the stateless verification method. This seems needed
% for stackexchange.com, which provides the =res_id= with a new
% association handle.
check_authentication(_Request, Form) :-
openid_server(_OpenIDLogin, _OpenID, Server),
debug(openid(check_authentication),
'Using stateless verification with ~q form~n~q', [Server, Form]),
select('openid.mode' = _, Form, Form1),
setup_call_cleanup(
http_open(Server, In,
[ post(form([ 'openid.mode' = check_authentication
| Form1
])),
cert_verify_hook(ssl_verify)
]),
read_stream_to_codes(In, Reply),
close(In)),
debug(openid(check_authentication),
'Reply: ~n~s~n', [Reply]),
key_values_data(Pairs, Reply),
forall(member(invalidate_handle-Handle, Pairs),
retractall(association(_, Handle, _))),
memberchk(is_valid-true, Pairs).
/*******************************
* AX HANDLING *
*******************************/
%! ax_options(+ServerOptions, +Options, +AXAttrs) is det.
%
% True when AXAttrs is a list of additional attribute exchange
% options to add to the OpenID redirect request.
ax_options(ServerOptions, Options, AXAttrs) :-
option(ax(Spec), Options),
option(xrds_types(Types), ServerOptions),
memberchk('http://openid.net/srv/ax/1.0', Types),
!,
http_ax_attributes(Spec, AXAttrs),
debug(openid(ax), 'AX attributes: ~q', [AXAttrs]).
ax_options(_, _, []) :-
debug(openid(ax), 'AX: not supported', []).
%! ax_store(+Form)
%
% Extract reported AX data and store this into the session. If
% there is a non-empty list of exchanged values, this calls
%
% openid_hook(ax(Values))
%
% If this hook fails, Values are added to the session data using
% http_session_assert(ax(Values)).
ax_store(Form) :-
debug(openid(ax), 'Form: ~q', [Form]),
ax_form_attributes(Form, Values),
debug(openid(ax), 'AX: ~q', [Values]),
( Values \== []
-> ( openid_hook(ax(Values))
-> true
; http_session_assert(ax(Values))
)
; true
).
/*******************************
* OPENID SERVER *
*******************************/
:- dynamic
server_association/3. % URL, Handle, Term
%! openid_server(+Options, +Request)
%
% Realise the OpenID server. The protocol demands a POST request
% here.
openid_server(Options, Request) :-
http_parameters(Request,
[ 'openid.mode'(Mode)
],
[ attribute_declarations(openid_attribute),
form_data(Form)
]),
( Mode == associate
-> associate_server(Request, Form, Options)
; Mode == checkid_setup
-> checkid_setup_server(Request, Form, Options)
).
%! associate_server(+Request, +Form, +Options)
%
% Handle the association-request. If successful, create a clause
% for server_association/3 to record the current association.
associate_server(Request, Form, Options) :-
memberchk('openid.assoc_type' = AssocType, Form),
memberchk('openid.session_type' = SessionType, Form),
memberchk('openid.dh_modulus' = P64, Form),
memberchk('openid.dh_gen' = G64, Form),
memberchk('openid.dh_consumer_public' = CPX64, Form),
base64_btwoc(P, P64),
base64_btwoc(G, G64),
base64_btwoc(CPX, CPX64),
Y is 1+random(P-1), % Our secret
DiffieHellman is powm(CPX, Y, P),
btwoc(DiffieHellman, DHBytes),
signature_algorithm(SessionType, SHA_Algo),
sha_hash(DHBytes, SHA1, [encoding(octet), algorithm(SHA_Algo)]),
CPY is powm(G, Y, P),
base64_btwoc(CPY, CPY64),
mackey_bytes(SessionType, MacBytes),
new_assoc_handle(MacBytes, Handle),
random_bytes(MacBytes, MacKey),
xor_codes(MacKey, SHA1, EncKey),
phrase(base64(EncKey), Base64EncKey),