[836a32]: caps / src / nsScriptSecurityManager.cpp  Maximize  Restore  History

Download this file

2916 lines (2510 with data), 96.9 kB

   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
2045
2046
2047
2048
2049
2050
2051
2052
2053
2054
2055
2056
2057
2058
2059
2060
2061
2062
2063
2064
2065
2066
2067
2068
2069
2070
2071
2072
2073
2074
2075
2076
2077
2078
2079
2080
2081
2082
2083
2084
2085
2086
2087
2088
2089
2090
2091
2092
2093
2094
2095
2096
2097
2098
2099
2100
2101
2102
2103
2104
2105
2106
2107
2108
2109
2110
2111
2112
2113
2114
2115
2116
2117
2118
2119
2120
2121
2122
2123
2124
2125
2126
2127
2128
2129
2130
2131
2132
2133
2134
2135
2136
2137
2138
2139
2140
2141
2142
2143
2144
2145
2146
2147
2148
2149
2150
2151
2152
2153
2154
2155
2156
2157
2158
2159
2160
2161
2162
2163
2164
2165
2166
2167
2168
2169
2170
2171
2172
2173
2174
2175
2176
2177
2178
2179
2180
2181
2182
2183
2184
2185
2186
2187
2188
2189
2190
2191
2192
2193
2194
2195
2196
2197
2198
2199
2200
2201
2202
2203
2204
2205
2206
2207
2208
2209
2210
2211
2212
2213
2214
2215
2216
2217
2218
2219
2220
2221
2222
2223
2224
2225
2226
2227
2228
2229
2230
2231
2232
2233
2234
2235
2236
2237
2238
2239
2240
2241
2242
2243
2244
2245
2246
2247
2248
2249
2250
2251
2252
2253
2254
2255
2256
2257
2258
2259
2260
2261
2262
2263
2264
2265
2266
2267
2268
2269
2270
2271
2272
2273
2274
2275
2276
2277
2278
2279
2280
2281
2282
2283
2284
2285
2286
2287
2288
2289
2290
2291
2292
2293
2294
2295
2296
2297
2298
2299
2300
2301
2302
2303
2304
2305
2306
2307
2308
2309
2310
2311
2312
2313
2314
2315
2316
2317
2318
2319
2320
2321
2322
2323
2324
2325
2326
2327
2328
2329
2330
2331
2332
2333
2334
2335
2336
2337
2338
2339
2340
2341
2342
2343
2344
2345
2346
2347
2348
2349
2350
2351
2352
2353
2354
2355
2356
2357
2358
2359
2360
2361
2362
2363
2364
2365
2366
2367
2368
2369
2370
2371
2372
2373
2374
2375
2376
2377
2378
2379
2380
2381
2382
2383
2384
2385
2386
2387
2388
2389
2390
2391
2392
2393
2394
2395
2396
2397
2398
2399
2400
2401
2402
2403
2404
2405
2406
2407
2408
2409
2410
2411
2412
2413
2414
2415
2416
2417
2418
2419
2420
2421
2422
2423
2424
2425
2426
2427
2428
2429
2430
2431
2432
2433
2434
2435
2436
2437
2438
2439
2440
2441
2442
2443
2444
2445
2446
2447
2448
2449
2450
2451
2452
2453
2454
2455
2456
2457
2458
2459
2460
2461
2462
2463
2464
2465
2466
2467
2468
2469
2470
2471
2472
2473
2474
2475
2476
2477
2478
2479
2480
2481
2482
2483
2484
2485
2486
2487
2488
2489
2490
2491
2492
2493
2494
2495
2496
2497
2498
2499
2500
2501
2502
2503
2504
2505
2506
2507
2508
2509
2510
2511
2512
2513
2514
2515
2516
2517
2518
2519
2520
2521
2522
2523
2524
2525
2526
2527
2528
2529
2530
2531
2532
2533
2534
2535
2536
2537
2538
2539
2540
2541
2542
2543
2544
2545
2546
2547
2548
2549
2550
2551
2552
2553
2554
2555
2556
2557
2558
2559
2560
2561
2562
2563
2564
2565
2566
2567
2568
2569
2570
2571
2572
2573
2574
2575
2576
2577
2578
2579
2580
2581
2582
2583
2584
2585
2586
2587
2588
2589
2590
2591
2592
2593
2594
2595
2596
2597
2598
2599
2600
2601
2602
2603
2604
2605
2606
2607
2608
2609
2610
2611
2612
2613
2614
2615
2616
2617
2618
2619
2620
2621
2622
2623
2624
2625
2626
2627
2628
2629
2630
2631
2632
2633
2634
2635
2636
2637
2638
2639
2640
2641
2642
2643
2644
2645
2646
2647
2648
2649
2650
2651
2652
2653
2654
2655
2656
2657
2658
2659
2660
2661
2662
2663
2664
2665
2666
2667
2668
2669
2670
2671
2672
2673
2674
2675
2676
2677
2678
2679
2680
2681
2682
2683
2684
2685
2686
2687
2688
2689
2690
2691
2692
2693
2694
2695
2696
2697
2698
2699
2700
2701
2702
2703
2704
2705
2706
2707
2708
2709
2710
2711
2712
2713
2714
2715
2716
2717
2718
2719
2720
2721
2722
2723
2724
2725
2726
2727
2728
2729
2730
2731
2732
2733
2734
2735
2736
2737
2738
2739
2740
2741
2742
2743
2744
2745
2746
2747
2748
2749
2750
2751
2752
2753
2754
2755
2756
2757
2758
2759
2760
2761
2762
2763
2764
2765
2766
2767
2768
2769
2770
2771
2772
2773
2774
2775
2776
2777
2778
2779
2780
2781
2782
2783
2784
2785
2786
2787
2788
2789
2790
2791
2792
2793
2794
2795
2796
2797
2798
2799
2800
2801
2802
2803
2804
2805
2806
2807
2808
2809
2810
2811
2812
2813
2814
2815
2816
2817
2818
2819
2820
2821
2822
2823
2824
2825
2826
2827
2828
2829
2830
2831
2832
2833
2834
2835
2836
2837
2838
2839
2840
2841
2842
2843
2844
2845
2846
2847
2848
2849
2850
2851
2852
2853
2854
2855
2856
2857
2858
2859
2860
2861
2862
2863
2864
2865
2866
2867
2868
2869
2870
2871
2872
2873
2874
2875
2876
2877
2878
2879
2880
2881
2882
2883
2884
2885
2886
2887
2888
2889
2890
2891
2892
2893
2894
2895
2896
2897
2898
2899
2900
2901
2902
2903
2904
2905
2906
2907
2908
2909
2910
2911
2912
2913
2914
2915
/* -*- Mode: C++; tab-width: 8; indent-tabs-mode: nil; c-basic-offset: 4 -*- */
/* vim: set ts=4 et sw=4 tw=80: */
/* This Source Code Form is subject to the terms of the Mozilla Public
* License, v. 2.0. If a copy of the MPL was not distributed with this
* file, You can obtain one at http://mozilla.org/MPL/2.0/. */
#include "mozilla/Util.h"
#include "xpcprivate.h"
#include "XPCWrapper.h"
#include "nsScriptSecurityManager.h"
#include "nsIServiceManager.h"
#include "nsIScriptObjectPrincipal.h"
#include "nsIScriptContext.h"
#include "nsIURL.h"
#include "nsINestedURI.h"
#include "nspr.h"
#include "nsJSPrincipals.h"
#include "nsSystemPrincipal.h"
#include "nsPrincipal.h"
#include "nsNullPrincipal.h"
#include "nsXPIDLString.h"
#include "nsCRT.h"
#include "nsCRTGlue.h"
#include "nsError.h"
#include "nsDOMCID.h"
#include "jsdbgapi.h"
#include "nsIXPConnect.h"
#include "nsIXPCSecurityManager.h"
#include "nsTextFormatter.h"
#include "nsIStringBundle.h"
#include "nsNetUtil.h"
#include "nsIProperties.h"
#include "nsDirectoryServiceDefs.h"
#include "nsIFile.h"
#include "nsIFileURL.h"
#include "nsIZipReader.h"
#include "nsIXPConnect.h"
#include "nsIScriptGlobalObject.h"
#include "nsPIDOMWindow.h"
#include "nsIDocShell.h"
#include "nsIPrompt.h"
#include "nsIWindowWatcher.h"
#include "nsIConsoleService.h"
#include "nsISecurityCheckedComponent.h"
#include "nsIJSRuntimeService.h"
#include "nsIObserverService.h"
#include "nsIContent.h"
#include "nsAutoPtr.h"
#include "nsDOMJSUtils.h"
#include "nsAboutProtocolUtils.h"
#include "nsIClassInfo.h"
#include "nsIURIFixup.h"
#include "nsCDefaultURIFixup.h"
#include "nsIChromeRegistry.h"
#include "nsIContentSecurityPolicy.h"
#include "nsIAsyncVerifyRedirectCallback.h"
#include "mozilla/Preferences.h"
#include "mozilla/dom/BindingUtils.h"
#include "mozilla/StandardInteger.h"
#include "mozilla/ClearOnShutdown.h"
#include "mozilla/StaticPtr.h"
#include "nsContentUtils.h"
#include "nsCxPusher.h"
// This should be probably defined on some other place... but I couldn't find it
#define WEBAPPS_PERM_NAME "webapps-manage"
using namespace mozilla;
using namespace mozilla::dom;
static NS_DEFINE_CID(kZipReaderCID, NS_ZIPREADER_CID);
nsIIOService *nsScriptSecurityManager::sIOService = nullptr;
nsIStringBundle *nsScriptSecurityManager::sStrBundle = nullptr;
JSRuntime *nsScriptSecurityManager::sRuntime = 0;
bool nsScriptSecurityManager::sStrictFileOriginPolicy = true;
bool
nsScriptSecurityManager::SubjectIsPrivileged()
{
JSContext *cx = GetCurrentJSContext();
if (cx && xpc::IsUniversalXPConnectEnabled(cx))
return true;
bool isSystem = false;
return NS_SUCCEEDED(SubjectPrincipalIsSystem(&isSystem)) && isSystem;
}
///////////////////////////
// Convenience Functions //
///////////////////////////
// Result of this function should not be freed.
static inline const PRUnichar *
IDToString(JSContext *cx, jsid id_)
{
JS::RootedId id(cx, id_);
if (JSID_IS_STRING(id))
return JS_GetInternedStringChars(JSID_TO_STRING(id));
JS::Value idval;
if (!JS_IdToValue(cx, id, &idval))
return nullptr;
JSString *str = JS_ValueToString(cx, idval);
if(!str)
return nullptr;
return JS_GetStringCharsZ(cx, str);
}
class nsAutoInPrincipalDomainOriginSetter {
public:
nsAutoInPrincipalDomainOriginSetter() {
++sInPrincipalDomainOrigin;
}
~nsAutoInPrincipalDomainOriginSetter() {
--sInPrincipalDomainOrigin;
}
static uint32_t sInPrincipalDomainOrigin;
};
uint32_t nsAutoInPrincipalDomainOriginSetter::sInPrincipalDomainOrigin;
static
nsresult
GetOriginFromURI(nsIURI* aURI, nsACString& aOrigin)
{
if (nsAutoInPrincipalDomainOriginSetter::sInPrincipalDomainOrigin > 1) {
// Allow a single recursive call to GetPrincipalDomainOrigin, since that
// might be happening on a different principal from the first call. But
// after that, cut off the recursion; it just indicates that something
// we're doing in this method causes us to reenter a security check here.
return NS_ERROR_NOT_AVAILABLE;
}
nsAutoInPrincipalDomainOriginSetter autoSetter;
nsCOMPtr<nsIURI> uri = NS_GetInnermostURI(aURI);
NS_ENSURE_TRUE(uri, NS_ERROR_UNEXPECTED);
nsAutoCString hostPort;
nsresult rv = uri->GetHostPort(hostPort);
if (NS_SUCCEEDED(rv)) {
nsAutoCString scheme;
rv = uri->GetScheme(scheme);
NS_ENSURE_SUCCESS(rv, rv);
aOrigin = scheme + NS_LITERAL_CSTRING("://") + hostPort;
}
else {
// Some URIs (e.g., nsSimpleURI) don't support host. Just
// get the full spec.
rv = uri->GetSpec(aOrigin);
NS_ENSURE_SUCCESS(rv, rv);
}
return NS_OK;
}
static
nsresult
GetPrincipalDomainOrigin(nsIPrincipal* aPrincipal,
nsACString& aOrigin)
{
nsCOMPtr<nsIURI> uri;
aPrincipal->GetDomain(getter_AddRefs(uri));
if (!uri) {
aPrincipal->GetURI(getter_AddRefs(uri));
}
NS_ENSURE_TRUE(uri, NS_ERROR_UNEXPECTED);
return GetOriginFromURI(uri, aOrigin);
}
static nsIScriptContext *
GetScriptContext(JSContext *cx)
{
return GetScriptContextFromJSContext(cx);
}
inline void SetPendingException(JSContext *cx, const char *aMsg)
{
JS_ReportError(cx, "%s", aMsg);
}
inline void SetPendingException(JSContext *cx, const PRUnichar *aMsg)
{
JS_ReportError(cx, "%hs", aMsg);
}
// DomainPolicy members
uint32_t DomainPolicy::sGeneration = 0;
// Helper class to get stuff from the ClassInfo and not waste extra time with
// virtual method calls for things it has already gotten
class ClassInfoData
{
public:
ClassInfoData(nsIClassInfo *aClassInfo, const char *aName)
: mClassInfo(aClassInfo),
mName(const_cast<char *>(aName)),
mDidGetFlags(false),
mMustFreeName(false)
{
}
~ClassInfoData()
{
if (mMustFreeName)
nsMemory::Free(mName);
}
uint32_t GetFlags()
{
if (!mDidGetFlags) {
if (mClassInfo) {
nsresult rv = mClassInfo->GetFlags(&mFlags);
if (NS_FAILED(rv)) {
mFlags = 0;
}
} else {
mFlags = 0;
}
mDidGetFlags = true;
}
return mFlags;
}
bool IsDOMClass()
{
return !!(GetFlags() & nsIClassInfo::DOM_OBJECT);
}
const char* GetName()
{
if (!mName) {
if (mClassInfo) {
mClassInfo->GetClassDescription(&mName);
}
if (mName) {
mMustFreeName = true;
} else {
mName = const_cast<char *>("UnnamedClass");
}
}
return mName;
}
private:
nsIClassInfo *mClassInfo; // WEAK
uint32_t mFlags;
char *mName;
bool mDidGetFlags;
bool mMustFreeName;
};
JSContext *
nsScriptSecurityManager::GetCurrentJSContext()
{
// Get JSContext from stack.
return nsXPConnect::XPConnect()->GetCurrentJSContext();
}
JSContext *
nsScriptSecurityManager::GetSafeJSContext()
{
// Get JSContext from stack.
return nsXPConnect::XPConnect()->GetSafeJSContext();
}
/* static */
bool
nsScriptSecurityManager::SecurityCompareURIs(nsIURI* aSourceURI,
nsIURI* aTargetURI)
{
return NS_SecurityCompareURIs(aSourceURI, aTargetURI, sStrictFileOriginPolicy);
}
// SecurityHashURI is consistent with SecurityCompareURIs because NS_SecurityHashURI
// is consistent with NS_SecurityCompareURIs. See nsNetUtil.h.
uint32_t
nsScriptSecurityManager::SecurityHashURI(nsIURI* aURI)
{
return NS_SecurityHashURI(aURI);
}
NS_IMETHODIMP
nsScriptSecurityManager::GetChannelPrincipal(nsIChannel* aChannel,
nsIPrincipal** aPrincipal)
{
NS_PRECONDITION(aChannel, "Must have channel!");
nsCOMPtr<nsISupports> owner;
aChannel->GetOwner(getter_AddRefs(owner));
if (owner) {
CallQueryInterface(owner, aPrincipal);
if (*aPrincipal) {
return NS_OK;
}
}
// OK, get the principal from the URI. Make sure this does the same thing
// as nsDocument::Reset and XULDocument::StartDocumentLoad.
nsCOMPtr<nsIURI> uri;
nsresult rv = NS_GetFinalChannelURI(aChannel, getter_AddRefs(uri));
NS_ENSURE_SUCCESS(rv, rv);
nsCOMPtr<nsIDocShell> docShell;
NS_QueryNotificationCallbacks(aChannel, docShell);
if (docShell) {
return GetDocShellCodebasePrincipal(uri, docShell, aPrincipal);
}
return GetCodebasePrincipalInternal(uri, UNKNOWN_APP_ID,
/* isInBrowserElement */ false, aPrincipal);
}
NS_IMETHODIMP
nsScriptSecurityManager::IsSystemPrincipal(nsIPrincipal* aPrincipal,
bool* aIsSystem)
{
*aIsSystem = (aPrincipal == mSystemPrincipal);
return NS_OK;
}
NS_IMETHODIMP_(nsIPrincipal *)
nsScriptSecurityManager::GetCxSubjectPrincipal(JSContext *cx)
{
NS_ASSERTION(cx == GetCurrentJSContext(),
"Uh, cx is not the current JS context!");
nsresult rv = NS_ERROR_FAILURE;
nsIPrincipal *principal = GetSubjectPrincipal(cx, &rv);
if (NS_FAILED(rv))
return nullptr;
return principal;
}
////////////////////
// Policy Storage //
////////////////////
// Table of security levels
static bool
DeleteCapability(nsHashKey *aKey, void *aData, void* closure)
{
NS_Free(aData);
return true;
}
//-- Per-Domain Policy - applies to one or more protocols or hosts
struct DomainEntry
{
DomainEntry(const char* aOrigin,
DomainPolicy* aDomainPolicy) : mOrigin(aOrigin),
mDomainPolicy(aDomainPolicy),
mNext(nullptr)
{
mDomainPolicy->Hold();
}
~DomainEntry()
{
mDomainPolicy->Drop();
}
bool Matches(const char *anOrigin)
{
int len = strlen(anOrigin);
int thisLen = mOrigin.Length();
if (len < thisLen)
return false;
if (mOrigin.RFindChar(':', thisLen-1, 1) != -1)
//-- Policy applies to all URLs of this scheme, compare scheme only
return mOrigin.EqualsIgnoreCase(anOrigin, thisLen);
//-- Policy applies to a particular host; compare domains
if (!mOrigin.Equals(anOrigin + (len - thisLen)))
return false;
if (len == thisLen)
return true;
char charBefore = anOrigin[len-thisLen-1];
return (charBefore == '.' || charBefore == ':' || charBefore == '/');
}
nsCString mOrigin;
DomainPolicy* mDomainPolicy;
DomainEntry* mNext;
};
static bool
DeleteDomainEntry(nsHashKey *aKey, void *aData, void* closure)
{
DomainEntry *entry = (DomainEntry*) aData;
do
{
DomainEntry *next = entry->mNext;
delete entry;
entry = next;
} while (entry);
return true;
}
/////////////////////////////
// nsScriptSecurityManager //
/////////////////////////////
////////////////////////////////////
// Methods implementing ISupports //
////////////////////////////////////
NS_IMPL_ISUPPORTS4(nsScriptSecurityManager,
nsIScriptSecurityManager,
nsIXPCSecurityManager,
nsIChannelEventSink,
nsIObserver)
///////////////////////////////////////////////////
// Methods implementing nsIScriptSecurityManager //
///////////////////////////////////////////////////
///////////////// Security Checks /////////////////
JSBool
nsScriptSecurityManager::ContentSecurityPolicyPermitsJSAction(JSContext *cx)
{
// Get the security manager
nsScriptSecurityManager *ssm =
nsScriptSecurityManager::GetScriptSecurityManager();
NS_ASSERTION(ssm, "Failed to get security manager service");
if (!ssm)
return JS_FALSE;
nsresult rv;
nsIPrincipal* subjectPrincipal = ssm->GetSubjectPrincipal(cx, &rv);
NS_ASSERTION(NS_SUCCEEDED(rv), "CSP: Failed to get nsIPrincipal from js context");
if (NS_FAILED(rv))
return JS_FALSE; // Not just absence of principal, but failure.
if (!subjectPrincipal)
return JS_TRUE;
nsCOMPtr<nsIContentSecurityPolicy> csp;
rv = subjectPrincipal->GetCsp(getter_AddRefs(csp));
NS_ASSERTION(NS_SUCCEEDED(rv), "CSP: Failed to get CSP from principal.");
// don't do anything unless there's a CSP
if (!csp)
return JS_TRUE;
bool evalOK = true;
bool reportViolation = false;
rv = csp->GetAllowsEval(&reportViolation, &evalOK);
if (NS_FAILED(rv))
{
NS_WARNING("CSP: failed to get allowsEval");
return JS_TRUE; // fail open to not break sites.
}
if (reportViolation) {
nsAutoString fileName;
unsigned lineNum = 0;
NS_NAMED_LITERAL_STRING(scriptSample, "call to eval() or related function blocked by CSP");
JSScript *script;
if (JS_DescribeScriptedCaller(cx, &script, &lineNum)) {
if (const char *file = JS_GetScriptFilename(cx, script)) {
CopyUTF8toUTF16(nsDependentCString(file), fileName);
}
}
csp->LogViolationDetails(nsIContentSecurityPolicy::VIOLATION_TYPE_EVAL,
fileName,
scriptSample,
lineNum);
}
return evalOK;
}
JSBool
nsScriptSecurityManager::CheckObjectAccess(JSContext *cx, JSHandleObject obj,
JSHandleId id, JSAccessMode mode,
JSMutableHandleValue vp)
{
// Get the security manager
nsScriptSecurityManager *ssm =
nsScriptSecurityManager::GetScriptSecurityManager();
NS_ASSERTION(ssm, "Failed to get security manager service");
if (!ssm)
return JS_FALSE;
// Get the object being accessed. We protect these cases:
// 1. The Function.prototype.caller property's value, which might lead
// an attacker up a call-stack to a function or another object from
// a different trust domain.
// 2. A user-defined getter or setter function accessible on another
// trust domain's window or document object.
// vp can be a primitive, in that case, we use obj as the target
// object.
JSObject* target = JSVAL_IS_PRIMITIVE(vp) ? obj : JSVAL_TO_OBJECT(vp);
// Do the same-origin check -- this sets a JS exception if the check fails.
// Pass the parent object's class name, as we have no class-info for it.
nsresult rv =
ssm->CheckPropertyAccess(cx, target, js::GetObjectClass(obj)->name, id,
(mode & JSACC_WRITE) ?
(int32_t)nsIXPCSecurityManager::ACCESS_SET_PROPERTY :
(int32_t)nsIXPCSecurityManager::ACCESS_GET_PROPERTY);
if (NS_FAILED(rv))
return JS_FALSE; // Security check failed (XXX was an error reported?)
return JS_TRUE;
}
NS_IMETHODIMP
nsScriptSecurityManager::CheckPropertyAccess(JSContext* cx,
JSObject* aJSObject,
const char* aClassName,
jsid aProperty,
uint32_t aAction)
{
return CheckPropertyAccessImpl(aAction, nullptr, cx, aJSObject,
nullptr, nullptr,
aClassName, aProperty, nullptr);
}
NS_IMETHODIMP
nsScriptSecurityManager::CheckSameOrigin(JSContext* cx,
nsIURI* aTargetURI)
{
nsresult rv;
// Get a context if necessary
if (!cx)
{
cx = GetCurrentJSContext();
if (!cx)
return NS_OK; // No JS context, so allow access
}
// Get a principal from the context
nsIPrincipal* sourcePrincipal = GetSubjectPrincipal(cx, &rv);
if (NS_FAILED(rv))
return rv;
if (!sourcePrincipal)
{
NS_WARNING("CheckSameOrigin called on script w/o principals; should this happen?");
return NS_OK;
}
if (sourcePrincipal == mSystemPrincipal)
{
// This is a system (chrome) script, so allow access
return NS_OK;
}
// Get the original URI from the source principal.
// This has the effect of ignoring any change to document.domain
// which must be done to avoid DNS spoofing (bug 154930)
nsCOMPtr<nsIURI> sourceURI;
sourcePrincipal->GetDomain(getter_AddRefs(sourceURI));
if (!sourceURI) {
sourcePrincipal->GetURI(getter_AddRefs(sourceURI));
NS_ENSURE_TRUE(sourceURI, NS_ERROR_FAILURE);
}
// Compare origins
if (!SecurityCompareURIs(sourceURI, aTargetURI))
{
ReportError(cx, NS_LITERAL_STRING("CheckSameOriginError"), sourceURI, aTargetURI);
return NS_ERROR_DOM_BAD_URI;
}
return NS_OK;
}
NS_IMETHODIMP
nsScriptSecurityManager::CheckSameOriginURI(nsIURI* aSourceURI,
nsIURI* aTargetURI,
bool reportError)
{
if (!SecurityCompareURIs(aSourceURI, aTargetURI))
{
if (reportError) {
ReportError(nullptr, NS_LITERAL_STRING("CheckSameOriginError"),
aSourceURI, aTargetURI);
}
return NS_ERROR_DOM_BAD_URI;
}
return NS_OK;
}
nsresult
nsScriptSecurityManager::CheckPropertyAccessImpl(uint32_t aAction,
nsAXPCNativeCallContext* aCallContext,
JSContext* cx, JSObject* aJSObject,
nsISupports* aObj,
nsIClassInfo* aClassInfo,
const char* aClassName, jsid aProperty,
void** aCachedClassPolicy)
{
nsresult rv;
JS::RootedObject jsObject(cx, aJSObject);
JS::RootedId property(cx, aProperty);
nsIPrincipal* subjectPrincipal = GetSubjectPrincipal(cx, &rv);
if (NS_FAILED(rv))
return rv;
if (!subjectPrincipal || subjectPrincipal == mSystemPrincipal)
// We have native code or the system principal: just allow access
return NS_OK;
nsCOMPtr<nsIPrincipal> objectPrincipal;
// Hold the class info data here so we don't have to go back to virtual
// methods all the time
ClassInfoData classInfoData(aClassInfo, aClassName);
//-- Look up the security policy for this class and subject domain
SecurityLevel securityLevel;
rv = LookupPolicy(cx, subjectPrincipal, classInfoData, property, aAction,
(ClassPolicy**)aCachedClassPolicy, &securityLevel);
if (NS_FAILED(rv))
return rv;
if (securityLevel.level == SCRIPT_SECURITY_UNDEFINED_ACCESS)
{
// No policy found for this property so use the default of last resort.
// If we were called from somewhere other than XPConnect
// (no XPC call context), assume this is a DOM class. Otherwise,
// ask the ClassInfo.
if (!aCallContext || classInfoData.IsDOMClass())
securityLevel.level = SCRIPT_SECURITY_SAME_ORIGIN_ACCESS;
else
securityLevel.level = SCRIPT_SECURITY_NO_ACCESS;
}
if (SECURITY_ACCESS_LEVEL_FLAG(securityLevel))
// This flag means securityLevel is allAccess, noAccess, or sameOrigin
{
switch (securityLevel.level)
{
case SCRIPT_SECURITY_NO_ACCESS:
rv = NS_ERROR_DOM_PROP_ACCESS_DENIED;
break;
case SCRIPT_SECURITY_ALL_ACCESS:
rv = NS_OK;
break;
case SCRIPT_SECURITY_SAME_ORIGIN_ACCESS:
{
nsCOMPtr<nsIPrincipal> principalHolder;
if (jsObject)
{
objectPrincipal = doGetObjectPrincipal(jsObject);
if (!objectPrincipal)
rv = NS_ERROR_DOM_SECURITY_ERR;
}
else
{
NS_ERROR("CheckPropertyAccessImpl called without a target object or URL");
return NS_ERROR_FAILURE;
}
if(NS_SUCCEEDED(rv))
rv = CheckSameOriginDOMProp(subjectPrincipal, objectPrincipal,
aAction);
break;
}
default:
NS_ERROR("Bad Security Level Value");
return NS_ERROR_FAILURE;
}
}
else // if SECURITY_ACCESS_LEVEL_FLAG is false, securityLevel is a capability
{
rv = SubjectIsPrivileged() ? NS_OK : NS_ERROR_DOM_SECURITY_ERR;
}
if (NS_SUCCEEDED(rv))
{
return rv;
}
//--See if the object advertises a non-default level of access
// using nsISecurityCheckedComponent
nsCOMPtr<nsISecurityCheckedComponent> checkedComponent =
do_QueryInterface(aObj);
nsXPIDLCString objectSecurityLevel;
if (checkedComponent)
{
nsCOMPtr<nsIXPConnectWrappedNative> wrapper;
nsCOMPtr<nsIInterfaceInfo> interfaceInfo;
const nsIID* objIID = nullptr;
rv = aCallContext->GetCalleeWrapper(getter_AddRefs(wrapper));
if (NS_SUCCEEDED(rv) && wrapper)
rv = wrapper->FindInterfaceWithMember(property, getter_AddRefs(interfaceInfo));
if (NS_SUCCEEDED(rv) && interfaceInfo)
rv = interfaceInfo->GetIIDShared(&objIID);
if (NS_SUCCEEDED(rv) && objIID)
{
switch (aAction)
{
case nsIXPCSecurityManager::ACCESS_GET_PROPERTY:
checkedComponent->CanGetProperty(objIID,
IDToString(cx, property),
getter_Copies(objectSecurityLevel));
break;
case nsIXPCSecurityManager::ACCESS_SET_PROPERTY:
checkedComponent->CanSetProperty(objIID,
IDToString(cx, property),
getter_Copies(objectSecurityLevel));
break;
case nsIXPCSecurityManager::ACCESS_CALL_METHOD:
checkedComponent->CanCallMethod(objIID,
IDToString(cx, property),
getter_Copies(objectSecurityLevel));
}
}
}
rv = CheckXPCPermissions(cx, aObj, jsObject, subjectPrincipal,
objectSecurityLevel);
if (NS_FAILED(rv)) //-- Security tests failed, access is denied, report error
{
nsAutoString stringName;
switch(aAction)
{
case nsIXPCSecurityManager::ACCESS_GET_PROPERTY:
stringName.AssignLiteral("GetPropertyDeniedOrigins");
break;
case nsIXPCSecurityManager::ACCESS_SET_PROPERTY:
stringName.AssignLiteral("SetPropertyDeniedOrigins");
break;
case nsIXPCSecurityManager::ACCESS_CALL_METHOD:
stringName.AssignLiteral("CallMethodDeniedOrigins");
}
// Null out objectPrincipal for now, so we don't leak information about
// it. Whenever we can report different error strings to content and
// the UI we can take this out again.
objectPrincipal = nullptr;
NS_ConvertUTF8toUTF16 className(classInfoData.GetName());
nsAutoCString subjectOrigin;
nsAutoCString subjectDomain;
if (!nsAutoInPrincipalDomainOriginSetter::sInPrincipalDomainOrigin) {
nsCOMPtr<nsIURI> uri, domain;
subjectPrincipal->GetURI(getter_AddRefs(uri));
if (uri) { // Object principal might be expanded
GetOriginFromURI(uri, subjectOrigin);
}
subjectPrincipal->GetDomain(getter_AddRefs(domain));
if (domain) {
GetOriginFromURI(domain, subjectDomain);
}
} else {
subjectOrigin.AssignLiteral("the security manager");
}
NS_ConvertUTF8toUTF16 subjectOriginUnicode(subjectOrigin);
NS_ConvertUTF8toUTF16 subjectDomainUnicode(subjectDomain);
nsAutoCString objectOrigin;
nsAutoCString objectDomain;
if (!nsAutoInPrincipalDomainOriginSetter::sInPrincipalDomainOrigin &&
objectPrincipal) {
nsCOMPtr<nsIURI> uri, domain;
objectPrincipal->GetURI(getter_AddRefs(uri));
if (uri) { // Object principal might be system
GetOriginFromURI(uri, objectOrigin);
}
objectPrincipal->GetDomain(getter_AddRefs(domain));
if (domain) {
GetOriginFromURI(domain, objectDomain);
}
}
NS_ConvertUTF8toUTF16 objectOriginUnicode(objectOrigin);
NS_ConvertUTF8toUTF16 objectDomainUnicode(objectDomain);
nsXPIDLString errorMsg;
const PRUnichar *formatStrings[] =
{
subjectOriginUnicode.get(),
className.get(),
IDToString(cx, property),
objectOriginUnicode.get(),
subjectDomainUnicode.get(),
objectDomainUnicode.get()
};
uint32_t length = ArrayLength(formatStrings);
// XXXbz Our localization system is stupid and can't handle not showing
// some strings that get passed in. Which means that we have to get
// our length precisely right: it has to be exactly the number of
// strings our format string wants. This means we'll have to move
// strings in the array as needed, sadly...
if (nsAutoInPrincipalDomainOriginSetter::sInPrincipalDomainOrigin ||
!objectPrincipal) {
stringName.AppendLiteral("OnlySubject");
length -= 3;
} else {
// default to a length that doesn't include the domains, then
// increase it as needed.
length -= 2;
if (!subjectDomainUnicode.IsEmpty()) {
stringName.AppendLiteral("SubjectDomain");
length += 1;
}
if (!objectDomainUnicode.IsEmpty()) {
stringName.AppendLiteral("ObjectDomain");
length += 1;
if (length != ArrayLength(formatStrings)) {
// We have an object domain but not a subject domain.
// Scoot our string over one slot. See the XXX comment
// above for why we need to do this.
formatStrings[length-1] = formatStrings[length];
}
}
}
// We need to keep our existing failure rv and not override it
// with a likely success code from the following string bundle
// call in order to throw the correct security exception later.
nsresult rv2 = sStrBundle->FormatStringFromName(stringName.get(),
formatStrings,
length,
getter_Copies(errorMsg));
if (NS_FAILED(rv2)) {
// Might just be missing the string... Do our best
errorMsg = stringName;
}
SetPendingException(cx, errorMsg.get());
}
return rv;
}
/* static */
nsresult
nsScriptSecurityManager::CheckSameOriginPrincipal(nsIPrincipal* aSubject,
nsIPrincipal* aObject)
{
/*
** Get origin of subject and object and compare.
*/
if (aSubject == aObject)
return NS_OK;
if (!AppAttributesEqual(aSubject, aObject)) {
return NS_ERROR_DOM_PROP_ACCESS_DENIED;
}
// Default to false, and change if that turns out wrong.
bool subjectSetDomain = false;
bool objectSetDomain = false;
nsCOMPtr<nsIURI> subjectURI;
nsCOMPtr<nsIURI> objectURI;
aSubject->GetDomain(getter_AddRefs(subjectURI));
if (!subjectURI) {
aSubject->GetURI(getter_AddRefs(subjectURI));
} else {
subjectSetDomain = true;
}
aObject->GetDomain(getter_AddRefs(objectURI));
if (!objectURI) {
aObject->GetURI(getter_AddRefs(objectURI));
} else {
objectSetDomain = true;
}
if (SecurityCompareURIs(subjectURI, objectURI))
{ // If either the subject or the object has changed its principal by
// explicitly setting document.domain then the other must also have
// done so in order to be considered the same origin. This prevents
// DNS spoofing based on document.domain (154930)
// If both or neither explicitly set their domain, allow the access
if (subjectSetDomain == objectSetDomain)
return NS_OK;
}
/*
** Access tests failed, so now report error.
*/
return NS_ERROR_DOM_PROP_ACCESS_DENIED;
}
// It's important that
//
// CheckSameOriginPrincipal(A, B) == NS_OK
//
// imply
//
// HashPrincipalByOrigin(A) == HashPrincipalByOrigin(B)
//
// if principals A and B could ever be used as keys in a hashtable.
// Violation of this invariant leads to spurious failures of hashtable
// lookups. See bug 454850.
/*static*/ uint32_t
nsScriptSecurityManager::HashPrincipalByOrigin(nsIPrincipal* aPrincipal)
{
nsCOMPtr<nsIURI> uri;
aPrincipal->GetDomain(getter_AddRefs(uri));
if (!uri)
aPrincipal->GetURI(getter_AddRefs(uri));
return SecurityHashURI(uri);
}
/* static */ bool
nsScriptSecurityManager::AppAttributesEqual(nsIPrincipal* aFirst,
nsIPrincipal* aSecond)
{
MOZ_ASSERT(aFirst && aSecond, "Don't pass null pointers!");
uint32_t firstAppId = nsIScriptSecurityManager::UNKNOWN_APP_ID;
if (!aFirst->GetUnknownAppId()) {
firstAppId = aFirst->GetAppId();
}
uint32_t secondAppId = nsIScriptSecurityManager::UNKNOWN_APP_ID;
if (!aSecond->GetUnknownAppId()) {
secondAppId = aSecond->GetAppId();
}
return ((firstAppId == secondAppId) &&
(aFirst->GetIsInBrowserElement() == aSecond->GetIsInBrowserElement()));
}
nsresult
nsScriptSecurityManager::CheckSameOriginDOMProp(nsIPrincipal* aSubject,
nsIPrincipal* aObject,
uint32_t aAction)
{
nsresult rv;
bool subsumes;
rv = aSubject->Subsumes(aObject, &subsumes);
if (NS_SUCCEEDED(rv) && !subsumes) {
rv = NS_ERROR_DOM_PROP_ACCESS_DENIED;
}
if (NS_SUCCEEDED(rv))
return NS_OK;
/*
* Content can't ever touch chrome (we check for UniversalXPConnect later)
*/
if (aObject == mSystemPrincipal)
return NS_ERROR_DOM_PROP_ACCESS_DENIED;
/*
** Access tests failed, so now report error.
*/
return NS_ERROR_DOM_PROP_ACCESS_DENIED;
}
nsresult
nsScriptSecurityManager::LookupPolicy(JSContext* cx,
nsIPrincipal* aPrincipal,
ClassInfoData& aClassData,
jsid aProperty,
uint32_t aAction,
ClassPolicy** aCachedClassPolicy,
SecurityLevel* result)
{
nsresult rv;
JS::RootedId property(cx, aProperty);
result->level = SCRIPT_SECURITY_UNDEFINED_ACCESS;
DomainPolicy* dpolicy = nullptr;
//-- Initialize policies if necessary
if (mPolicyPrefsChanged)
{
if (!mPrefInitialized) {
rv = InitPrefs();
NS_ENSURE_SUCCESS(rv, rv);
}
rv = InitPolicies();
if (NS_FAILED(rv))
return rv;
}
else
{
aPrincipal->GetSecurityPolicy((void**)&dpolicy);
}
if (!dpolicy && mOriginToPolicyMap)
{
//-- Look up the relevant domain policy, if any
if (nsCOMPtr<nsIExpandedPrincipal> exp = do_QueryInterface(aPrincipal))
{
// For expanded principals domain origin is not defined so let's just
// use the default policy
dpolicy = mDefaultPolicy;
}
else
{
nsAutoCString origin;
rv = GetPrincipalDomainOrigin(aPrincipal, origin);
NS_ENSURE_SUCCESS(rv, rv);
char *start = origin.BeginWriting();
const char *nextToLastDot = nullptr;
const char *lastDot = nullptr;
const char *colon = nullptr;
char *p = start;
//-- search domain (stop at the end of the string or at the 3rd slash)
for (uint32_t slashes=0; *p; p++)
{
if (*p == '/' && ++slashes == 3)
{
*p = '\0'; // truncate at 3rd slash
break;
}
if (*p == '.')
{
nextToLastDot = lastDot;
lastDot = p;
}
else if (!colon && *p == ':')
colon = p;
}
nsCStringKey key(nextToLastDot ? nextToLastDot+1 : start);
DomainEntry *de = (DomainEntry*) mOriginToPolicyMap->Get(&key);
if (!de)
{
nsAutoCString scheme(start, colon-start+1);
nsCStringKey schemeKey(scheme);
de = (DomainEntry*) mOriginToPolicyMap->Get(&schemeKey);
}
while (de)
{
if (de->Matches(start))
{
dpolicy = de->mDomainPolicy;
break;
}
de = de->mNext;
}
if (!dpolicy)
dpolicy = mDefaultPolicy;
}
aPrincipal->SetSecurityPolicy((void*)dpolicy);
}
ClassPolicy* cpolicy = nullptr;
if ((dpolicy == mDefaultPolicy) && aCachedClassPolicy)
{
// No per-domain policy for this principal (the more common case)
// so look for a cached class policy from the object wrapper
cpolicy = *aCachedClassPolicy;
}
if (!cpolicy)
{ //-- No cached policy for this class, need to look it up
cpolicy = static_cast<ClassPolicy*>
(PL_DHashTableOperate(dpolicy,
aClassData.GetName(),
PL_DHASH_LOOKUP));
if (PL_DHASH_ENTRY_IS_FREE(cpolicy))
cpolicy = NO_POLICY_FOR_CLASS;
if ((dpolicy == mDefaultPolicy) && aCachedClassPolicy)
*aCachedClassPolicy = cpolicy;
}
NS_ASSERTION(JSID_IS_INT(property) || JSID_IS_OBJECT(property) ||
JSID_IS_STRING(property), "Property must be a valid id");
// Only atomized strings are stored in the policies' hash tables.
if (!JSID_IS_STRING(property))
return NS_OK;
JS::RootedString propertyKey(cx, JSID_TO_STRING(property));
// We look for a PropertyPolicy in the following places:
// 1) The ClassPolicy for our class we got from our DomainPolicy
// 2) The mWildcardPolicy of our DomainPolicy
// 3) The ClassPolicy for our class we got from mDefaultPolicy
// 4) The mWildcardPolicy of our mDefaultPolicy
PropertyPolicy* ppolicy = nullptr;
if (cpolicy != NO_POLICY_FOR_CLASS)
{
ppolicy = static_cast<PropertyPolicy*>
(PL_DHashTableOperate(cpolicy->mPolicy,
propertyKey,
PL_DHASH_LOOKUP));
}
// If there is no class policy for this property, and we have a wildcard
// policy, try that.
if (dpolicy->mWildcardPolicy &&
(!ppolicy || PL_DHASH_ENTRY_IS_FREE(ppolicy)))
{
ppolicy =
static_cast<PropertyPolicy*>
(PL_DHashTableOperate(dpolicy->mWildcardPolicy->mPolicy,
propertyKey,
PL_DHASH_LOOKUP));
}
// If dpolicy is not the defauly policy and there's no class or wildcard
// policy for this property, check the default policy for this class and
// the default wildcard policy
if (dpolicy != mDefaultPolicy &&
(!ppolicy || PL_DHASH_ENTRY_IS_FREE(ppolicy)))
{
cpolicy = static_cast<ClassPolicy*>
(PL_DHashTableOperate(mDefaultPolicy,
aClassData.GetName(),
PL_DHASH_LOOKUP));
if (PL_DHASH_ENTRY_IS_BUSY(cpolicy))
{
ppolicy =
static_cast<PropertyPolicy*>
(PL_DHashTableOperate(cpolicy->mPolicy,
propertyKey,
PL_DHASH_LOOKUP));
}
if ((!ppolicy || PL_DHASH_ENTRY_IS_FREE(ppolicy)) &&
mDefaultPolicy->mWildcardPolicy)
{
ppolicy =
static_cast<PropertyPolicy*>
(PL_DHashTableOperate(mDefaultPolicy->mWildcardPolicy->mPolicy,
propertyKey,
PL_DHASH_LOOKUP));
}
}
if (!ppolicy || PL_DHASH_ENTRY_IS_FREE(ppolicy))
return NS_OK;
// Get the correct security level from the property policy
if (aAction == nsIXPCSecurityManager::ACCESS_SET_PROPERTY)
*result = ppolicy->mSet;
else
*result = ppolicy->mGet;
return NS_OK;
}
NS_IMETHODIMP
nsScriptSecurityManager::CheckLoadURIFromScript(JSContext *cx, nsIURI *aURI)
{
// Get principal of currently executing script.
nsresult rv;
nsIPrincipal* principal = GetSubjectPrincipal(cx, &rv);
if (NS_FAILED(rv))
return rv;
// Native code can load all URIs.
if (!principal)
return NS_OK;
rv = CheckLoadURIWithPrincipal(principal, aURI,
nsIScriptSecurityManager::STANDARD);
if (NS_SUCCEEDED(rv)) {
// OK to load
return NS_OK;
}
// See if we're attempting to load a file: URI. If so, let a
// UniversalXPConnect capability trump the above check.
bool isFile = false;
bool isRes = false;
if (NS_FAILED(aURI->SchemeIs("file", &isFile)) ||
NS_FAILED(aURI->SchemeIs("resource", &isRes)))
return NS_ERROR_FAILURE;
if (isFile || isRes)
{
if (SubjectIsPrivileged())
return NS_OK;
}
// Report error.
nsAutoCString spec;
if (NS_FAILED(aURI->GetAsciiSpec(spec)))
return NS_ERROR_FAILURE;
nsAutoCString msg("Access to '");
msg.Append(spec);
msg.AppendLiteral("' from script denied");
SetPendingException(cx, msg.get());
return NS_ERROR_DOM_BAD_URI;
}
/**
* Helper method to handle cases where a flag passed to
* CheckLoadURIWithPrincipal means denying loading if the given URI has certain
* nsIProtocolHandler flags set.
* @return if success, access is allowed. Otherwise, deny access
*/
static nsresult
DenyAccessIfURIHasFlags(nsIURI* aURI, uint32_t aURIFlags)
{
NS_PRECONDITION(aURI, "Must have URI!");
bool uriHasFlags;
nsresult rv =
NS_URIChainHasFlags(aURI, aURIFlags, &uriHasFlags);
NS_ENSURE_SUCCESS(rv, rv);
if (uriHasFlags) {
return NS_ERROR_DOM_BAD_URI;
}
return NS_OK;
}
NS_IMETHODIMP
nsScriptSecurityManager::CheckLoadURIWithPrincipal(nsIPrincipal* aPrincipal,
nsIURI *aTargetURI,
uint32_t aFlags)
{
NS_PRECONDITION(aPrincipal, "CheckLoadURIWithPrincipal must have a principal");
// If someone passes a flag that we don't understand, we should
// fail, because they may need a security check that we don't
// provide.
NS_ENSURE_FALSE(aFlags & ~(nsIScriptSecurityManager::LOAD_IS_AUTOMATIC_DOCUMENT_REPLACEMENT |
nsIScriptSecurityManager::ALLOW_CHROME |
nsIScriptSecurityManager::DISALLOW_SCRIPT |
nsIScriptSecurityManager::DISALLOW_INHERIT_PRINCIPAL |
nsIScriptSecurityManager::DONT_REPORT_ERRORS),
NS_ERROR_UNEXPECTED);
NS_ENSURE_ARG_POINTER(aPrincipal);
NS_ENSURE_ARG_POINTER(aTargetURI);
// If DISALLOW_INHERIT_PRINCIPAL is set, we prevent loading of URIs which
// would do such inheriting. That would be URIs that do not have their own
// security context. We do this even for the system principal.
if (aFlags & nsIScriptSecurityManager::DISALLOW_INHERIT_PRINCIPAL) {
nsresult rv =
DenyAccessIfURIHasFlags(aTargetURI,
nsIProtocolHandler::URI_INHERITS_SECURITY_CONTEXT);
NS_ENSURE_SUCCESS(rv, rv);
}
if (aPrincipal == mSystemPrincipal) {
// Allow access
return NS_OK;
}
nsCOMPtr<nsIURI> sourceURI;
aPrincipal->GetURI(getter_AddRefs(sourceURI));
if (!sourceURI) {
nsCOMPtr<nsIExpandedPrincipal> expanded = do_QueryInterface(aPrincipal);
if (expanded) {
nsTArray< nsCOMPtr<nsIPrincipal> > *whiteList;
expanded->GetWhiteList(&whiteList);
for (uint32_t i = 0; i < whiteList->Length(); ++i) {
nsresult rv = CheckLoadURIWithPrincipal((*whiteList)[i],
aTargetURI,
aFlags);
if (NS_SUCCEEDED(rv)) {
// Allow access if it succeeded with one of the white listed principals
return NS_OK;
}
}
// None of our whitelisted principals worked.
return NS_ERROR_DOM_BAD_URI;
}
NS_ERROR("Non-system principals or expanded principal passed to CheckLoadURIWithPrincipal "
"must have a URI!");
return NS_ERROR_UNEXPECTED;
}
// Automatic loads are not allowed from certain protocols.
if (aFlags & nsIScriptSecurityManager::LOAD_IS_AUTOMATIC_DOCUMENT_REPLACEMENT) {
nsresult rv =
DenyAccessIfURIHasFlags(sourceURI,
nsIProtocolHandler::URI_FORBIDS_AUTOMATIC_DOCUMENT_REPLACEMENT);
NS_ENSURE_SUCCESS(rv, rv);
}
// If either URI is a nested URI, get the base URI
nsCOMPtr<nsIURI> sourceBaseURI = NS_GetInnermostURI(sourceURI);
nsCOMPtr<nsIURI> targetBaseURI = NS_GetInnermostURI(aTargetURI);
//-- get the target scheme
nsAutoCString targetScheme;
nsresult rv = targetBaseURI->GetScheme(targetScheme);
if (NS_FAILED(rv)) return rv;
//-- Some callers do not allow loading javascript:
if ((aFlags & nsIScriptSecurityManager::DISALLOW_SCRIPT) &&
targetScheme.EqualsLiteral("javascript"))
{
return NS_ERROR_DOM_BAD_URI;
}
NS_NAMED_LITERAL_STRING(errorTag, "CheckLoadURIError");
bool reportErrors = !(aFlags & nsIScriptSecurityManager::DONT_REPORT_ERRORS);
// Check for uris that are only loadable by principals that subsume them
bool hasFlags;
rv = NS_URIChainHasFlags(targetBaseURI,
nsIProtocolHandler::URI_LOADABLE_BY_SUBSUMERS,
&hasFlags);
NS_ENSURE_SUCCESS(rv, rv);
if (hasFlags) {
return aPrincipal->CheckMayLoad(targetBaseURI, true, false);
}
//-- get the source scheme
nsAutoCString sourceScheme;
rv = sourceBaseURI->GetScheme(sourceScheme);
if (NS_FAILED(rv)) return rv;
if (sourceScheme.LowerCaseEqualsLiteral(NS_NULLPRINCIPAL_SCHEME)) {
// A null principal can target its own URI.
if (sourceURI == aTargetURI) {
return NS_OK;
}
}
else if (targetScheme.Equals(sourceScheme,
nsCaseInsensitiveCStringComparator()))
{
// every scheme can access another URI from the same scheme,
// as long as they don't represent null principals...
// Or they don't require an special permission to do so
// See bug#773886
bool hasFlags;
rv = NS_URIChainHasFlags(targetBaseURI,
nsIProtocolHandler::URI_CROSS_ORIGIN_NEEDS_WEBAPPS_PERM,
&hasFlags);
NS_ENSURE_SUCCESS(rv, rv);
if (hasFlags) {
// In this case, we allow opening only if the source and target URIS
// are on the same domain, or the opening URI has the webapps
// permision granted
if (!SecurityCompareURIs(sourceBaseURI,targetBaseURI) &&
!nsContentUtils::IsExactSitePermAllow(aPrincipal,WEBAPPS_PERM_NAME)){
return NS_ERROR_DOM_BAD_URI;
}
}
return NS_OK;
}
// If the schemes don't match, the policy is specified by the protocol
// flags on the target URI. Note that the order of policy checks here is
// very important! We start from most restrictive and work our way down.
// Note that since we're working with the innermost URI, we can just use
// the methods that work on chains of nested URIs and they will only look
// at the flags for our one URI.
// Check for system target URI
rv = DenyAccessIfURIHasFlags(targetBaseURI,
nsIProtocolHandler::URI_DANGEROUS_TO_LOAD);
if (NS_FAILED(rv)) {
// Deny access, since the origin principal is not system
if (reportErrors) {
ReportError(nullptr, errorTag, sourceURI, aTargetURI);
}
return rv;
}
// Check for chrome target URI
rv = NS_URIChainHasFlags(targetBaseURI,
nsIProtocolHandler::URI_IS_UI_RESOURCE,
&hasFlags);
NS_ENSURE_SUCCESS(rv, rv);
if (hasFlags) {
if (aFlags & nsIScriptSecurityManager::ALLOW_CHROME) {
if (!targetScheme.EqualsLiteral("chrome")) {
// for now don't change behavior for resource: or moz-icon:
return NS_OK;
}
// allow load only if chrome package is whitelisted
nsCOMPtr<nsIXULChromeRegistry> reg(do_GetService(
NS_CHROMEREGISTRY_CONTRACTID));
if (reg) {
bool accessAllowed = false;
reg->AllowContentToAccess(targetBaseURI, &accessAllowed);
if (accessAllowed) {
return NS_OK;
}
}
}
// resource: and chrome: are equivalent, securitywise
// That's bogus!! Fix this. But watch out for
// the view-source stylesheet?
bool sourceIsChrome;
rv = NS_URIChainHasFlags(sourceBaseURI,
nsIProtocolHandler::URI_IS_UI_RESOURCE,
&sourceIsChrome);
NS_ENSURE_SUCCESS(rv, rv);
if (sourceIsChrome) {
return NS_OK;
}
if (reportErrors) {
ReportError(nullptr, errorTag, sourceURI, aTargetURI);
}
return NS_ERROR_DOM_BAD_URI;
}
// Check for target URI pointing to a file
rv = NS_URIChainHasFlags(targetBaseURI,
nsIProtocolHandler::URI_IS_LOCAL_FILE,
&hasFlags);
NS_ENSURE_SUCCESS(rv, rv);
if (hasFlags) {
// resource: and chrome: are equivalent, securitywise
// That's bogus!! Fix this. But watch out for
// the view-source stylesheet?
bool sourceIsChrome;
rv = NS_URIChainHasFlags(sourceURI,
nsIProtocolHandler::URI_IS_UI_RESOURCE,
&sourceIsChrome);
NS_ENSURE_SUCCESS(rv, rv);
if (sourceIsChrome) {
return NS_OK;
}
// Now check capability policies
static const char loadURIPrefGroup[] = "checkloaduri";
ClassInfoData nameData(nullptr, loadURIPrefGroup);
SecurityLevel secLevel;
rv = LookupPolicy(GetCurrentJSContext(),
aPrincipal, nameData, sEnabledID,
nsIXPCSecurityManager::ACCESS_GET_PROPERTY,
nullptr, &secLevel);
if (NS_SUCCEEDED(rv) && secLevel.level == SCRIPT_SECURITY_ALL_ACCESS)
{
// OK for this site!
return NS_OK;
}
if (reportErrors) {
ReportError(nullptr, errorTag, sourceURI, aTargetURI);
}
return NS_ERROR_DOM_BAD_URI;
}
// OK, everyone is allowed to load this, since unflagged handlers are
// deprecated but treated as URI_LOADABLE_BY_ANYONE. But check whether we
// need to warn. At some point we'll want to make this warning into an
// error and treat unflagged handlers as URI_DANGEROUS_TO_LOAD.
rv = NS_URIChainHasFlags(targetBaseURI,
nsIProtocolHandler::URI_LOADABLE_BY_ANYONE,
&hasFlags);
NS_ENSURE_SUCCESS(rv, rv);
if (!hasFlags) {
nsXPIDLString message;
NS_ConvertASCIItoUTF16 ucsTargetScheme(targetScheme);
const PRUnichar* formatStrings[] = { ucsTargetScheme.get() };
rv = sStrBundle->
FormatStringFromName(NS_LITERAL_STRING("ProtocolFlagError").get(),
formatStrings,
ArrayLength(formatStrings),
getter_Copies(message));
if (NS_SUCCEEDED(rv)) {
nsCOMPtr<nsIConsoleService> console(
do_GetService("@mozilla.org/consoleservice;1"));
NS_ENSURE_TRUE(console, NS_ERROR_FAILURE);
console->LogStringMessage(message.get());
}
}
return NS_OK;
}
nsresult
nsScriptSecurityManager::ReportError(JSContext* cx, const nsAString& messageTag,
nsIURI* aSource, nsIURI* aTarget)
{
nsresult rv;
NS_ENSURE_TRUE(aSource && aTarget, NS_ERROR_NULL_POINTER);
// Get the source URL spec
nsAutoCString sourceSpec;
rv = aSource->GetAsciiSpec(sourceSpec);
NS_ENSURE_SUCCESS(rv, rv);
// Get the target URL spec
nsAutoCString targetSpec;
rv = aTarget->GetAsciiSpec(targetSpec);
NS_ENSURE_SUCCESS(rv, rv);
// Localize the error message
nsXPIDLString message;
NS_ConvertASCIItoUTF16 ucsSourceSpec(sourceSpec);
NS_ConvertASCIItoUTF16 ucsTargetSpec(targetSpec);
const PRUnichar *formatStrings[] = { ucsSourceSpec.get(), ucsTargetSpec.get() };
rv = sStrBundle->FormatStringFromName(PromiseFlatString(messageTag).get(),
formatStrings,
ArrayLength(formatStrings),
getter_Copies(message));
NS_ENSURE_SUCCESS(rv, rv);
// If a JS context was passed in, set a JS exception.
// Otherwise, print the error message directly to the JS console
// and to standard output
if (cx)
{
SetPendingException(cx, message.get());
}
else // Print directly to the console
{
nsCOMPtr<nsIConsoleService> console(
do_GetService("@mozilla.org/consoleservice;1"));
NS_ENSURE_TRUE(console, NS_ERROR_FAILURE);
console->LogStringMessage(message.get());
}
return NS_OK;
}
NS_IMETHODIMP
nsScriptSecurityManager::CheckLoadURIStrWithPrincipal(nsIPrincipal* aPrincipal,
const nsACString& aTargetURIStr,
uint32_t aFlags)
{
nsresult rv;
nsCOMPtr<nsIURI> target;
rv = NS_NewURI(getter_AddRefs(target), aTargetURIStr,
nullptr, nullptr, sIOService);
NS_ENSURE_SUCCESS(rv, rv);
rv = CheckLoadURIWithPrincipal(aPrincipal, target, aFlags);
NS_ENSURE_SUCCESS(rv, rv);
// Now start testing fixup -- since aTargetURIStr is a string, not
// an nsIURI, we may well end up fixing it up before loading.
// Note: This needs to stay in sync with the nsIURIFixup api.
nsCOMPtr<nsIURIFixup> fixup = do_GetService(NS_URIFIXUP_CONTRACTID);
if (!fixup) {
return rv;
}
uint32_t flags[] = {
nsIURIFixup::FIXUP_FLAG_NONE,
nsIURIFixup::FIXUP_FLAG_ALLOW_KEYWORD_LOOKUP,
nsIURIFixup::FIXUP_FLAGS_MAKE_ALTERNATE_URI,
nsIURIFixup::FIXUP_FLAG_ALLOW_KEYWORD_LOOKUP |
nsIURIFixup::FIXUP_FLAGS_MAKE_ALTERNATE_URI
};
for (uint32_t i = 0; i < ArrayLength(flags); ++i) {
rv = fixup->CreateFixupURI(aTargetURIStr, flags[i], nullptr,
getter_AddRefs(target));
NS_ENSURE_SUCCESS(rv, rv);
rv = CheckLoadURIWithPrincipal(aPrincipal, target, aFlags);
NS_ENSURE_SUCCESS(rv, rv);
}
return rv;
}
NS_IMETHODIMP
nsScriptSecurityManager::CheckFunctionAccess(JSContext *aCx, void *aFunObj,
void *aTargetObj)
{
// This check is called for event handlers
nsresult rv;
JS::Rooted<JSObject*> rootedFunObj(aCx, static_cast<JSObject*>(aFunObj));
nsIPrincipal* subject =
GetFunctionObjectPrincipal(aCx, rootedFunObj, &rv);
// If subject is null, get a principal from the function object's scope.
if (NS_SUCCEEDED(rv) && !subject)
{
#ifdef DEBUG
{
JS_ASSERT(JS_ObjectIsFunction(aCx, rootedFunObj));
JS::Rooted<JSFunction*> fun(aCx, JS_GetObjectFunction(rootedFunObj));
JSScript *script = JS_GetFunctionScript(aCx, fun);
NS_ASSERTION(!script, "Null principal for non-native function!");
}
#endif
subject = doGetObjectPrincipal(rootedFunObj);
}
if (!subject)
return NS_ERROR_FAILURE;
if (subject == mSystemPrincipal)
// This is the system principal: just allow access
return NS_OK;
// Check if the principal the function was compiled under is
// allowed to execute scripts.
bool result;
rv = CanExecuteScripts(aCx, subject, true, &result);
if (NS_FAILED(rv))
return rv;
if (!result)
return NS_ERROR_DOM_SECURITY_ERR;
if (!aTargetObj) {
// We're done here
return NS_OK;
}
/*
** Get origin of subject and object and compare.
*/
JS::Rooted<JSObject*> obj(aCx, (JSObject*)aTargetObj);
nsIPrincipal* object = doGetObjectPrincipal(obj);
if (!object)
return NS_ERROR_FAILURE;
bool subsumes;
rv = subject->Subsumes(object, &subsumes);
if (NS_SUCCEEDED(rv) && !subsumes) {
rv = NS_ERROR_DOM_PROP_ACCESS_DENIED;
}
return rv;
}
NS_IMETHODIMP
nsScriptSecurityManager::CanExecuteScripts(JSContext* cx,
nsIPrincipal *aPrincipal,
bool *result)
{
return CanExecuteScripts(cx, aPrincipal, false, result);
}
nsresult
nsScriptSecurityManager::CanExecuteScripts(JSContext* cx,
nsIPrincipal *aPrincipal,
bool aAllowIfNoScriptContext,
bool *result)
{
*result = false;
if (aPrincipal == mSystemPrincipal)
{
// Even if JavaScript is disabled, we must still execute system scripts
*result = true;
return NS_OK;
}
// Same thing for nsExpandedPrincipal, which is pseudo-privileged.
nsCOMPtr<nsIExpandedPrincipal> ep = do_QueryInterface(aPrincipal);
if (ep)
{
*result = true;
return NS_OK;
}
//-- See if the current window allows JS execution
nsIScriptContext *scriptContext = GetScriptContext(cx);
if (!scriptContext) {
if (aAllowIfNoScriptContext) {
*result = true;
return NS_OK;
}
return NS_ERROR_FAILURE;
}
if (!scriptContext->GetScriptsEnabled()) {
// No scripting on this context, folks
*result = false;
return NS_OK;
}
nsIScriptGlobalObject *sgo = scriptContext->GetGlobalObject();
if (!sgo) {
return NS_ERROR_FAILURE;
}
// window can be null here if we're running with a non-DOM window
// as the script global (i.e. a XUL prototype document).
nsCOMPtr<nsPIDOMWindow> window = do_QueryInterface(sgo);
nsCOMPtr<nsIDocShell> docshell;
nsresult rv;
if (window) {
docshell = window->GetDocShell();
}
if (docshell) {
rv = docshell->GetCanExecuteScripts(result);
if (NS_FAILED(rv)) return rv;
if (!*result) return NS_OK;
}
// OK, the docshell doesn't have script execution explicitly disabled.
// Check whether our URI is an "about:" URI that allows scripts. If it is,
// we need to allow JS to run. In this case, don't apply the JS enabled
// pref or policies. On failures, just press on and don't do this special
// case.
nsCOMPtr<nsIURI> principalURI;
aPrincipal->GetURI(getter_AddRefs(principalURI));
if (!principalURI) {
// Broken principal of some sort. Disallow.
*result = false;
return NS_ERROR_UNEXPECTED;
}
bool isAbout;
rv = principalURI->SchemeIs("about", &isAbout);
if (NS_SUCCEEDED(rv) && isAbout) {
nsCOMPtr<nsIAboutModule> module;
rv = NS_GetAboutModule(principalURI, getter_AddRefs(module));
if (NS_SUCCEEDED(rv)) {
uint32_t flags;
rv = module->GetURIFlags(principalURI, &flags);
if (NS_SUCCEEDED(rv) &&
(flags & nsIAboutModule::ALLOW_SCRIPT)) {
*result = true;
return NS_OK;
}
}
}
*result = mIsJavaScriptEnabled;
if (!*result)
return NS_OK; // Do not run scripts
//-- Check for a per-site policy
static const char jsPrefGroupName[] = "javascript";
ClassInfoData nameData(nullptr, jsPrefGroupName);
SecurityLevel secLevel;
rv = LookupPolicy(cx, aPrincipal, nameData, sEnabledID,
nsIXPCSecurityManager::ACCESS_GET_PROPERTY,
nullptr, &secLevel);
if (NS_FAILED(rv) || secLevel.level == SCRIPT_SECURITY_NO_ACCESS)
{
*result = false;
return rv;
}
//-- Nobody vetoed, so allow the JS to run.
*result = true;
return NS_OK;
}
///////////////// Principals ///////////////////////
NS_IMETHODIMP
nsScriptSecurityManager::GetSubjectPrincipal(nsIPrincipal **aSubjectPrincipal)
{
nsresult rv;
*aSubjectPrincipal = doGetSubjectPrincipal(&rv);
if (NS_SUCCEEDED(rv))
NS_IF_ADDREF(*aSubjectPrincipal);
return rv;
}
nsIPrincipal*
nsScriptSecurityManager::doGetSubjectPrincipal(nsresult* rv)
{
NS_PRECONDITION(rv, "Null out param");
JSContext *cx = GetCurrentJSContext();
if (!cx)
{
*rv = NS_OK;
return nullptr;
}
return GetSubjectPrincipal(cx, rv);
}
NS_IMETHODIMP
nsScriptSecurityManager::GetSystemPrincipal(nsIPrincipal **result)
{
NS_ADDREF(*result = mSystemPrincipal);
return NS_OK;
}
NS_IMETHODIMP
nsScriptSecurityManager::SubjectPrincipalIsSystem(bool* aIsSystem)
{
NS_ENSURE_ARG_POINTER(aIsSystem);
*aIsSystem = false;
if (!mSystemPrincipal)
return NS_OK;
nsCOMPtr<nsIPrincipal> subject;
nsresult rv = GetSubjectPrincipal(getter_AddRefs(subject));
if (NS_FAILED(rv))
return rv;
if(!subject)
{
// No subject principal means no JS is running;
// this is the equivalent of system principal code
*aIsSystem = true;
return NS_OK;
}
return mSystemPrincipal->Equals(subject, aIsSystem);
}
nsresult
nsScriptSecurityManager::CreateCodebasePrincipal(nsIURI* aURI, uint32_t aAppId,
bool aInMozBrowser,
nsIPrincipal **result)
{
// I _think_ it's safe to not create null principals here based on aURI.
// At least all the callers would do the right thing in those cases, as far
// as I can tell. --bz
nsCOMPtr<nsIURIWithPrincipal> uriPrinc = do_QueryInterface(aURI);
if (uriPrinc) {
nsCOMPtr<nsIPrincipal> principal;
uriPrinc->GetPrincipal(getter_AddRefs(principal));
if (!principal || principal == mSystemPrincipal) {
return CallCreateInstance(NS_NULLPRINCIPAL_CONTRACTID, result);
}
principal.forget(result);
return NS_OK;
}
nsRefPtr<nsPrincipal> codebase = new nsPrincipal();
if (!codebase)
return NS_ERROR_OUT_OF_MEMORY;
nsresult rv = codebase->Init(aURI, aAppId, aInMozBrowser);
if (NS_FAILED(rv))
return rv;
NS_ADDREF(*result = codebase);
return NS_OK;
}
NS_IMETHODIMP
nsScriptSecurityManager::GetSimpleCodebasePrincipal(nsIURI* aURI,
nsIPrincipal** aPrincipal)
{
return GetCodebasePrincipalInternal(aURI,
nsIScriptSecurityManager::UNKNOWN_APP_ID,
false, aPrincipal);
}
NS_IMETHODIMP
nsScriptSecurityManager::GetNoAppCodebasePrincipal(nsIURI* aURI,
nsIPrincipal** aPrincipal)
{
return GetCodebasePrincipalInternal(aURI, nsIScriptSecurityManager::NO_APP_ID,
false, aPrincipal);
}
NS_IMETHODIMP
nsScriptSecurityManager::GetCodebasePrincipal(nsIURI* aURI,
nsIPrincipal** aPrincipal)
{
return GetNoAppCodebasePrincipal(aURI, aPrincipal);
}
NS_IMETHODIMP
nsScriptSecurityManager::GetAppCodebasePrincipal(nsIURI* aURI,
uint32_t aAppId,
bool aInMozBrowser,
nsIPrincipal** aPrincipal)
{
NS_ENSURE_TRUE(aAppId != nsIScriptSecurityManager::UNKNOWN_APP_ID,
NS_ERROR_INVALID_ARG);
return GetCodebasePrincipalInternal(aURI, aAppId, aInMozBrowser, aPrincipal);
}
NS_IMETHODIMP
nsScriptSecurityManager::GetDocShellCodebasePrincipal(nsIURI* aURI,
nsIDocShell* aDocShell,
nsIPrincipal** aPrincipal)
{
return GetCodebasePrincipalInternal(aURI,
aDocShell->GetAppId(),
aDocShell->GetIsInBrowserElement(),
aPrincipal);
}
nsresult
nsScriptSecurityManager::GetCodebasePrincipalInternal(nsIURI *aURI,
uint32_t aAppId,
bool aInMozBrowser,
nsIPrincipal **result)
{
NS_ENSURE_ARG(aURI);
bool inheritsPrincipal;
nsresult rv =
NS_URIChainHasFlags(aURI,
nsIProtocolHandler::URI_INHERITS_SECURITY_CONTEXT,
&inheritsPrincipal);
if (NS_FAILED(rv) || inheritsPrincipal) {
return CallCreateInstance(NS_NULLPRINCIPAL_CONTRACTID, result);
}
nsCOMPtr<nsIPrincipal> principal;
rv = CreateCodebasePrincipal(aURI, aAppId, aInMozBrowser,
getter_AddRefs(principal));
NS_ENSURE_SUCCESS(rv, rv);
NS_IF_ADDREF(*result = principal);
return NS_OK;
}
// static
nsIPrincipal*
nsScriptSecurityManager::GetScriptPrincipal(JSScript *script,
nsresult* rv)
{
NS_PRECONDITION(rv, "Null out param");
*rv = NS_OK;
if (!script)
{
return nullptr;
}
JSPrincipals *jsp = JS_GetScriptPrincipals(script);
if (!jsp) {
*rv = NS_ERROR_FAILURE;
NS_ERROR("Script compiled without principals!");
return nullptr;
}
return nsJSPrincipals::get(jsp);
}
// static
nsIPrincipal*
nsScriptSecurityManager::GetFunctionObjectPrincipal(JSContext *cx,
JS::Handle<JSObject*> obj,
nsresult *rv)
{
NS_PRECONDITION(rv, "Null out param");
*rv = NS_OK;
if (!JS_ObjectIsFunction(cx, obj))
{
// Protect against pseudo-functions (like SJOWs).
nsIPrincipal *result = doGetObjectPrincipal(obj);
if (!result)
*rv = NS_ERROR_FAILURE;
return result;
}
JS::Rooted<JSFunction*> fun(cx, JS_GetObjectFunction(obj));
JSScript *script = JS_GetFunctionScript(cx, fun);
if (!script)
{
// A native function: skip it in order to find its scripted caller.
return nullptr;
}
if (!js::IsOriginalScriptFunction(fun))
{
// Here, obj is a cloned function object. In this case, the
// clone's prototype may have been precompiled from brutally
// shared chrome, or else it is a lambda or nested function.
// The general case here is a function compiled against a
// different scope than the one it is parented by at runtime,
// hence the creation of a clone to carry the correct scope
// chain linkage.
//
// Since principals follow scope, we must get the object
// principal from the clone's scope chain. There are no
// reliable principals compiled into the function itself.
nsIPrincipal *result = doGetObjectPrincipal(obj);
if (!result)
*rv = NS_ERROR_FAILURE;
return result;
}
return GetScriptPrincipal(script, rv);
}
nsIPrincipal*
nsScriptSecurityManager::GetSubjectPrincipal(JSContext *cx,
nsresult* rv)
{
*rv = NS_OK;
JSCompartment *compartment = js::GetContextCompartment(cx);
// The context should always be in a compartment, either one it has entered
// or the one associated with its global.
MOZ_ASSERT(!!compartment);
JSPrincipals *principals = JS_GetCompartmentPrincipals(compartment);
return nsJSPrincipals::get(principals);
}
NS_IMETHODIMP
nsScriptSecurityManager::GetObjectPrincipal(JSContext *aCx, JSObject *aObj,
nsIPrincipal **result)
{
JS::Rooted<JSObject*> obj(aCx, aObj);
*result = doGetObjectPrincipal(obj);
if (!*result)
return NS_ERROR_FAILURE;
NS_ADDREF(*result);
return NS_OK;
}
// static
nsIPrincipal*
nsScriptSecurityManager::doGetObjectPrincipal(JS::Handle<JSObject*> aObj)
{
JSCompartment *compartment = js::GetObjectCompartment(aObj);
JSPrincipals *principals = JS_GetCompartmentPrincipals(compartment);
nsIPrincipal *principal = nsJSPrincipals::get(principals);
// We leave the old code in for a little while to make sure that pulling
// object principals directly off the compartment always gives an equivalent
// result (from a security perspective).
#ifdef DEBUG
nsIPrincipal *old = old_doGetObjectPrincipal(aObj);
MOZ_ASSERT(NS_SUCCEEDED(CheckSameOriginPrincipal(principal, old)));
#endif
return principal;
}
#ifdef DEBUG
// static
nsIPrincipal*
nsScriptSecurityManager::old_doGetObjectPrincipal(JS::Handle<JSObject*> aObj,
bool aAllowShortCircuit)
{
NS_ASSERTION(aObj, "Bad call to doGetObjectPrincipal()!");
nsIPrincipal* result = nullptr;
JSContext* cx = nsXPConnect::XPConnect()->GetCurrentJSContext();
JS::RootedObject obj(cx, aObj);
JS::RootedObject origObj(cx, obj);
js::Class *jsClass = js::GetObjectClass(obj);
// A common case seen in this code is that we enter this function
// with obj being a Function object, whose parent is a Call
// object. Neither of those have object principals, so we can skip
// those objects here before we enter the below loop. That way we
// avoid wasting time checking properties of their classes etc in
// the loop.
if (jsClass == &js::FunctionClass) {
obj = js::GetObjectParent(obj);
if (!obj)
return nullptr;
jsClass = js::GetObjectClass(obj);
if (jsClass == &js::CallClass) {
obj = js::GetObjectParentMaybeScope(obj);
if (!obj)
return nullptr;
jsClass = js::GetObjectClass(obj);
}
}
do {
// Note: jsClass is set before this loop, and also at the
// *end* of this loop.
if (IS_WRAPPER_CLASS(jsClass)) {
result = nsXPConnect::XPConnect()->GetPrincipal(obj,
aAllowShortCircuit);
if (result) {
break;
}
} else {
nsISupports *priv;
if (!(~jsClass->flags & (JSCLASS_HAS_PRIVATE |
JSCLASS_PRIVATE_IS_NSISUPPORTS))) {
priv = (nsISupports *) js::GetObjectPrivate(obj);
} else {
priv = UnwrapDOMObjectToISupports(obj);
}
if (aAllowShortCircuit) {
nsCOMPtr<nsIXPConnectWrappedNative> xpcWrapper =
do_QueryInterface(priv);
NS_ASSERTION(!xpcWrapper ||
!strcmp(jsClass->name, "XPCNativeWrapper"),
"Uh, an nsIXPConnectWrappedNative with the "
"wrong JSClass or getObjectOps hooks!");
}
nsCOMPtr<nsIScriptObjectPrincipal> objPrin =
do_QueryInterface(priv);
if (objPrin) {
result = objPrin->GetPrincipal();
if (result) {
break;
}
}
}
obj = js::GetObjectParentMaybeScope(obj);
if (!obj)
break;
jsClass = js::GetObjectClass(obj);
} while (1);
if (aAllowShortCircuit) {
nsIPrincipal *principal = old_doGetObjectPrincipal(origObj, false);
// Because of inner window reuse, we can have objects with one principal
// living in a scope with a different (but same-origin) principal. So
// just check same-origin here.
NS_ASSERTION(NS_SUCCEEDED(CheckSameOriginPrincipal(result, principal)),
"Principal mismatch. Not good");
}
return result;
}
#endif /* DEBUG */
////////////////////////////////////////////////
// Methods implementing nsIXPCSecurityManager //
////////////////////////////////////////////////
NS_IMETHODIMP
nsScriptSecurityManager::CanCreateWrapper(JSContext *cx,
const nsIID &aIID,
nsISupports *aObj,
nsIClassInfo *aClassInfo,
void **aPolicy)
{
// XXX Special case for nsIXPCException ?
ClassInfoData objClassInfo = ClassInfoData(aClassInfo, nullptr);
if (objClassInfo.IsDOMClass())
{
return NS_OK;
}
//--See if the object advertises a non-default level of access
// using nsISecurityCheckedComponent
nsCOMPtr<nsISecurityCheckedComponent> checkedComponent =
do_QueryInterface(aObj);
nsXPIDLCString objectSecurityLevel;
if (checkedComponent)
checkedComponent->CanCreateWrapper((nsIID *)&aIID, getter_Copies(objectSecurityLevel));
nsresult rv = CheckXPCPermissions(cx, aObj, nullptr, nullptr, objectSecurityLevel);
if (NS_FAILED(rv))
{
//-- Access denied, report an error
NS_ConvertUTF8toUTF16 strName("CreateWrapperDenied");
nsAutoCString origin;
nsresult rv2;
nsIPrincipal* subjectPrincipal = doGetSubjectPrincipal(&rv2);
if (NS_SUCCEEDED(rv2) && subjectPrincipal) {
GetPrincipalDomainOrigin(subjectPrincipal, origin);
}
NS_ConvertUTF8toUTF16 originUnicode(origin);
NS_ConvertUTF8toUTF16 className(objClassInfo.GetName());
const PRUnichar* formatStrings[] = {
className.get(),
originUnicode.get()
};
uint32_t length = ArrayLength(formatStrings);
if (originUnicode.IsEmpty()) {
--length;
} else {
strName.AppendLiteral("ForOrigin");
}
nsXPIDLString errorMsg;
// We need to keep our existing failure rv and not override it
// with a likely success code from the following string bundle
// call in order to throw the correct security exception later.
rv2 = sStrBundle->FormatStringFromName(strName.get(),
formatStrings,
length,
getter_Copies(errorMsg));
NS_ENSURE_SUCCESS(rv2, rv2);
SetPendingException(cx, errorMsg.get());
}
return rv;
}
NS_IMETHODIMP
nsScriptSecurityManager::CanCreateInstance(JSContext *cx,
const nsCID &aCID)
{
nsresult rv = CheckXPCPermissions(cx, nullptr, nullptr, nullptr, nullptr);
if (NS_FAILED(rv))
{
//-- Access denied, report an error
nsAutoCString errorMsg("Permission denied to create instance of class. CID=");
char cidStr[NSID_LENGTH];
aCID.ToProvidedString(cidStr);
errorMsg.Append(cidStr);
SetPendingException(cx, errorMsg.get());
}
return rv;
}
NS_IMETHODIMP
nsScriptSecurityManager::CanGetService(JSContext *cx,
const nsCID &aCID)
{
nsresult rv = CheckXPCPermissions(cx, nullptr, nullptr, nullptr, nullptr);
if (NS_FAILED(rv))
{
//-- Access denied, report an error
nsAutoCString errorMsg("Permission denied to get service. CID=");
char cidStr[NSID_LENGTH];
aCID.ToProvidedString(cidStr);
errorMsg.Append(cidStr);
SetPendingException(cx, errorMsg.get());
}
return rv;
}
NS_IMETHODIMP
nsScriptSecurityManager::CanAccess(uint32_t aAction,
nsAXPCNativeCallContext* aCallContext,
JSContext* cx,
JSObject* aJSObject,
nsISupports* aObj,
nsIClassInfo* aClassInfo,
jsid aPropertyName,
void** aPolicy)
{
return CheckPropertyAccessImpl(aAction, aCallContext, cx,
aJSObject, aObj, aClassInfo,
nullptr, aPropertyName, aPolicy);
}
nsresult
nsScriptSecurityManager::CheckXPCPermissions(JSContext* cx,
nsISupports* aObj, JSObject* aJSObject,
nsIPrincipal* aSubjectPrincipal,
const char* aObjectSecurityLevel)
{
MOZ_ASSERT(cx);
JS::RootedObject jsObject(cx, aJSObject);
// Check if the subject is privileged.
if (SubjectIsPrivileged())
return NS_OK;
//-- If the object implements nsISecurityCheckedComponent, it has a non-default policy.
if (aObjectSecurityLevel)
{
if (PL_strcasecmp(aObjectSecurityLevel, "allAccess") == 0)
return NS_OK;
if (cx && PL_strcasecmp(aObjectSecurityLevel, "sameOrigin") == 0)
{
nsresult rv;
if (!jsObject)
{
nsCOMPtr<nsIXPConnectWrappedJS> xpcwrappedjs =
do_QueryInterface(aObj);
if (xpcwrappedjs)
{
jsObject = xpcwrappedjs->GetJSObject();
NS_ENSURE_STATE(jsObject);
}
}
if (!aSubjectPrincipal)
{
// No subject principal passed in. Compute it.
aSubjectPrincipal = GetSubjectPrincipal(cx, &rv);
NS_ENSURE_SUCCESS(rv, rv);
}
if (aSubjectPrincipal && jsObject)
{
nsIPrincipal* objectPrincipal = doGetObjectPrincipal(jsObject);
// Only do anything if we have both a subject and object
// principal.
if (objectPrincipal)
{
bool subsumes;
rv = aSubjectPrincipal->Subsumes(objectPrincipal, &subsumes);
NS_ENSURE_SUCCESS(rv, rv);
if (subsumes)
return NS_OK;
}
}
}
else if (PL_strcasecmp(aObjectSecurityLevel, "noAccess") != 0)
{
if (SubjectIsPrivileged())
return NS_OK;
}
}
//-- Access tests failed
return NS_ERROR_DOM_XPCONNECT_ACCESS_DENIED;
}
/////////////////////////////////////////////
// Method implementing nsIChannelEventSink //
/////////////////////////////////////////////
NS_IMETHODIMP
nsScriptSecurityManager::AsyncOnChannelRedirect(nsIChannel* oldChannel,
nsIChannel* newChannel,
uint32_t redirFlags,
nsIAsyncVerifyRedirectCallback *cb)
{
nsCOMPtr<nsIPrincipal> oldPrincipal;
GetChannelPrincipal(oldChannel, getter_AddRefs(oldPrincipal));
nsCOMPtr<nsIURI> newURI;
newChannel->GetURI(getter_AddRefs(newURI));
nsCOMPtr<nsIURI> newOriginalURI;
newChannel->GetOriginalURI(getter_AddRefs(newOriginalURI));
NS_ENSURE_STATE(oldPrincipal && newURI && newOriginalURI);
const uint32_t flags =
nsIScriptSecurityManager::LOAD_IS_AUTOMATIC_DOCUMENT_REPLACEMENT |
nsIScriptSecurityManager::DISALLOW_SCRIPT;
nsresult rv = CheckLoadURIWithPrincipal(oldPrincipal, newURI, flags);
if (NS_SUCCEEDED(rv) && newOriginalURI != newURI) {
rv = CheckLoadURIWithPrincipal(oldPrincipal, newOriginalURI, flags);
}
if (NS_FAILED(rv))
return rv;
cb->OnRedirectVerifyCallback(NS_OK);
return NS_OK;
}
/////////////////////////////////////
// Method implementing nsIObserver //
/////////////////////////////////////
const char sJSEnabledPrefName[] = "javascript.enabled";
const char sFileOriginPolicyPrefName[] =
"security.fileuri.strict_origin_policy";
static const char sPolicyPrefix[] = "capability.policy.";
static const char* kObservedPrefs[] = {
sJSEnabledPrefName,
sFileOriginPolicyPrefName,
sPolicyPrefix,
nullptr
};
NS_IMETHODIMP
nsScriptSecurityManager::Observe(nsISupports* aObject, const char* aTopic,
const PRUnichar* aMessage)
{
nsresult rv = NS_OK;
NS_ConvertUTF16toUTF8 messageStr(aMessage);
const char *message = messageStr.get();
static const char jsPrefix[] = "javascript.";
static const char securityPrefix[] = "security.";
if ((PL_strncmp(message, jsPrefix, sizeof(jsPrefix)-1) == 0) ||
(PL_strncmp(message, securityPrefix, sizeof(securityPrefix)-1) == 0) )
{
ScriptSecurityPrefChanged();
}
else if (PL_strncmp(message, sPolicyPrefix, sizeof(sPolicyPrefix)-1) == 0)
{
// This will force re-initialization of the pref table
mPolicyPrefsChanged = true;
}
return rv;
}
/////////////////////////////////////////////
// Constructor, Destructor, Initialization //
/////////////////////////////////////////////
nsScriptSecurityManager::nsScriptSecurityManager(void)
: mOriginToPolicyMap(nullptr),
mDefaultPolicy(nullptr),
mCapabilities(nullptr),
mPrefInitialized(false),
mIsJavaScriptEnabled(false),
mPolicyPrefsChanged(true)
{
MOZ_STATIC_ASSERT(sizeof(intptr_t) == sizeof(void*),
"intptr_t and void* have different lengths on this platform. "
"This may cause a security failure with the SecurityLevel union.");
}
nsresult nsScriptSecurityManager::Init()
{
JSContext* cx = GetSafeJSContext();
if (!cx) return NS_ERROR_FAILURE; // this can happen of xpt loading fails
::JS_BeginRequest(cx);
if (sEnabledID == JSID_VOID)
sEnabledID = INTERNED_STRING_TO_JSID(cx, ::JS_InternString(cx, "enabled"));
::JS_EndRequest(cx);
InitPrefs();
nsresult rv = CallGetService(NS_IOSERVICE_CONTRACTID, &sIOService);
NS_ENSURE_SUCCESS(rv, rv);
nsCOMPtr<nsIStringBundleService> bundleService =
mozilla::services::GetStringBundleService();
if (!bundleService)
return NS_ERROR_FAILURE;
rv = bundleService->CreateBundle("chrome://global/locale/security/caps.properties", &sStrBundle);
NS_ENSURE_SUCCESS(rv, rv);
// Create our system principal singleton
nsRefPtr<nsSystemPrincipal> system = new nsSystemPrincipal();
NS_ENSURE_TRUE(system, NS_ERROR_OUT_OF_MEMORY);
mSystemPrincipal = system;
//-- Register security check callback in the JS engine
// Currently this is used to control access to function.caller
rv = nsXPConnect::XPConnect()->GetRuntime(&sRuntime);
NS_ENSURE_SUCCESS(rv, rv);
static const JSSecurityCallbacks securityCallbacks = {
CheckObjectAccess,
ContentSecurityPolicyPermitsJSAction
};
MOZ_ASSERT(!JS_GetSecurityCallbacks(sRuntime));
JS_SetSecurityCallbacks(sRuntime, &securityCallbacks);
JS_InitDestroyPrincipalsCallback(sRuntime, nsJSPrincipals::Destroy);
JS_SetTrustedPrincipals(sRuntime, system);
return NS_OK;
}
static StaticRefPtr<nsScriptSecurityManager> gScriptSecMan;
jsid nsScriptSecurityManager::sEnabledID = JSID_VOID;
nsScriptSecurityManager::~nsScriptSecurityManager(void)
{
Preferences::RemoveObservers(this, kObservedPrefs);
delete mOriginToPolicyMap;
if(mDefaultPolicy)
mDefaultPolicy->Drop();
delete mCapabilities;
}
void
nsScriptSecurityManager::Shutdown()
{
if (sRuntime) {
JS_SetSecurityCallbacks(sRuntime, nullptr);
JS_SetTrustedPrincipals(sRuntime, nullptr);
sRuntime = nullptr;
}
sEnabledID = JSID_VOID;
NS_IF_RELEASE(sIOService);
NS_IF_RELEASE(sStrBundle);
}
nsScriptSecurityManager *
nsScriptSecurityManager::GetScriptSecurityManager()
{
if (!gScriptSecMan)
{
nsRefPtr<nsScriptSecurityManager> ssManager = new nsScriptSecurityManager();
nsresult rv;
rv = ssManager->Init();
NS_ASSERTION(NS_SUCCEEDED(rv), "Failed to initialize nsScriptSecurityManager");
if (NS_FAILED(rv)) {
return nullptr;
}
rv = nsXPConnect::XPConnect()->
SetDefaultSecurityManager(ssManager,
nsIXPCSecurityManager::HOOK_ALL);
if (NS_FAILED(rv)) {
NS_WARNING("Failed to install xpconnect security manager!");
return nullptr;
}
ClearOnShutdown(&gScriptSecMan);
gScriptSecMan = ssManager;
}
return gScriptSecMan;
}
// Currently this nsGenericFactory constructor is used only from FastLoad
// (XPCOM object deserialization) code, when "creating" the system principal
// singleton.
nsSystemPrincipal *
nsScriptSecurityManager::SystemPrincipalSingletonConstructor()
{
nsIPrincipal *sysprin = nullptr;
if (gScriptSecMan)
NS_ADDREF(sysprin = gScriptSecMan->mSystemPrincipal);
return static_cast<nsSystemPrincipal*>(sysprin);
}
nsresult
nsScriptSecurityManager::InitPolicies()
{
// Clear any policies cached on XPConnect wrappers
nsresult rv =
nsXPConnect::XPConnect()->ClearAllWrappedNativeSecurityPolicies();
if (NS_FAILED(rv)) return rv;
//-- Clear mOriginToPolicyMap: delete mapped DomainEntry items,
//-- whose dtor decrements refcount of stored DomainPolicy object
delete mOriginToPolicyMap;
//-- Marks all the survivor DomainPolicy objects (those cached
//-- by nsPrincipal objects) as invalid: they will be released
//-- on first nsPrincipal::GetSecurityPolicy() attempt.
DomainPolicy::InvalidateAll();
//-- Release old default policy
if(mDefaultPolicy) {
mDefaultPolicy->Drop();
mDefaultPolicy = nullptr;
}
//-- Initialize a new mOriginToPolicyMap
mOriginToPolicyMap =
new nsObjectHashtable(nullptr, nullptr, DeleteDomainEntry, nullptr);
if (!mOriginToPolicyMap)
return NS_ERROR_OUT_OF_MEMORY;
//-- Create, refcount and initialize a new default policy
mDefaultPolicy = new DomainPolicy();
if (!mDefaultPolicy)
return NS_ERROR_OUT_OF_MEMORY;
mDefaultPolicy->Hold();
if (!mDefaultPolicy->Init())
return NS_ERROR_UNEXPECTED;
//-- Initialize the table of security levels
if (!mCapabilities)
{
mCapabilities =
new nsObjectHashtable(nullptr, nullptr, DeleteCapability, nullptr);
if (!mCapabilities)
return NS_ERROR_OUT_OF_MEMORY;
}
// Get a JS context - we need it to create internalized strings later.
AutoSafeJSContext cx;
rv = InitDomainPolicy(cx, "default", mDefaultPolicy);
NS_ENSURE_SUCCESS(rv, rv);
nsAdoptingCString policyNames =
Preferences::GetCString("capability.policy.policynames");
nsAdoptingCString defaultPolicyNames =
Preferences::GetCString("capability.policy.default_policynames");
policyNames += NS_LITERAL_CSTRING(" ") + defaultPolicyNames;
//-- Initialize domain policies
char* policyCurrent = policyNames.BeginWriting();
bool morePolicies = true;
while (morePolicies)
{
while(*policyCurrent == ' ' || *policyCurrent == ',')
policyCurrent++;
if (*policyCurrent == '\0')
break;
char* nameBegin = policyCurrent;
while(*policyCurrent != '\0' && *policyCurrent != ' ' && *policyCurrent != ',')
policyCurrent++;
morePolicies = (*policyCurrent != '\0');
*policyCurrent = '\0';
policyCurrent++;
nsAutoCString sitesPrefName(
NS_LITERAL_CSTRING(sPolicyPrefix) +
nsDependentCString(nameBegin) +
NS_LITERAL_CSTRING(".sites"));
nsAdoptingCString domainList =
Preferences::GetCString(sitesPrefName.get());
if (!domainList) {
continue;
}
DomainPolicy* domainPolicy = new DomainPolicy();
if (!domainPolicy)
return NS_ERROR_OUT_OF_MEMORY;
if (!domainPolicy->Init())
{
delete domainPolicy;
return NS_ERROR_UNEXPECTED;
}
domainPolicy->Hold();
//-- Parse list of sites and create an entry in mOriginToPolicyMap for each
char* domainStart = domainList.BeginWriting();
char* domainCurrent = domainStart;
char* lastDot = nullptr;
char* nextToLastDot = nullptr;
bool moreDomains = true;
while (moreDomains)
{
if (*domainCurrent == ' ' || *domainCurrent == '\0')
{
moreDomains = (*domainCurrent != '\0');
*domainCurrent = '\0';
nsCStringKey key(nextToLastDot ? nextToLastDot+1 : domainStart);
DomainEntry *newEntry = new DomainEntry(domainStart, domainPolicy);
if (!newEntry)
{
domainPolicy->Drop();
return NS_ERROR_OUT_OF_MEMORY;
}
DomainEntry *existingEntry = (DomainEntry *)
mOriginToPolicyMap->Get(&key);
if (!existingEntry)
mOriginToPolicyMap->Put(&key, newEntry);
else
{
if (existingEntry->Matches(domainStart))
{
newEntry->mNext = existingEntry;
mOriginToPolicyMap->Put(&key, newEntry);
}
else
{
while (existingEntry->mNext)
{
if (existingEntry->mNext->Matches(domainStart))
{
newEntry->mNext = existingEntry->mNext;
existingEntry->mNext = newEntry;
break;
}
existingEntry = existingEntry->mNext;
}
if (!existingEntry->mNext)
existingEntry->mNext = newEntry;
}
}
domainStart = domainCurrent + 1;
lastDot = nextToLastDot = nullptr;
}
else if (*domainCurrent == '.')
{
nextToLastDot = lastDot;
lastDot = domainCurrent;
}
domainCurrent++;
}
rv = InitDomainPolicy(cx, nameBegin, domainPolicy);
domainPolicy->Drop();
if (NS_FAILED(rv))
return rv;
}
// Reset the "dirty" flag
mPolicyPrefsChanged = false;
return NS_OK;
}
nsresult
nsScriptSecurityManager::InitDomainPolicy(JSContext* cx,
const char* aPolicyName,
DomainPolicy* aDomainPolicy)
{
nsresult rv;
nsAutoCString policyPrefix(NS_LITERAL_CSTRING(sPolicyPrefix) +
nsDependentCString(aPolicyName) +
NS_LITERAL_CSTRING("."));
uint32_t prefixLength = policyPrefix.Length() - 1; // subtract the '.'
uint32_t prefCount;
char** prefNames;
nsIPrefBranch* branch = Preferences::GetRootBranch();
NS_ASSERTION(branch, "failed to get the root pref branch");
rv = branch->GetChildList(policyPrefix.get(), &prefCount, &prefNames);
if (NS_FAILED(rv)) return rv;
if (prefCount == 0)
return NS_OK;
//-- Populate the policy
uint32_t currentPref = 0;
for (; currentPref < prefCount; currentPref++)
{
// Get the class name
const char* start = prefNames[currentPref] + prefixLength + 1;
char* end = PL_strchr(start, '.');
if (!end) // malformed pref, bail on this one
continue;
static const char sitesStr[] = "sites";
// We dealt with "sites" in InitPolicies(), so no need to do
// that again...
if (PL_strncmp(start, sitesStr, sizeof(sitesStr)-1) == 0)
continue;
// Get the pref value
nsAdoptingCString prefValue =
Preferences::GetCString(prefNames[currentPref]);
if (!prefValue) {
continue;
}
SecurityLevel secLevel;
if (PL_strcasecmp(prefValue, "noAccess") == 0)
secLevel.level = SCRIPT_SECURITY_NO_ACCESS;
else if (PL_strcasecmp(prefValue, "allAccess") == 0)
secLevel.level = SCRIPT_SECURITY_ALL_ACCESS;
else if (PL_strcasecmp(prefValue, "sameOrigin") == 0)
secLevel.level = SCRIPT_SECURITY_SAME_ORIGIN_ACCESS;
else
{ //-- pref value is the name of a capability
nsCStringKey secLevelKey(prefValue);
secLevel.capability =
reinterpret_cast<char*>(mCapabilities->Get(&secLevelKey));
if (!secLevel.capability)
{
secLevel.capability = NS_strdup(prefValue);
if (!secLevel.capability)
break;
mCapabilities->Put(&secLevelKey,
secLevel.capability);
}
}
*end = '\0';
// Find or store this class in the classes table
ClassPolicy* cpolicy =
static_cast<ClassPolicy*>
(PL_DHashTableOperate(aDomainPolicy, start,
PL_DHASH_ADD));
if (!cpolicy)
break;
// If this is the wildcard class (class '*'), save it in mWildcardPolicy
// (we leave it stored in the hashtable too to take care of the cleanup)
if ((*start == '*') && (end == start + 1)) {
aDomainPolicy->mWildcardPolicy = cpolicy;
// Make sure that cpolicy knows about aDomainPolicy so it can reset
// the mWildcardPolicy pointer as needed if it gets moved in the
// hashtable.
cpolicy->mDomainWeAreWildcardFor = aDomainPolicy;
}
// Get the property name
start = end + 1;
end = PL_strchr(start, '.');
if (end)
*end = '\0';
JSString* propertyKey = ::JS_InternString(cx, start);
if (!propertyKey)
return NS_ERROR_OUT_OF_MEMORY;
// Store this property in the class policy
PropertyPolicy* ppolicy =
static_cast<PropertyPolicy*>
(PL_DHashTableOperate(cpolicy->mPolicy, propertyKey,
PL_DHASH_ADD));
if (!ppolicy)
break;
if (end) // The pref specifies an access mode
{
start = end + 1;
if (PL_strcasecmp(start, "set") == 0)
ppolicy->mSet = secLevel;
else
ppolicy->mGet = secLevel;
}
else
{
if (ppolicy->mGet.level == SCRIPT_SECURITY_UNDEFINED_ACCESS)
ppolicy->mGet = secLevel;
if (ppolicy->mSet.level == SCRIPT_SECURITY_UNDEFINED_ACCESS)
ppolicy->mSet = secLevel;
}
}
NS_FREE_XPCOM_ALLOCATED_POINTER_ARRAY(prefCount, prefNames);
if (currentPref < prefCount) // Loop exited early because of out-of-memory error
return NS_ERROR_OUT_OF_MEMORY;
return NS_OK;
}
inline void
nsScriptSecurityManager::ScriptSecurityPrefChanged()
{
// JavaScript defaults to enabled in failure cases.
mIsJavaScriptEnabled = true;
sStrictFileOriginPolicy = true;
nsresult rv;
if (!mPrefInitialized) {
rv = InitPrefs();
if (NS_FAILED(rv))
return;
}
mIsJavaScriptEnabled =
Preferences::GetBool(sJSEnabledPrefName, mIsJavaScriptEnabled);
sStrictFileOriginPolicy =
Preferences::GetBool(sFileOriginPolicyPrefName, false);
}
nsresult
nsScriptSecurityManager::InitPrefs()
{
nsIPrefBranch* branch = Preferences::GetRootBranch();
NS_ENSURE_TRUE(branch, NS_ERROR_FAILURE);
mPrefInitialized = true;
// Set the initial value of the "javascript.enabled" prefs
ScriptSecurityPrefChanged();
// set observer callbacks in case the value of the prefs change
Preferences::AddStrongObservers(this, kObservedPrefs);
return NS_OK;
}
namespace mozilla {
void
GetExtendedOrigin(nsIURI* aURI, uint32_t aAppId, bool aInMozBrowser,
nsACString& aExtendedOrigin)
{
MOZ_ASSERT(aURI);
MOZ_ASSERT(aAppId != nsIScriptSecurityManager::UNKNOWN_APP_ID);
if (aAppId == nsIScriptSecurityManager::UNKNOWN_APP_ID) {
aAppId = nsIScriptSecurityManager::NO_APP_ID;
}
nsAutoCString origin;
nsPrincipal::GetOriginForURI(aURI, getter_Copies(origin));
// Fallback.
if (aAppId == nsIScriptSecurityManager::NO_APP_ID && !aInMozBrowser) {
aExtendedOrigin.Assign(origin);
return;
}
// aExtendedOrigin = appId + "+" + { 't', 'f' } "+" + origin;
aExtendedOrigin.Truncate();
aExtendedOrigin.AppendInt(aAppId);
aExtendedOrigin.Append('+');
aExtendedOrigin.Append(aInMozBrowser ? 't' : 'f');
aExtendedOrigin.Append('+');
aExtendedOrigin.Append(origin);
return;
}
} // namespace mozilla
NS_IMETHODIMP
nsScriptSecurityManager::GetExtendedOrigin(nsIURI* aURI,
uint32_t aAppId,
bool aInMozBrowser,
nsACString& aExtendedOrigin)
{
MOZ_ASSERT(aAppId != nsIScriptSecurityManager::UNKNOWN_APP_ID);
mozilla::GetExtendedOrigin(aURI, aAppId, aInMozBrowser, aExtendedOrigin);
return NS_OK;
}

Get latest updates about Open Source Projects, Conferences and News.

Sign up for the SourceForge newsletter:





No, thanks