/usr/share/perl5/Net/OpenID/Consumer.pm is in libnet-openid-consumer-perl 1.15-1.
This file is owned by root:root, with mode 0o644.
The actual contents of the file can be viewed below.
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 1001 1002 1003 1004 1005 1006 1007 1008 1009 1010 1011 1012 1013 1014 1015 1016 1017 1018 1019 1020 1021 1022 1023 1024 1025 1026 1027 1028 1029 1030 1031 1032 1033 1034 1035 1036 1037 1038 1039 1040 1041 1042 1043 1044 1045 1046 1047 1048 1049 1050 1051 1052 1053 1054 1055 1056 1057 1058 1059 1060 1061 1062 1063 1064 1065 1066 1067 1068 1069 1070 1071 1072 1073 1074 1075 1076 1077 1078 1079 1080 1081 1082 1083 1084 1085 1086 1087 1088 1089 1090 1091 1092 1093 1094 1095 1096 1097 1098 1099 1100 1101 1102 1103 1104 1105 1106 1107 1108 1109 1110 1111 1112 1113 1114 1115 1116 1117 1118 1119 1120 1121 1122 1123 1124 1125 1126 1127 1128 1129 1130 1131 1132 1133 1134 1135 1136 1137 1138 1139 1140 1141 1142 1143 1144 1145 1146 1147 1148 1149 1150 1151 1152 1153 1154 1155 1156 1157 1158 1159 1160 1161 1162 1163 1164 1165 1166 1167 1168 1169 1170 1171 1172 1173 1174 1175 1176 1177 1178 1179 1180 1181 1182 1183 1184 1185 1186 1187 1188 1189 1190 1191 1192 1193 1194 1195 1196 1197 1198 1199 1200 1201 1202 1203 1204 1205 1206 1207 1208 1209 1210 1211 1212 1213 1214 1215 1216 1217 1218 1219 1220 1221 1222 1223 1224 1225 1226 1227 1228 1229 1230 1231 1232 1233 1234 1235 1236 1237 1238 1239 1240 1241 1242 1243 1244 1245 1246 1247 1248 1249 1250 1251 1252 1253 1254 1255 1256 1257 1258 1259 1260 1261 1262 1263 1264 1265 1266 1267 1268 1269 1270 1271 1272 1273 1274 1275 1276 1277 1278 1279 1280 1281 1282 1283 1284 1285 1286 1287 1288 1289 1290 1291 1292 1293 1294 1295 1296 1297 1298 1299 1300 1301 1302 1303 1304 1305 1306 1307 1308 1309 1310 1311 1312 1313 1314 1315 1316 1317 1318 1319 1320 1321 1322 1323 1324 1325 1326 1327 1328 1329 1330 1331 1332 1333 1334 1335 1336 1337 1338 1339 1340 1341 1342 1343 1344 1345 1346 1347 1348 1349 1350 1351 1352 1353 1354 1355 1356 1357 1358 1359 1360 1361 1362 1363 1364 1365 1366 1367 1368 1369 1370 1371 1372 1373 1374 1375 1376 1377 1378 1379 1380 1381 1382 1383 1384 1385 1386 1387 1388 1389 1390 1391 1392 1393 1394 1395 1396 1397 1398 1399 1400 1401 1402 1403 1404 1405 1406 1407 1408 1409 1410 1411 1412 1413 1414 1415 1416 1417 1418 1419 1420 1421 1422 1423 1424 1425 1426 1427 1428 1429 1430 1431 1432 1433 1434 1435 1436 1437 1438 1439 1440 1441 1442 1443 1444 1445 1446 1447 1448 1449 1450 1451 1452 1453 1454 1455 1456 1457 1458 1459 1460 1461 1462 1463 1464 1465 1466 1467 1468 1469 1470 1471 1472 1473 1474 1475 1476 1477 1478 1479 1480 1481 1482 1483 1484 1485 1486 1487 1488 1489 1490 1491 1492 1493 1494 1495 1496 1497 1498 1499 1500 1501 1502 1503 1504 1505 1506 1507 1508 1509 1510 1511 1512 1513 1514 1515 1516 1517 1518 1519 1520 1521 1522 1523 1524 1525 1526 1527 1528 1529 1530 1531 1532 1533 1534 1535 1536 1537 1538 1539 1540 1541 1542 1543 1544 1545 1546 1547 1548 1549 1550 1551 1552 1553 1554 1555 1556 1557 1558 1559 1560 1561 1562 1563 1564 1565 1566 1567 1568 1569 1570 1571 1572 1573 1574 1575 1576 1577 1578 1579 1580 1581 1582 1583 1584 1585 1586 1587 1588 1589 1590 1591 1592 1593 1594 1595 1596 1597 1598 1599 1600 1601 1602 1603 1604 1605 1606 1607 1608 1609 1610 1611 1612 1613 1614 1615 1616 1617 1618 1619 1620 1621 1622 1623 1624 1625 1626 1627 1628 1629 1630 1631 1632 1633 1634 1635 1636 1637 1638 1639 1640 1641 1642 1643 1644 1645 1646 1647 1648 1649 1650 1651 1652 1653 1654 1655 1656 1657 1658 1659 1660 1661 1662 1663 1664 1665 1666 1667 1668 1669 1670 1671 1672 1673 1674 1675 1676 1677 1678 1679 1680 1681 1682 1683 1684 1685 1686 1687 1688 1689 1690 1691 1692 1693 1694 1695 1696 1697 1698 1699 1700 1701 1702 1703 1704 1705 1706 1707 1708 1709 1710 1711 1712 1713 1714 1715 1716 1717 1718 1719 1720 1721 1722 1723 1724 1725 1726 1727 1728 1729 1730 1731 1732 1733 1734 1735 1736 1737 1738 1739 1740 1741 1742 1743 1744 1745 1746 1747 1748 1749 1750 1751 1752 1753 1754 1755 1756 1757 1758 1759 1760 1761 1762 1763 1764 1765 1766 1767 1768 1769 1770 1771 1772 1773 1774 1775 1776 1777 1778 1779 1780 1781 1782 1783 1784 1785 1786 1787 1788 1789 1790 1791 1792 1793 1794 1795 1796 1797 1798 1799 1800 1801 1802 1803 1804 1805 1806 1807 1808 1809 1810 1811 1812 1813 1814 1815 1816 1817 1818 1819 1820 1821 1822 1823 1824 1825 1826 1827 1828 1829 1830 1831 1832 1833 1834 1835 1836 1837 1838 1839 1840 1841 1842 1843 1844 1845 1846 1847 1848 1849 1850 1851 1852 1853 1854 1855 1856 1857 1858 1859 1860 1861 1862 1863 1864 1865 1866 1867 1868 1869 1870 1871 1872 1873 1874 1875 1876 1877 1878 1879 1880 1881 1882 1883 1884 1885 1886 1887 1888 1889 1890 1891 1892 1893 1894 1895 1896 1897 1898 1899 1900 1901 1902 1903 1904 1905 1906 1907 1908 1909 1910 1911 1912 1913 1914 1915 1916 1917 1918 1919 1920 1921 1922 1923 1924 1925 1926 1927 1928 1929 1930 1931 1932 1933 1934 1935 1936 1937 1938 1939 1940 1941 1942 1943 1944 1945 1946 1947 1948 1949 1950 1951 1952 1953 1954 1955 1956 1957 1958 1959 1960 1961 1962 1963 1964 1965 1966 1967 1968 1969 1970 1971 1972 1973 1974 1975 1976 1977 1978 1979 1980 1981 1982 1983 1984 1985 1986 1987 1988 1989 1990 1991 1992 1993 1994 1995 1996 1997 1998 1999 2000 2001 2002 2003 2004 2005 2006 2007 2008 2009 2010 2011 2012 2013 2014 2015 2016 2017 2018 2019 2020 2021 2022 2023 2024 2025 2026 2027 2028 2029 2030 2031 2032 2033 2034 2035 2036 2037 2038 2039 2040 2041 2042 2043 2044 | # LICENSE: You're free to distribute this under the same terms as Perl itself.
use strict;
use Carp ();
############################################################################
package Net::OpenID::Consumer;
{
$Net::OpenID::Consumer::VERSION = '1.15';
}
use fields (
'cache', # Cache object to store HTTP responses,
# associations, and nonces
'ua', # LWP::UserAgent instance to use
'args', # how to get at your args
'message', # args interpreted as an IndirectMessage, if possible
'consumer_secret', # scalar/subref
'required_root', # the default required_root value, or undef
'last_errcode', # last error code we got
'last_errtext', # last error code we got
'debug', # debug flag or codeblock
'minimum_version', # The minimum protocol version to support
'assoc_options', # options for establishing ID provider associations
'nonce_options', # options for dealing with nonces
);
use Net::OpenID::ClaimedIdentity;
use Net::OpenID::VerifiedIdentity;
use Net::OpenID::Association;
use Net::OpenID::Yadis;
use Net::OpenID::IndirectMessage;
use Net::OpenID::URIFetch;
use Net::OpenID::Common; # To get the OpenID::util package
use MIME::Base64 ();
use Digest::SHA qw(hmac_sha1_hex);
use Time::Local;
use HTTP::Request;
use LWP::UserAgent;
use Storable;
use JSON qw(encode_json);
use URI::Escape qw(uri_escape_utf8);
use HTML::Parser;
sub new {
my Net::OpenID::Consumer $self = shift;
$self = fields::new( $self ) unless ref $self;
my %opts = @_;
$self->{ua} = delete $opts{ua};
$self->args ( delete $opts{args} );
$self->cache ( delete $opts{cache} );
$self->consumer_secret ( delete $opts{consumer_secret} );
$self->required_root ( delete $opts{required_root} );
$self->minimum_version ( delete $opts{minimum_version} );
$self->assoc_options ( delete $opts{assoc_options} );
$self->nonce_options ( delete $opts{nonce_options} );
$self->{debug} = delete $opts{debug};
Carp::croak("Unknown options: " . join(", ", keys %opts)) if %opts;
return $self;
}
# NOTE: This method is here only to support the openid-test library.
# Don't call it from anywhere else, or you'll break when it gets
# removed. Instead, call minimum_version(2).
# FIXME: Can we just make openid-test do that and get rid of this?
sub disable_version_1 {
$_[0]->minimum_version(2);
}
sub cache { &_getset; }
sub consumer_secret { &_getset; }
sub required_root { &_getset; }
sub assoc_options { &_hashgetset }
sub nonce_options { &_hashgetset }
sub _getset {
my Net::OpenID::Consumer $self = shift;
my $param = (caller(1))[3];
$param =~ s/.+:://;
if (@_) {
my $val = shift;
Carp::croak("Too many parameters") if @_;
$self->{$param} = $val;
}
return $self->{$param};
}
sub _hashgetset {
my Net::OpenID::Consumer $self = shift;
my $param = (caller(1))[3];
$param =~ s/.+:://;
my $check_param = "_canonicalize_$param";
my $v;
if (scalar(@_) == 1) {
$v = shift;
unless ($v) {
$v = {};
}
elsif (ref $v eq 'ARRAY') {
$v = {@$v};
}
elsif (ref $v) {
# assume it's a hash and hope for the best
$v = {%$v};
}
else {
Carp::croak("single argument must be HASH or ARRAY reference");
}
$self->{$param} = $self->$check_param($v);
}
elsif (@_) {
Carp::croak("odd number of parameters?")
if scalar(@_)%2;
$self->{$param} = $self->$check_param({@_});
}
return $self->{$param};
}
sub minimum_version {
my Net::OpenID::Consumer $self = shift;
if (@_) {
my $minv = shift;
Carp::croak("Too many parameters") if @_;
$minv = 1 unless $minv && $minv > 1;
$self->{minimum_version} = $minv;
}
return $self->{minimum_version};
}
sub _canonicalize_assoc_options { return $_[1]; }
sub _debug {
my Net::OpenID::Consumer $self = shift;
return unless $self->{debug};
if (ref $self->{debug} eq "CODE") {
$self->{debug}->($_[0]);
} else {
print STDERR "[DEBUG Net::OpenID::Consumer] $_[0]\n";
}
}
# given something that can have GET arguments, returns a subref to get them:
# Apache
# Apache::Request
# CGI
# HASH of get args
# CODE returning get arg, given key
# ...
sub args {
my Net::OpenID::Consumer $self = shift;
if (my $what = shift) {
unless (ref $what) {
return $self->{args} ? $self->{args}->($what) : Carp::croak("No args defined");
}
Carp::croak("Too many parameters") if @_;
# since we do not require field setters to be called in any particular order,
# we cannot pass minimum_version here as it might change later.
my $message = Net::OpenID::IndirectMessage->new($what);
$self->{message} = $message;
if ($message) {
$self->{args} = $message->getter;
# handle OpenID 2.0 'error' mode
# (may as well do this here; we may not get another chance
# since handle_server_response is not a required part of the API)
if ($message->protocol_version >= 2 && $message->mode eq 'error') {
$self->_fail('provider_error',$message->get('error'));
}
}
else {
$self->{args} = sub { undef };
}
}
$self->{args};
}
sub message {
my Net::OpenID::Consumer $self = shift;
my $message = $self->{message};
return undef
unless $message &&
($self->{minimum_version} <= $message->protocol_version);
if (@_) {
return $message->get($_[0]);
}
else {
return $message;
}
}
sub _message_mode_is {
return (($_[0]->message('mode')||' ') eq $_[1]);
}
sub _message_version {
my $message = $_[0]->message;
return $message ? $message->protocol_version : 0;
}
sub ua {
my Net::OpenID::Consumer $self = shift;
$self->{ua} = shift if @_;
Carp::croak("Too many parameters") if @_;
# make default one on first access
unless ($self->{ua}) {
my $ua = $self->{ua} = LWP::UserAgent->new;
$ua->timeout(10);
}
$self->{ua};
}
our %Error_text =
(
'bad_mode' => "The openid.mode argument is not correct",
'bogus_delegation' => "Asserted identity does not match claimed_id or local_id.",
'bogus_return_to' => "Return URL does not match required_root.",
'bogus_url' => "URL scheme must be http: or https:",
'empty_url' => "No URL entered.",
'expired_association' => "Association between ID provider and relying party has expired.",
'naive_verify_failed_network' => "Could not contact ID provider to verify response.",
'naive_verify_failed_return' => "Direct contact invalidated ID provider response.",
'no_identity' => "Identity is missing from ID provider response.",
'no_identity_server' => "Could not determine ID provider from URL.",
'no_return_to' => "Return URL is missing from ID provider response.",
'no_sig' => "Signature is missing from ID provider response.",
'protocol_version_incorrect' => "ID provider does not support minimum protocol version",
'provider_error' => "ID provider-specific error",
'server_not_allowed' => "None of the discovered endpoints matches op_endpoint.",
'signature_mismatch' => "Prior association invalidated ID provider response.",
'time_bad_sig' => "Return_to signature is not valid.",
'time_expired' => "Return_to signature is stale.",
'time_in_future' => "Return_to signature is from the future.",
'unexpected_url_redirect' => "Discovery for the given ID ended up at the wrong place",
'unsigned_field' => sub { "Field(s) must be signed: " . join(", ", @_) },
'nonce_missing' => "Response_nonce is missing from ID provider response.",
'nonce_reused' => 'Re-used response_nonce; possible replay attempt.',
'nonce_stale' => 'Stale response_nonce; could have been used before.',
'nonce_format' => 'Bad timestamp format in response_nonce.',
'nonce_future' => 'Provider clock is too far forward.',
# no longer used as of 1.11
# 'no_head_tag' => "Could not determine ID provider; URL document has no <head>.",
# 'url_fetch_err' => "Error fetching the provided URL.",
);
sub _fail {
my Net::OpenID::Consumer $self = shift;
my ($code, $text, @params) = @_;
# 'bad_mode' is only an error if we survive to the end of
# .mode dispatch without having figured out what to do;
# it should not overwrite other errors.
unless ($self->{last_errcode} && $code eq 'bad_mode') {
$text ||= $Error_text{$code};
$text = $text->(@params) if ref($text) && ref($text) eq 'CODE';
$self->{last_errcode} = $code;
$self->{last_errtext} = $text;
$self->_debug("fail($code) $text");
}
wantarray ? () : undef;
}
sub json_err {
my Net::OpenID::Consumer $self = shift;
return encode_json({
err_code => $self->{last_errcode},
err_text => $self->{last_errtext},
});
}
sub err {
my Net::OpenID::Consumer $self = shift;
$self->{last_errcode} . ": " . $self->{last_errtext};
}
sub errcode {
my Net::OpenID::Consumer $self = shift;
$self->{last_errcode};
}
sub errtext {
my Net::OpenID::Consumer $self = shift;
$self->{last_errtext};
}
# make sure you change the $prefix every time you change the $hook format
# so that when user installs a new version and the old cache server is
# still running the old cache entries won't confuse things.
sub _get_url_contents {
my Net::OpenID::Consumer $self = shift;
my ($url, $final_url_ref, $hook, $prefix) = @_;
$final_url_ref ||= do { my $dummy; \$dummy; };
my $res = Net::OpenID::URIFetch->fetch($url, $self, $hook, $prefix);
$$final_url_ref = $res->final_uri;
return $res ? $res->content : undef;
}
# List of head elements that matter for HTTP discovery.
# Each entry defines a key+value that will appear in the
# _find_semantic_info hash if the specified element exists
# [
# FSI_KEY -- key name
# TAG_NAME -- must be 'link' or 'meta'
#
# ELT_VALUES -- string (default = FSI_KEY)
# what join(';',values of ELT_KEYS) has to match
# in order for a given html element to provide
# the value for FSI_KEY
#
# ELT_KEYS -- list-ref of html attribute names
# default = ['rel'] for <link...>
# default = ['name'] for <meta...>
#
# FSI_VALUE -- name of html attribute where value lives
# default = 'href' for <link...>
# default = 'content' for <meta...>
# ]
#
our @HTTP_discovery_link_meta_tags =
map {
my ($fsi_key, $tag, $elt_value, $elt_keys, $fsi_value) = @{$_};
[$fsi_key, $tag,
$elt_value || $fsi_key,
$elt_keys || [$tag eq 'link' ? 'rel' : 'name'],
$fsi_value || ($tag eq 'link' ? 'href' : 'content'),
]
}
# OpenID providers / delegated identities
# <link rel="openid.server"
# href="http://www.livejournal.com/misc/openid.bml" />
# <link rel="openid.delegate"
# href="whatever" />
#
[qw(openid.server link)], # 'openid.server' => ['rel'], 'href'
[qw(openid.delegate link)],
# OpenID2 providers / local identifiers
# <link rel="openid2.provider"
# href="http://www.livejournal.com/misc/openid.bml" />
# <link rel="openid2.local_id" href="whatever" />
#
[qw(openid2.provider link)],
[qw(openid2.local_id link)],
# FOAF maker info
# <meta name="foaf:maker"
# content="foaf:mbox_sha1sum '4caa1d6f6203d21705a00a7aca86203e82a9cf7a'"/>
#
[qw(foaf.maker meta foaf:maker)], # == .name
# FOAF documents
# <link rel="meta" type="application/rdf+xml" title="FOAF"
# href="http://brad.livejournal.com/data/foaf" />
#
[qw(foaf link), 'meta;foaf;application/rdf+xml' => [qw(rel title type)]],
# RSS
# <link rel="alternate" type="application/rss+xml" title="RSS"
# href="http://www.livejournal.com/~brad/data/rss" />
#
[qw(rss link), 'alternate;application/rss+xml' => [qw(rel type)]],
# Atom
# <link rel="alternate" type="application/atom+xml" title="Atom"
# href="http://www.livejournal.com/~brad/data/rss" />
#
[qw(atom link), 'alternate;application/atom+xml' => [qw(rel type)]],
;
sub _document_to_semantic_info {
my $doc = shift;
my $info = {};
my $elts = OpenID::util::html_extract_linkmetas($doc);
for (@HTTP_discovery_link_meta_tags) {
my ($key, $tag, $elt_value, $elt_keys, $vattrib) = @$_;
for my $lm (@{$elts->{$tag}}) {
$info->{$key} = $lm->{$vattrib}
if $elt_value eq join ';', map {lc($lm->{$_}||'')} @$elt_keys;
}
}
return $info;
}
sub _find_semantic_info {
my Net::OpenID::Consumer $self = shift;
my $url = shift;
my $final_url_ref = shift;
my $doc = $self->_get_url_contents($url, $final_url_ref);
my $info = _document_to_semantic_info($doc);
$self->_debug("semantic info ($url) = " . join(", ", map { $_.' => '.$info->{$_} } keys %$info)) if $self->{debug};
return $info;
}
sub _find_openid_server {
my Net::OpenID::Consumer $self = shift;
my $url = shift;
my $final_url_ref = shift;
my $sem_info = $self->_find_semantic_info($url, $final_url_ref) or
return;
return $self->_fail("no_identity_server") unless $sem_info->{"openid.server"};
$sem_info->{"openid.server"};
}
sub is_server_response {
my Net::OpenID::Consumer $self = shift;
return $self->message ? 1 : 0;
}
my $_warned_about_setup_required = 0;
sub handle_server_response {
my Net::OpenID::Consumer $self = shift;
my %callbacks_in = @_;
my %callbacks = ();
foreach my $cb (qw(not_openid cancelled verified error)) {
$callbacks{$cb} = delete($callbacks_in{$cb}) || sub { Carp::croak("No ".$cb." callback") };
}
# backwards compatibility:
# 'setup_needed' is expected as of 1.04
# 'setup_required' is deprecated but allowed in its place,
my $found_setup_callback = 0;
foreach my $cb (qw(setup_needed setup_required)) {
$callbacks{$cb} = delete($callbacks_in{$cb}) and $found_setup_callback++;
}
Carp::croak($found_setup_callback > 1
? "Cannot have both setup_needed and setup_required"
: "No setup_needed callback")
unless $found_setup_callback == 1;
if (warnings::enabled('deprecated') &&
$callbacks{setup_required} &&
!$_warned_about_setup_required++
) {
warnings::warn
("deprecated",
"'setup_required' callback is deprecated, use 'setup_needed'");
}
Carp::croak("Unknown callbacks: ".join(',', keys %callbacks_in))
if %callbacks_in;
unless ($self->is_server_response) {
return $callbacks{not_openid}->();
}
if ($self->setup_needed) {
return $callbacks{setup_needed}->()
unless ($callbacks{setup_required});
my $setup_url = $self->user_setup_url;
return $callbacks{setup_required}->($setup_url)
if $setup_url;
# otherwise FALL THROUGH to preserve prior behavior,
# Even though this is broken, old clients could have
# put a workaround into the 'error' callback to handle
# the setup_needed+(setup_url=undef) case
}
if ($self->user_cancel) {
return $callbacks{cancelled}->();
}
elsif (my $vident = $self->verified_identity) {
return $callbacks{verified}->($vident);
}
else {
return $callbacks{error}->($self->errcode, $self->errtext);
}
}
sub _canonicalize_id_url {
my Net::OpenID::Consumer $self = shift;
my $url = shift;
# trim whitespace
$url =~ s/^\s+//;
$url =~ s/\s+$//;
return $self->_fail("empty_url") unless $url;
# add scheme
$url = "http://$url" if $url && $url !~ m!^\w+://!;
return $self->_fail("bogus_url") unless $url =~ m!^https?://!i;
# make sure there is a slash after the hostname
$url .= "/" unless $url =~ m!^https?://.+/!i;
return $url;
}
# always returns a listref; might be empty, though
sub _discover_acceptable_endpoints {
my Net::OpenID::Consumer $self = shift;
my $url = shift; #already canonicalized ID url
my %opts = @_;
# if return_early is set, we'll return as soon as we have enough
# information to determine the "primary" endpoint, and return
# that as the first (and possibly only) item in our response.
my $primary_only = delete $opts{primary_only} ? 1 : 0;
# if force_version is set, we only return endpoints that have
# that have {version} == $force_version
my $force_version = delete $opts{force_version};
Carp::croak("Unknown option(s) ".join(', ', keys(%opts))) if %opts;
my @discovered_endpoints = ();
my $result = sub {
# We always prefer 2.0 endpoints to 1.1 ones, regardless of
# the priority chosen by the identifier.
return [
(grep { $_->{version} == 2 } @discovered_endpoints),
(grep { $_->{version} == 1 } @discovered_endpoints),
];
};
# TODO: Support XRI too?
# First we Yadis service discovery
my $yadis = Net::OpenID::Yadis->new(consumer => $self);
if ($yadis->discover($url)) {
# FIXME: Currently we don't ever do _find_semantic_info in the Yadis
# code path, so an extra redundant HTTP request is done later
# when the semantic info is accessed.
my $final_url = $yadis->identity_url;
my @services = $yadis->services(
OpenID::util::version_2_xrds_service_url(),
OpenID::util::version_2_xrds_directed_service_url(),
OpenID::util::version_1_xrds_service_url(),
);
my $version2 = OpenID::util::version_2_xrds_service_url();
my $version1 = OpenID::util::version_1_xrds_service_url();
my $version2_directed = OpenID::util::version_2_xrds_directed_service_url();
foreach my $service (@services) {
my $service_uris = $service->URI;
# Service->URI seems to return all sorts of bizarre things, so let's
# normalize it to always be an arrayref.
if (ref($service_uris) eq 'ARRAY') {
my @sorted_id_servers = sort {
my $pa = $a->{priority};
my $pb = $b->{priority};
defined($pb) <=> defined($pa)
|| (defined($pa) ? ($pa <=> $pb) : 0)
} @$service_uris;
$service_uris = \@sorted_id_servers;
}
if (ref($service_uris) eq 'HASH') {
$service_uris = [ $service_uris->{content} ];
}
unless (ref($service_uris)) {
$service_uris = [ $service_uris ];
}
my $delegate = undef;
my @versions = ();
if (grep(/^${version2}$/, $service->Type)) {
# We have an OpenID 2.0 end-user identifier
$delegate = $service->extra_field("LocalID");
push @versions, 2;
}
if (grep(/^${version1}$/, $service->Type)) {
# We have an OpenID 1.1 end-user identifier
$delegate = $service->extra_field("Delegate", "http://openid.net/xmlns/1.0");
push @versions, 1;
}
if (@versions) {
foreach my $version (@versions) {
next if defined($force_version) && $force_version != $version;
foreach my $uri (@$service_uris) {
push @discovered_endpoints, {
uri => $uri,
version => $version,
final_url => $final_url,
delegate => $delegate,
sem_info => undef,
mechanism => "Yadis",
};
}
}
}
if (((!defined($force_version)) || $force_version == 2)
&& grep(/^${version2_directed}$/, $service->Type)) {
# We have an OpenID 2.0 OP identifier (i.e. we're doing directed identity)
my $version = 2;
# In this case, the user's claimed identifier is a magic value
# and the actual identifier will be determined by the provider.
my $final_url = OpenID::util::version_2_identifier_select_url();
my $delegate = OpenID::util::version_2_identifier_select_url();
foreach my $uri (@$service_uris) {
push @discovered_endpoints, {
uri => $uri,
version => $version,
final_url => $final_url,
delegate => $delegate,
sem_info => undef,
mechanism => "Yadis",
};
}
}
if ($primary_only && scalar(@discovered_endpoints)) {
# We've got at least one endpoint now, so return early
return $result->();
}
}
}
# Now HTML-based discovery, both 2.0- and 1.1-style.
{
my $final_url = undef;
my $sem_info = $self->_find_semantic_info($url, \$final_url);
if ($sem_info) {
if ($sem_info->{"openid2.provider"}) {
unless (defined($force_version) && $force_version != 2) {
push @discovered_endpoints, {
uri => $sem_info->{"openid2.provider"},
version => 2,
final_url => $final_url,
delegate => $sem_info->{"openid2.local_id"},
sem_info => $sem_info,
mechanism => "HTML",
};
}
}
if ($sem_info->{"openid.server"}) {
unless (defined($force_version) && $force_version != 1) {
push @discovered_endpoints, {
uri => $sem_info->{"openid.server"},
version => 1,
final_url => $final_url,
delegate => $sem_info->{"openid.delegate"},
sem_info => $sem_info,
mechanism => "HTML",
};
}
}
}
}
return $result->();
}
# returns Net::OpenID::ClaimedIdentity
sub claimed_identity {
my Net::OpenID::Consumer $self = shift;
my $url = shift;
Carp::croak("Too many parameters") if @_;
return unless $url = $self->_canonicalize_id_url($url);
my $endpoints = $self->_discover_acceptable_endpoints($url, primary_only => 1);
if (@$endpoints) {
foreach my $endpoint (@$endpoints) {
next unless $endpoint->{version} >= $self->minimum_version;
$self->_debug("Discovered version $endpoint->{version} endpoint at $endpoint->{uri} via $endpoint->{mechanism}");
$self->_debug("Delegate is $endpoint->{delegate}") if $endpoint->{delegate};
return Net::OpenID::ClaimedIdentity->new(
identity => $endpoint->{final_url},
server => $endpoint->{uri},
consumer => $self,
delegate => $endpoint->{delegate},
protocol_version => $endpoint->{version},
semantic_info => $endpoint->{sem_info},
);
}
# If we've fallen out here, then none of the available services are of the required version.
return $self->_fail("protocol_version_incorrect");
}
else {
return $self->_fail("no_identity_server");
}
}
sub user_cancel {
my Net::OpenID::Consumer $self = shift;
return $self->_message_mode_is("cancel");
}
sub setup_needed {
my Net::OpenID::Consumer $self = shift;
if ($self->_message_version == 1) {
return $self->_message_mode_is("id_res") && $self->message("user_setup_url");
}
else {
return $self->_message_mode_is('setup_needed');
}
}
sub user_setup_url {
my Net::OpenID::Consumer $self = shift;
my %opts = @_;
my $post_grant = delete $opts{'post_grant'};
Carp::croak("Unknown options: " . join(", ", keys %opts)) if %opts;
if ($self->_message_version == 1) {
return $self->_fail("bad_mode") unless $self->_message_mode_is("id_res");
}
else {
return undef unless $self->_message_mode_is('setup_needed');
}
my $setup_url = $self->message("user_setup_url");
OpenID::util::push_url_arg(\$setup_url, "openid.post_grant", $post_grant)
if $setup_url && $post_grant;
return $setup_url;
}
sub verified_identity {
my Net::OpenID::Consumer $self = shift;
my %opts = @_;
my $rr = delete $opts{'required_root'} || $self->{required_root};
Carp::croak("Unknown options: " . join(", ", keys %opts)) if %opts;
return $self->_fail("bad_mode") unless $self->_message_mode_is("id_res");
# the asserted identity (the delegated one, if there is one, since the protocol
# knows nothing of the original URL)
my $a_ident = $self->message("identity") or return $self->_fail("no_identity");
my $sig64 = $self->message("sig") or return $self->_fail("no_sig");
# fix sig if the OpenID provider failed to properly escape pluses (+) in the sig
$sig64 =~ s/ /+/g;
my $returnto = $self->message("return_to") or return $self->_fail("no_return_to");
my $signed = $self->message("signed");
my $possible_endpoints;
my $server;
my $claimed_identity;
my $real_ident =
($self->_message_version == 1
? $self->args("oic.identity")
: $self->message("claimed_id")
) || $a_ident;
my $real_canon = $self->_canonicalize_id_url($real_ident);
return $self->_fail("no_identity_server")
unless ($real_canon
&& @{
$possible_endpoints =
$self->_discover_acceptable_endpoints
($real_canon, force_version => $self->_message_version)
});
# FIXME: It kinda sucks that the above will always do both Yadis and HTML discovery, even though
# in most cases only one will be in use.
if ($self->_message_version == 1) {
# In version 1, we have to assume that the primary server
# found during discovery is the one sending us this message.
splice(@$possible_endpoints,1);
$server = $possible_endpoints->[0]->{uri};
$self->_debug("Server is $server");
}
else {
# In version 2, the OpenID provider tells us its URL.
$server = $self->message("op_endpoint");
$self->_debug("Server is $server");
# but make sure that URL matches one of the discovered ones.
@$possible_endpoints =
grep {$_->{uri} eq $server} @$possible_endpoints
or return $self->_fail("server_not_allowed");
}
# check that returnto is for the right host
return $self->_fail("bogus_return_to") if $rr && $returnto !~ /^\Q$rr\E/;
my $now = time();
# check that we have not seen response_nonce before
my $response_nonce = $self->message("response_nonce");
unless ($response_nonce) {
# 1.0/1.1 does not require nonces
return $self->_fail("nonce_missing")
if $self->_message_version >= 2;
}
else {
return unless $self->_nonce_check_succeeds($now, $server, $response_nonce);
}
# check age/signature of return_to
{
my ($sig_time, $sig) = split(/\-/, $self->args("oic.time") || "");
# complain if more than an hour since we sent them off
return $self->_fail("time_expired") if $sig_time < $now - 3600;
# also complain if the signature is from the future by more than 30 seconds,
# which compensates for potential clock drift between nodes in a web farm.
return $self->_fail("time_in_future") if $sig_time - 30 > $now;
# and check that the time isn't faked
my $c_secret = $self->_get_consumer_secret($sig_time);
my $good_sig = substr(hmac_sha1_hex($sig_time, $c_secret), 0, 20);
return $self->_fail("time_bad_sig") unless OpenID::util::timing_indep_eq($sig, $good_sig);
}
my $last_error = undef;
my $error = sub {
$self->_debug("$server not acceptable: ".$_[0]);
$last_error = $_[0];
};
foreach my $endpoint (@$possible_endpoints) {
# Known:
# $endpoint->{version} == $self->_message_version
# $endpoint->{uri} == $server
my $final_url = $endpoint->{final_url};
my $delegate = $endpoint->{delegate};
# OpenID 2.0 wants us to exclude the fragment part of the URL when doing equality checks
my $a_ident_nofragment = $a_ident;
my $real_ident_nofragment = $real_ident;
my $final_url_nofragment = $final_url;
if ($self->_message_version >= 2) {
$a_ident_nofragment =~ s/\#.*$//x;
$real_ident_nofragment =~ s/\#.*$//x;
$final_url_nofragment =~ s/\#.*$//x;
}
unless ($final_url_nofragment eq $real_ident_nofragment) {
$error->("unexpected_url_redirect");
next;
}
# if openid.delegate was used, check that it was done correctly
if ($a_ident_nofragment ne $real_ident_nofragment) {
unless ($delegate eq $a_ident_nofragment) {
$error->("bogus_delegation");
next;
}
}
# If we've got this far then we've found the right endpoint.
$claimed_identity = Net::OpenID::ClaimedIdentity->new(
identity => $endpoint->{final_url},
server => $endpoint->{uri},
consumer => $self,
delegate => $endpoint->{delegate},
protocol_version => $endpoint->{version},
semantic_info => $endpoint->{sem_info},
);
last;
}
unless ($claimed_identity) {
# We failed to find a good endpoint in the above loop, so
# lets bail out.
return $self->_fail($last_error);
}
my $assoc_handle = $self->message("assoc_handle");
$self->_debug("verified_identity: assoc_handle" .
($assoc_handle ? ": $assoc_handle" : " missing"));
my $assoc = Net::OpenID::Association::handle_assoc($self, $server, $assoc_handle);
my @signed_fields = grep {m/^[\w\.]+$/} split(/,/, $signed);
my %signed_value = map {$_,$self->args("openid.$_")} @signed_fields;
# Auth 2.0 requires certain keys to be signed.
if ($self->_message_version >= 2) {
my %unsigned;
# these fields must be signed unconditionally
foreach my $f (qw/op_endpoint return_to response_nonce assoc_handle/) {
$unsigned{$f}++ unless exists $signed_value{$f};
}
# these fields must be signed if present
foreach my $f (qw/claimed_id identity/) {
$unsigned{$f}++
if $self->args("openid.$f") && !exists $signed_value{$f};
}
if (%unsigned) {
return $self->_fail("unsigned_field", undef, keys %unsigned);
}
}
if ($assoc) {
$self->_debug("verified_identity: verifying with found association");
return $self->_fail("expired_association")
if $assoc->expired;
# verify the token
my $token = join '',map {"$_:$signed_value{$_}\n"} @signed_fields;
utf8::encode($token);
my $good_sig = $assoc->generate_signature($token);
return $self->_fail("signature_mismatch") unless OpenID::util::timing_indep_eq($sig64, $good_sig);
} else {
$self->_debug("verified_identity: verifying using HTTP (dumb mode)");
# didn't find an association. have to do dumb consumer mode
# and check it with a POST
my %post;
my @mkeys;
if ($self->_message_version >= 2
&& (@mkeys = $self->message->all_parameters)) {
# OpenID 2.0: copy *EVERYTHING*, not just signed parameters.
# (XXX: Do we need to copy non "openid." parameters as well?
# For now, assume if provider is sending them, there is a reason)
%post = map {$_ eq 'openid.mode' ? () : ($_, $self->args($_)) } @mkeys;
}
else {
# OpenID 1.1 *OR* legacy client did not provide a proper
# enumerator; in the latter case under 2.0 we have no
# choice but to send a partial (1.1-style)
# check_authentication request and hope for the best.
%post = (
"openid.assoc_handle" => $assoc_handle,
"openid.signed" => $signed,
"openid.sig" => $sig64,
);
if ($self->_message_version >= 2) {
$post{'openid.ns'} = OpenID::util::VERSION_2_NAMESPACE();
}
# and copy in all signed parameters that we don't already have into %post
$post{"openid.$_"} = $signed_value{$_}
foreach grep {!exists $post{"openid.$_"}} @signed_fields;
# if the provider told us our handle as bogus, let's ask in our
# check_authentication mode whether that's true
if (my $ih = $self->message("invalidate_handle")) {
$post{"openid.invalidate_handle"} = $ih;
}
}
$post{"openid.mode"} = "check_authentication";
my $req = HTTP::Request->new(POST => $server);
$req->header("Content-Type" => "application/x-www-form-urlencoded");
$req->content(join("&", map { "$_=" . uri_escape_utf8($post{$_}) } keys %post));
my $ua = $self->ua;
my $res = $ua->request($req);
return $self->_fail("naive_verify_failed_network")
unless $res && $res->is_success;
my $content = $res->content;
my %args = OpenID::util::parse_keyvalue($content);
# delete the handle from our cache
if (my $ih = $args{'invalidate_handle'}) {
Net::OpenID::Association::invalidate_handle($self, $server, $ih);
}
return $self->_fail("naive_verify_failed_return") unless
$args{'is_valid'} eq "true" || # protocol 1.1
$args{'lifetime'} > 0; # DEPRECATED protocol 1.0
}
$self->_debug("verified identity! = $real_ident");
# verified!
return Net::OpenID::VerifiedIdentity->new(
claimed_identity => $claimed_identity,
consumer => $self,
signed_fields => \%signed_value,
);
}
sub supports_consumer_secret { 1; }
sub _get_consumer_secret {
my Net::OpenID::Consumer $self = shift;
my $time = shift;
my $ss;
if (ref $self->{consumer_secret} eq "CODE") {
$ss = $self->{consumer_secret};
} elsif ($self->{consumer_secret}) {
$ss = sub { return $self->{consumer_secret}; };
} else {
Carp::croak("You haven't defined a consumer_secret value or subref.\n");
}
my $sec = $ss->($time);
Carp::croak("Consumer secret too long") if length($sec) > 255;
return $sec;
}
our $nonce_default_delay = 1200;
our $nonce_default_skew = 300;
sub _canonicalize_nonce_options {
my Net::OpenID::Consumer $self = shift;
my $o = shift;
my ($no_check,$ignore_time,$lifetime,$window,$start,$skew,$timecop) =
delete @{$o}{qw(no_check ignore_time lifetime window start skew timecop)};
Carp::croak("Unrecognized nonce_options: ".join(',',keys %$o))
if keys %$o;
return +{ no_check => 1 }
if ($no_check);
return +{ window => 0,
lifetime => ($lifetime && $lifetime > 0 ? $lifetime : 0),
}
if ($ignore_time);
$window =
defined($lifetime) ? $lifetime :
$nonce_default_delay + 2*(defined($skew) && $skew > $nonce_default_skew
? $skew : $nonce_default_skew)
unless (defined($window));
$lifetime = $window
unless (defined($lifetime));
$lifetime = 0 if $lifetime < 0;
$window = 0 if $window < 0;
$skew = $window < 2*$nonce_default_skew ? $window/2 : $nonce_default_skew
unless (defined($skew));
Carp::croak("Unrecognized nonce_options: ".join(',',keys %$o))
if keys %$o;
return
+{
window => $window,
lifetime => $lifetime,
skew => $skew,
defined($start) ? (start => $start) : (),
};
}
# The contract:
# IF the provider adheres to protocol and is properly configured
# which, for our purposes here means
# (1) it sends properly formatted nonces
# that reflect provider clock time and
# (2) provider clock is not skewed from our own by more than
# <skew> (the maximum acceptable)
# AND
# we have a cache that can reliably hold onto entries
# for at least <lifetime> seconds
# THEN we must not accept a duplicate nonce.
#
# Preconditions imply that no message with this nonce will be received
# prior to <nonce_time>-<skew> (i.e., provider clock is running
# maximally fast and there is no transmission delay). If our cache
# start time is prior to this and the lifetime of cache entries is
# long enough, then we can know for certain that it's not a duplicate,
# otherwise we do not and therefore must reject it.
#
# If we detect an instance where preconditions do not hold, there is
# not much we can do: rejecting nonces in this case will not make the
# protocol more secure. As long as the provider's clock is skewed too
# far forward, an attacker will be able to take advantage of it. Best
# we can do is issue warnings, which is the point of 'timecop', but if
# there's no place to send the warnings, then it's a waste of time.
#
sub _nonce_check_succeeds {
my Net::OpenID::Consumer $self = shift;
my ($now, $uri, $nonce) = @_;
my $o = $self->nonce_options;
my $cache = $self->cache;
return 1
if $o->{no_check} || !$cache;
my $cache_key = "nonce:$uri:$nonce";
return $self->_fail('nonce_reused') if ($cache->get($cache_key));
$cache->set($cache_key, 1,
($o->{lifetime} ? ($now + $o->{lifetime}) : ()));
return 1
unless $o->{window} || $o->{start};
# parse RFC3336 timestamp restricted as per 10.1
my ($year,$mon,$day,$hour,$min,$sec) =
$nonce =~ m/^([0-9]{4})-([0-9]{2})-([0-9]{2})T([0-9]{2}):([0-9]{2}):([0-9]{2})Z/
or return $self->_fail('nonce_format');
# $nonce_time is a lower bound on when the nonce could have been
# received according to our clock
my $nonce_time = eval { timegm($sec,$min,$hour,$day,$mon-1,$year) - $o->{skew} };
return $self->_fail('nonce_format') if $@;
# nonces from the future indicate misconfigured providers
# that we can do nothing about except give warnings
return !$o->{timecop} || $self->_fail('nonce_future')
if ($now < $nonce_time);
# the check that matters
return $self->_fail('nonce_stale')
if ($o->{window} && $nonce_time < $now - $o->{window})
|| ($o->{start} && $nonce_time < $o->{start});
# win
return 1;
}
1;
__END__
=head1 NAME
Net::OpenID::Consumer - Library for consumers of OpenID identities
=head1 VERSION
version 1.15
=head1 SYNOPSIS
use Net::OpenID::Consumer;
my $csr = Net::OpenID::Consumer->new(
ua => LWPx::ParanoidAgent->new,
cache => Cache::File->new( cache_root => '/tmp/mycache' ),
args => $cgi,
consumer_secret => ...,
required_root => "http://site.example.com/",
assoc_options => [
max_encrypt => 1,
session_no_encrypt_https => 1,
],
);
# Say a user enters "bradfitz.com" as his/her identity. The first
# step is to perform discovery, i.e., fetch that page, parse it,
# find out the actual identity provider and other useful information,
# which gets encapsulated in a Net::OpenID::ClaimedIdentity object:
my $claimed_identity = $csr->claimed_identity("bradfitz.com");
unless ($claimed_identity) {
die "not actually an openid? " . $csr->err;
}
# We can then launch the actual authentication of this identity.
# The first step is to redirect the user to the appropriate URL at
# the identity provider. This URL is constructed as follows:
#
my $check_url = $claimed_identity->check_url(
return_to => "http://example.com/openid-check.app?yourarg=val",
trust_root => "http://example.com/",
# to do a "checkid_setup mode" request, in which the user can
# interact with the provider, e.g., so that the user can sign in
# there if s/he has not done so already, you will need this,
delayed_return => 1
# otherwise, this will be a "check_immediate mode" request, the
# provider will have to immediately return some kind of answer
# without interaction
);
# Once you redirect the user to $check_url, the provider should
# eventually redirect back, at which point you need some kind of
# handler at openid-check.app to deal with that response.
# You can either use the callback-based API (recommended)...
#
$csr->handle_server_response(
not_openid => sub {
die "Not an OpenID message";
},
setup_needed => sub {
if ($csr->message->protocol_version >= 2) {
# (OpenID 2) retry request in checkid_setup mode (above)
}
else {
# (OpenID 1) redirect user to $csr->user_setup_url
}
},
cancelled => sub {
# User hit cancel; restore application state prior to check_url
},
verified => sub {
my ($vident) = @_;
my $verified_url = $vident->url;
print "You are $verified_url !";
},
error => sub {
my ($errcode,$errtext) = @_;
die("Error validating identity: $errcode: $errcode");
},
);
# ... or handle the various cases yourself
#
unless ($csr->is_server_response) {
die "Not an OpenID message";
} elsif ($csr->setup_needed) {
# (OpenID 2) retry request in checkid_setup mode
# (OpenID 1) redirect/link/popup user to $csr->user_setup_url
} elsif ($csr->user_cancel) {
# User hit cancel; restore application state prior to check_url
} elsif (my $vident = $csr->verified_identity) {
my $verified_url = $vident->url;
print "You are $verified_url !";
} else {
die "Error validating identity: " . $csr->err;
}
=head1 DESCRIPTION
This is the Perl API for (the consumer half of) OpenID, a distributed
identity system based on proving you own a URL, which is then your
identity. More information is available at:
http://openid.net/
=head1 CONSTRUCTOR
=over 4
=item B<new>
my $csr = Net::OpenID::Consumer->new( %options );
The following option names are recognized:
C<ua>,
C<cache>,
C<args>,
C<consumer_secret>,
C<minimum_version>,
C<required_root>,
C<assoc_options>, and
C<nonce_options>
in the constructor.
In each case the option value is treated exactly as the argument
to the corresponding method described below under L<Configuration|/Configuration>.
=back
=head1 METHODS
=head2 State
=over 4
=item $csr->B<message>($key)
Returns the value for the given key/field from the OpenID protocol
message contained in the request URL parameters (i.e., the value for
the URL parameter C<openid.$key>).
This can only be used to obtain core OpenID fields not extension fields.
Calling this method without a C<$key> argument returns a
L<Net::OpenID::IndirectMessage|Net::OpenID::IndirectMessage>
object representing the protocol message, at which point the
various object methods are available, including
$csr->message->protocol_version
$csr->message->has_ext
$csr->message->get_ext
Returns undef in either case if no URL parameters have been supplied
(i.e., because B<args>() has not been initialized) or if the request
is not an actual OpenID message.
=item $csr->B<err>
Returns the last error, in form "errcode: errtext",
as set by the various handlers below.
=item $csr->B<errcode>
Returns the last error code.
See L<Error Codes|/ERROR CODES> below.
=item $csr->B<errtext>
Returns the last error text.
=item $csr->B<json_err>
Returns the last error code/text in JSON format.
=back
=head2 Configuration
=over 4
=item $csr->B<ua>($user_agent)
=item $csr->B<ua>
Getter/setter for the L<LWP::UserAgent|LWP::UserAgent> (or subclass)
instance which will be used when direct HTTP requests to a provider are needed.
It's highly recommended that you use
L<LWPx::ParanoidAgent|LWPx::ParanoidAgent>, or at least read its
documentation so you're aware of why you should care.
=item $csr->B<cache>($cache)
=item $csr->B<cache>
Getter/setter for the cache instance which is used for storing fetched
HTML or XRDS pages, keys for associations with identity providers, and
received response_nonce values from positive provider assertions.
The $cache object can be anything that has a -E<gt>get($key) and
-E<gt>set($key,$value[,$expire]) methods. See L<URI::Fetch> for more
information. This cache object is passed to L<URI::Fetch|URI::Fetch> directly.
Setting a cache instance is not absolutely required,
But without it, provider associations will not be possible and
the same pages may be fetched multiple times during discovery.
B<It will also not be possible to check for repetition of the
response_nonce, which may then leave you open to replay attacks.>
=item $csr->B<consumer_secret>($scalar)
=item $csr->B<consumer_secret>($code)
$code = $csr->B<consumer_secret>; ($secret) = $code->($time);
The consumer secret is used to generate self-signed nonces for the
return_to URL, to prevent spoofing.
In the simplest (and least secure) form, you configure a static secret
value with a scalar. If you use this method and change the scalar
value, any outstanding requests from the last 30 seconds or so will fail.
You may also supply a subref that takes one argument, I<$time>,
a unix timestamp and returns a secret.
Your secret may not exceed 255 characters.
For the best protection against replays and login cross-site request
forgery, consumer_secret should additionally depend on something known
to be specific to the client browser instance and not visible to an
attacker. If C<SSH_SESSION_ID> is available, you should use that.
Otherwise you'll need to set a (Secure) cookie on the (HTTPS) page
where the signin form appears in order to establish a pre-login
session, then make sure to change this cookie upon successful login.
=item $csr->B<minimum_version>(2)
=item $csr->B<minimum_version>
Get or set the minimum OpenID protocol version supported. Currently
the only useful value you can set here is 2, which will cause
1.1 identifiers to fail discovery with the error C<protocol_version_incorrect>
and responses from version 1 providers to not be recognized.
In most cases you'll want to allow both 1.1 and 2.0 identifiers,
which is the default. If you want, you can set this property to 1
to make this behavior explicit.
=item $csr->B<args>($ref)
=item $csr->B<args>($param)
=item $csr->B<args>
Can be used in 1 of 3 ways:
=over
=item 1.
Set the object from which URL parameter names and values are to be retrieved:
$csr->args( $reference )
where C<$reference> is either
an unblessed C<HASH> ref,
a C<CODE> ref, or
some kind of "request object" E<mdash> the latter being either a
L<CGI|..::CGI>,
L<Apache|..::Apache>,
L<Apache::Request|Apache::Request>,
L<Apache2::Request|Apache2::Request>, or
L<Plack::Request|Plack::Request> object.
If you pass in a C<CODE> ref, it must,
=over
=item *
given a single parameter name argument, return the corresponding parameter value, I<and>,
=item *
given no arguments at all, return the full list of parameter names from the request.
=back
If you pass in an L<Apache|..::Apache> (mod_perl 1.x interface) object
and this is a POST request, you must I<not> have already called
C<< $r->content >> as this routine will be making said call
itself in order to extract the request parameters.
=item 2.
Get a parameter value:
my $foo = $csr->args("foo");
When given an unblessed scalar, it retrieves the value. It croaks if
you haven't defined a way to get at the parameters.
Most callers should instead use the C<message> method above, which
abstracts away the need to understand OpenID's message serialization.
=item 3.
Get the parameter getter:
my $code = $csr->args;
this being a subref that takes a parameter name and
returns the corresponding value.
Most callers should instead use the C<message> method above with no
arguments, which returns an object from which extension attributes
can be obtained by their documented namespace URI.
=back
=item $csr->B<required_root>($url_prefix)
=item $csr->B<required_root>
Gets or sets the string prefix that, if nonempty, all return_to URLs
must start with. Messages with return_to URLS that don't match will
be considered invalid (spoofed from another site).
=item $csr->B<assoc_options>(...)
=item $csr->B<assoc_options>
Get or sets the hash of parameters that determine how associations
with identity providers will be made. Available options include:
=over 4
=item C<assoc_type>
Association type, (default 'HMAC-SHA1')
=item C<session_type>
Association session type, (default 'DH-SHA1')
=item C<max_encrypt>
(boolean)
Use best encryption available for protocol version
for both session type and association type.
This overrides C<session_type> and C<assoc_type>
=item C<session_no_encrypt_https>
(boolean)
Use an unencrypted session type if the ID provider URL scheme is C<https:>.
This overrides C<max_encrypt> if both are set.
=item C<allow_eavesdropping>
(boolean)
Because it is generally a bad idea, we abort assocations where an
unencrypted session over a non-SSL connection is called for.
However the OpenID 1.1 specification technically allows this,
so if that is what you really want, set this flag true.
Ignored under protocol version 2.
=back
=item $csr->B<nonce_options>(...)
=item $csr->B<nonce_options>
Gets or sets the hash of options for how response_nonce should be checked.
In OpenID 2.0, response_nonce is sent by the identity provider as part
of a positive identity assertion in order to help prevent replay
attacks. In the check_authentication phase, the provider is also
required to not authenticate the same response_nonce twice.
The relying party is strongly encouraged but not required to reject
multiple occurrences of a nonce (which can matter if associations are
in use and there is no check_authentication phase). Relying party may
also choose to reject a nonce on the basis of the timestamp being out
of an acceptable range.
Available options include:
=over
=item C<nocheck>
(boolean)
Skip response_nonce checking entirely.
This overrides all other nonce_options.
C<nocheck> is implied and is the only possibility if $csr->B<cache> is unset.
=item C<lifetime>
(integer)
Cache entries for nonces will expire after this many seconds.
Defaults to the value of C<window>, below.
If C<lifetime> is zero or negative, expiration times will not be set
at all; entries will expire as per the default behavior for your cache
(or you will need to purge them via some separate process).
If your cache implementation ignores the third argument on
$entry->B<set>() calls (see L<Cache::Entry>), then this option
has no effect beyond serving as a default for C<window>.
=item C<ignoretime>
(boolean)
Do not do any checking of timestamps, i.e., only test whether nonce is in
the cache. This overrides all other nonce options except for C<lifetime>
and C<nocheck>
=item C<skew>
(integer)
Number of seconds that a provider clock can be ahead of ours before we
deem it to be misconfigured.
Default skew is 300 (5 minutes) or C<window/2>, if C<window> is
specified and C<window/2> is smaller.
(C<skew> is treated as 0 if set negative, but don't do that).
Misconfiguration of the provider clock means its timestamps are not
reliable, which then means there is no way to know whether or not the
nonce could have been sent before the start of the cache window, which
nullifies any obligation to detect all multiply sent nonces.
Conversely, if proper configuration can be assumed, then the timestamp
value minus C<skew> will be the earliest possible time that we could
have received a previous instance of this response_nonce, and if the
cache is reliable about holding entries from that time forward, then
(and only then) can one be certain that an uncached nonce instance is
indeed the first.
=item C<start>
(integer)
Reject nonces where I<timestamp> minus C<skew> is earlier than C<start>
(absolute seconds; default is zero a.k.a. midnight 1/1/1970 UTC)
If you know the start time of your HTTP server (or your cache server,
if that is separate E<mdash> or the maximum of the start times if you
have multiple cache servers), you should use this option to declare that.
=item C<window>
(integer)
Reject nonces where I<timestamp> minus C<skew> is more than C<window>
seconds ago. Zero or negative values of C<window> are treated as
infinite (i.e., allow everything).
If C<lifetime> is specified, C<window> defaults to that.
If C<lifetime> is not specified, C<window> defaults to 1800 (30 minutes),
adjusted upwards if C<skew> is specified and larger than the default skew.
On general principles, C<window> should be a maximal expected
propagation delay plus twice the C<skew>.
Values between 0 and C<skew> (causing all nonces to be rejected) and
values greater than C<lifetime> (cache may fail to keep all nonces
that are still within the window) are I<not> recommended.
=item C<timecop>
(boolean)
Reject nonces from The Future (i.e., timestamped more than
C<skew> seconds from now).
Note that rejecting future nonces is not required. Nor does it
protect from anything since an attacker can retry the message once it
has expired from the cache but is still within the time interval where
we would not yet I<expect> that it could expire E<mdash> this being
the essential problem with future nonces. It may, however, be useful
to have warnings about misconfigured provider clocks E<mdash> and hence
about this insecurity E<mdash> at the cost of impairing interoperability
(since this rejects messages that are otherwise allowed by the
protocol), hence this option.
=back
In most cases it will be enough to either set C<nocheck> to dispense
with response_nonce checking entirely because some other (better)
method of preventing replay attacks (see B<consumer_secret>) has been
implemented, or use C<lifetime> to declare/set the lifetime of cache
entries for nonces whether because the default lifetime is
unsatisfactory or because the cache implementation is incapable of
setting individual expiration times. All other options should default
reasonably in these cases.
In order for the nonce check to be as reliable/secure as possible
(i.e., that it block all instances of duplicate nonces from properly
configured providers as defined by C<skew>, which is the best we can
do), C<start> must be no earlier than the cache start time and the
cache must be guaranteed to hold nonce entries for at least C<window>
seconds (though, to be sure, if you can tolerate being vulnerable for
the first C<window> seconds of a server run, then you do not need to
set C<start>).
=back
=head2 Performing Discovery
=over
=item $csr->B<claimed_identity>($url)
Given a user-entered $url
(which could be missing http://, or have extra whitespace, etc),
converts it to canonical form,
performs partial discovery to confirm that at least one provider endpoint exists,
and returns a L<Net::OpenID::ClaimedIdentity|Net::OpenID::ClaimedIdentity>
object, or, on failure of any of the above,
returns undef and sets last error ($csr->B<err>).
Note that the identity returned is I<not> verified yet.
It's only who the user claims they are, but they could be lying.
If this method returns undef, an error code will be set.
See L<Error Codes|/ERROR CODES> below.
=back
=head2 Handling Provider Responses
The following routines are for handling a redirected provider response
and assume that, among other things, $csr->B<args> has been properly
populated with the URL parameters.
=over
=item $csr->B<handle_server_response>( %callbacks );
When a request comes in that contains a response from an OpenID provider,
figure out what it means and dispatch to an appropriate callback to handle
the request. This is the callback-based alternative to explicitly calling
the methods below in the correct sequence, and is recommended unless you
need to do something strange.
Anything you return from the selected callback function will be returned
by this method verbatim. This is useful if the caller needs to return
something different in each case.
The available callbacks are:
=over
=item C<not_openid>
the request isn't an OpenID response after all.
=item C<setup_needed>
a checkid_immediate mode request was rejected, indicating that the provider requires user interaction.
=item C<cancelled>
the user cancelled the authentication request from the provider's UI.
=item C<verified ($verified_identity)>
the user's identity has been successfully verified.
A L<Net::OpenID::VerifiedIdentity|Net::OpenID::VerifiedIdentity> object is passed in.
=item C<error ($errcode, $errmsg)>
an error has occured. An error code and message are provided.
See L<Error Codes|/ERROR CODES> below for the meanings of the codes.
=back
For the sake of legacy code we also allow
=over
=item C<setup_required ($setup_url)>
B<[DEPRECATED]> a checkid_immediate mode request was rejected
I<and> $setup_url was provided.
Clients using this callback should be updated to use B<setup_needed>
at the earliest opportunity. Here $setup_url is the same as returned by
$csr->B<user_setup_url>.
=back
=item $csr->B<is_server_response>
Returns true if a set of URL parameters has been supplied (via $csr->B<args>)
and constitutes an actual OpenID protocol message.
=item $csr->B<setup_needed>
Returns true if a checkid_immediate request failed because the provider
requires user interaction. The correct action to take at this point
depends on the OpenID protocol version
(Version 1) Redirect to or otherwise make available a link to
C<$csr>->C<user_setup_url>.
(Version 2) Retry the request in checkid_setup mode; the provider will
then issue redirects as needed.
=over
B<N.B.>: While some providers have been known to supply the C<user_setup_url>
parameter in Version 2 C<setup_needed> responses, you I<cannot> rely on this,
and, moreover, since the OpenID 2.0 specification has nothing to say about
the meaning of such a parameter, you cannot rely on it meaning anything
in particular even if it is supplied.
=back
=item $csr->B<user_setup_url>( [ %opts ] )
(Version 1 only) Returns the URL the user must return to in order to
login, setup trust, or do whatever the identity provider needs them to
do in order to make the identity assertion which they previously
initiated by entering their claimed identity URL.
=over
B<N.B.>: Checking whether C<user_setup_url> is set in order to determine
whether a checkid_immediate request failed is DEPRECATED and will fail
under OpenID 2.0. Use C<setup_needed()> instead.
=back
The base URL that this function returns can be modified by using the
following options in %opts:
=over
=item C<post_grant>
What you're asking the identity provider to do with the user after they
setup trust. Can be either C<return> or C<close> to return the user
back to the return_to URL, or close the browser window with
JavaScript. If you don't specify, the behavior is undefined (probably
the user gets a dead-end page with a link back to the return_to URL).
In any case, the identity provider can do whatever it wants, so don't
depend on this.
=back
=item $csr->B<user_cancel>
Returns true if the user declined to share their identity, false
otherwise. (This function is literally one line: returns true if
"openid.mode" eq "cancel")
It's then your job to restore your app to where it was prior to
redirecting them off to the user_setup_url, using the other query
parameters that you'd sent along in your return_to URL.
=item $csr->B<verified_identity>( [ %opts ] )
Returns a Net::OpenID::VerifiedIdentity object,
or returns undef and sets last error ($csr->B<err>).
Verification includes double-checking the reported identity URL
declares the identity provider, verifying the signature, etc.
The options in %opts may contain:
=over
=item C<required_root>
Sets the required_root just for this request. Values returns to its
previous value afterwards.
=back
If this method returns undef, an error code will be set.
See L<Error Codes|/ERROR CODES> below.
=back
=head1 ERROR CODES
This is the complete list of error codes that can be set. Errors marked with (C) are set by B<claimed_identity>. Other errors occur during handling of provider responses and can be set by B<args> (A), B<verified_identity> (V), and B<user_setup_url> (S), all of which can show up in the C<error> callback for B<handle_server_response>.
=over
=over
=item C<provider_error>
(A) The protocol message is a (2.0) error mode (i.e., C<openid.mode = 'error'>) message, typically used for provider-specific error reponses. Use $csr->B<message> to get at the C<contact> and C<reference> fields.
=item C<empty_url>
(C) Tried to do discovery on an empty or all-whitespace string.
=item C<bogus_url>
(C) Tried to do discovery on a non-http:/https: URL.
=item C<protocol_version_incorrect>
(C) None of the ID providers found support even the minimum protocol version ($csr->B<minimum_version>)
=item C<no_identity_server>
(CV) Tried to do discovery on a URL that does not seem to have any providers at all.
=item C<bad_mode>
(SV) The C<openid.mode> was expected to be C<id_res> (positive assertion or, in version 1, checkid_immediate failed).
=item C<no_identity>
(V) The C<openid.identity> parameter is missing.
=item C<no_sig>
(V) The C<openid.sig> parameter is missing.
=item C<no_return_to>
(V) The C<openid.return_to> parameter is missing
=item C<bogus_return_to>
(V) The C<return_to> URL does not match $csr->B<required_root>
=item C<nonce_missing>
(V) The C<openid.response_nonce> parameter is missing.
=item C<nonce_reused>
(V) A previous assertion from this provider used this response_nonce already. Someone may be attempting a replay attack.
=item C<nonce_format>
(V) Either the response_nonce timestamp was not in the correct format (e.g., tried to have fractional seconds or not UTC) or one of the components was out of range (e.g., month = 13).
=item C<nonce_future>
(V) C<timecop> was set and we got a response_nonce that was more than C<skew> seconds into the future.
=item C<nonce_stale>
(V) We got a response_nonce that was either prior to the start time or more than window seconds ago.
=item C<time_expired>
(V) The return_to signature time (C<oic.time>) is from too long ago.
=item C<time_in_future>
(V) The return_to signature time (C<oic.time>) is too far into the future.
=item C<time_bad_sig>
(V) The HMAC of the return_to signature (C<oic.time>) is not what it should be.
=item C<server_not_allowed>
(V) None of the provider endpoints found for the given ID match the server specified by the C<openid.op_endpoint> parameter (OpenID 2 only).
=item C<unexpected_url_redirect>
(V) Discovery for the given ID ended up at the wrong place
=item C<bogus_delegation>
(V) Asserted identity (C<openid.identity>) does not match claimed_id or local_id/delegate.
=item C<unsigned_field>
(V) In OpenID 2.0, C<openid.op_endpoint>, C<openid.return_to>, C<openid.response_nonce>, and C<openid.assoc_handle> must always be signed, while C<openid.claimed_id> and C<openid.identity> must be signed if present.
=item C<expired_association>
(V) C<openid.assoc_handle> is for an association that has expired.
=item C<signature_mismatch>
(V) An attempt to confirm the positive assertion using the association given by C<openid.assoc_handle> failed; the signature is not what it should be.
=item C<naive_verify_failed_network>
(V) An attempt to confirm the positive assertion via direct contact (check_authentication) with the provider failed with no response or a bad status code (!= 200).
=item C<naive_verify_failed_return>
(V) An attempt to confirm a positive assertion via direct contact (check_authentication) received an explicitly negative response (C<openid.is_valid = FALSE>).
=back
=back
=head1 PROTOCOL VARIANCES
XRI-based identities are not supported.
Meanwhile, here are answers to the security profile questions from L<section 15.6 of the OpenID 2.0 specification|http://openid.net/specs/openid-authentication-2_0.html#anchor47> that are relevant to the Consumer/Relying-Party:
=over
=item 1.
I<Are wildcards allowed in realms?>
B<Yes.>
=item 2.
N/A.
=item 3.
I<Types of claimed identifiers accepted.>
B<HTTP or HTTPS>
=item 4.
I<Are self-issued certificates allowed for authentication?>
B<Depends entirely on the user agent (C<ua>) supplied. L<LWP::UserAgent|LWP::UserAgent>, as of version 6.0, can be configured to only accept connections to sites with certificates deriving from a set of trusted roots.>
=item 5.
I<Must the XRDS file be signed?> B<No.>
=item 6.
I<Must the XRDS file be retrieved over secure channel?> B<No.>
=item 7.
I<What types of session types can be used when creating associations?> B<Any of C<no-encryption>,C<DH-SHA1>,C<DH-SHA256>>
=item 8.
N/A.
=item 9.
N/A.
=item 10.
I<Must the association request take place over a secure channel?> B<If the session type is C<no-encryption>, then Yes for version 2.0 providers and likewise for version 1.1 providers if C<allow_eavesdropping> is not set, otherwise No.>
=back
=head1 COPYRIGHT
This module is Copyright (c) 2005 Brad Fitzpatrick.
All rights reserved.
You may distribute under the terms of either the GNU General Public
License or the Artistic License, as specified in the Perl README file.
If you need more liberal licensing terms, please contact the
maintainer.
=head1 WARRANTY
This is free software. IT COMES WITHOUT WARRANTY OF ANY KIND.
=head1 MAILING LIST
The Net::OpenID family of modules has a mailing list powered
by Google Groups. For more information, see
L<http://groups.google.com/group/openid-perl>.
=head1 SEE ALSO
OpenID website: L<http://openid.net/>
L<Net::OpenID::ClaimedIdentity> -- part of this module
L<Net::OpenID::VerifiedIdentity> -- part of this module
L<Net::OpenID::Server> -- another module, for implementing an OpenID identity provider/server
=head1 AUTHORS
Brad Fitzpatrick <brad@danga.com>
Tatsuhiko Miyagawa <miyagawa@sixapart.com>
Martin Atkins <mart@degeneration.co.uk>
Robert Norris <rob@eatenbyagrue.org>
Roger Crew <crew@cs.stanford.edu>
|