summaryrefslogtreecommitdiff
path: root/Xext/security.c
blob: 488296f51d89cd801c9a80896697e5d36fef4ee8 (plain)
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
/* $XdotOrg: xc/programs/Xserver/Xext/security.c,v 1.2 2004/04/23 18:44:41 eich Exp $ */
/* $Xorg: security.c,v 1.4 2001/02/09 02:04:32 xorgcvs Exp $ */
/*

Copyright 1996, 1998  The Open Group

Permission to use, copy, modify, distribute, and sell this software and its
documentation for any purpose is hereby granted without fee, provided that
the above copyright notice appear in all copies and that both that
copyright notice and this permission notice appear in supporting
documentation.

The above copyright notice and this permission notice shall be included in
all copies or substantial portions of the Software.

THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR
IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY,
FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT.  IN NO EVENT SHALL THE
OPEN GROUP BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER LIABILITY, WHETHER IN
AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, OUT OF OR IN
CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE SOFTWARE.

Except as contained in this notice, the name of The Open Group shall not be
used in advertising or otherwise to promote the sale, use or other dealings
in this Software without prior written authorization from The Open Group.

*/
/* $XFree86: xc/programs/Xserver/Xext/security.c,v 1.16tsi Exp $ */

#include "dixstruct.h"
#include "extnsionst.h"
#include "windowstr.h"
#include "inputstr.h"
#include "scrnintstr.h"
#include "gcstruct.h"
#include "colormapst.h"
#include "propertyst.h"
#define _SECURITY_SERVER
#include "securstr.h"
#include <assert.h>
#include <stdarg.h>
#ifdef LBX
#define _XLBX_SERVER_
#include "XLbx.h"
extern unsigned char LbxReqCode;
#endif
#ifdef XAPPGROUP
#include "Xagsrv.h"
#endif
#include <stdio.h>  /* for file reading operations */
#include "Xatom.h"  /* for XA_STRING */

#ifndef DEFAULTPOLICYFILE
# define DEFAULTPOLICYFILE NULL
#endif
#if defined(WIN32) || defined(__CYGWIN__)
#include <X11/Xos.h>
#undef index
#endif

#include "modinit.h"

static int SecurityErrorBase;  /* first Security error number */
static int SecurityEventBase;  /* first Security event number */

CallbackListPtr SecurityValidateGroupCallback = NULL;  /* see security.h */

RESTYPE SecurityAuthorizationResType; /* resource type for authorizations */

static RESTYPE RTEventClient;

/* Proc vectors for untrusted clients, swapped and unswapped versions.
 * These are the same as the normal proc vectors except that extensions
 * that haven't declared themselves secure will have ProcBadRequest plugged
 * in for their major opcode dispatcher.  This prevents untrusted clients
 * from guessing extension major opcodes and using the extension even though
 * the extension can't be listed or queried.
 */
int (*UntrustedProcVector[256])(
    ClientPtr /*client*/
);
int (*SwappedUntrustedProcVector[256])(
    ClientPtr /*client*/
);

/* SecurityAudit
 *
 * Arguments:
 *	format is the formatting string to be used to interpret the
 *	  remaining arguments.
 *
 * Returns: nothing.
 *
 * Side Effects:
 *	Writes the message to the log file if security logging is on.
 */

void
SecurityAudit(char *format, ...)
{
    va_list args;

    if (auditTrailLevel < SECURITY_AUDIT_LEVEL)
	return;
    va_start(args, format);
    VAuditF(format, args);
    va_end(args);
} /* SecurityAudit */

#define rClient(obj) (clients[CLIENT_ID((obj)->resource)])

/* SecurityDeleteAuthorization
 *
 * Arguments:
 *	value is the authorization to delete.
 *	id is its resource ID.
 *
 * Returns: Success.
 *
 * Side Effects:
 *	Frees everything associated with the authorization.
 */

static int
SecurityDeleteAuthorization(
    pointer value,
    XID id)
{
    SecurityAuthorizationPtr pAuth = (SecurityAuthorizationPtr)value;
    unsigned short name_len, data_len;
    char *name, *data;
    int status;
    int i;
    OtherClientsPtr pEventClient;

    /* Remove the auth using the os layer auth manager */

    status = AuthorizationFromID(pAuth->id, &name_len, &name,
				 &data_len, &data);
    assert(status);
    status = RemoveAuthorization(name_len, name, data_len, data);
    assert(status);
    (void)status;

    /* free the auth timer if there is one */

    if (pAuth->timer) TimerFree(pAuth->timer);

    /* send revoke events */

    while ((pEventClient = pAuth->eventClients))
    {
	/* send revocation event event */
	ClientPtr client = rClient(pEventClient);

	if (!client->clientGone)
	{
	    xSecurityAuthorizationRevokedEvent are;
	    are.type = SecurityEventBase + XSecurityAuthorizationRevoked;
	    are.sequenceNumber = client->sequence;
	    are.authId = pAuth->id;
	    WriteEventsToClient(client, 1, (xEvent *)&are);
	}
	FreeResource(pEventClient->resource, RT_NONE);
    }

    /* kill all clients using this auth */

    for (i = 1; i<currentMaxClients; i++)
    {
	if (clients[i] && (clients[i]->authId == pAuth->id))
	    CloseDownClient(clients[i]);
    }

    SecurityAudit("revoked authorization ID %d\n", pAuth->id);
    xfree(pAuth);
    return Success;

} /* SecurityDeleteAuthorization */


/* resource delete function for RTEventClient */
static int
SecurityDeleteAuthorizationEventClient(
    pointer value,
    XID id)
{
    OtherClientsPtr pEventClient, prev = NULL;
    SecurityAuthorizationPtr pAuth = (SecurityAuthorizationPtr)value;

    for (pEventClient = pAuth->eventClients;
	 pEventClient;
	 pEventClient = pEventClient->next)
    {
	if (pEventClient->resource == id)
	{
	    if (prev)
		prev->next = pEventClient->next;
	    else
		pAuth->eventClients = pEventClient->next;
	    xfree(pEventClient);
	    return(Success);
	}
	prev = pEventClient;
    }
    /*NOTREACHED*/
    return -1; /* make compiler happy */
} /* SecurityDeleteAuthorizationEventClient */


/* SecurityComputeAuthorizationTimeout
 *
 * Arguments:
 *	pAuth is the authorization for which we are computing the timeout
 *	seconds is the number of seconds we want to wait
 *
 * Returns:
 *	the number of milliseconds that the auth timer should be set to
 *
 * Side Effects:
 *	Sets pAuth->secondsRemaining to any "overflow" amount of time
 *	that didn't fit in 32 bits worth of milliseconds
 */

static CARD32
SecurityComputeAuthorizationTimeout(
    SecurityAuthorizationPtr pAuth,
    unsigned int seconds)
{
    /* maxSecs is the number of full seconds that can be expressed in
     * 32 bits worth of milliseconds
     */
    CARD32 maxSecs = (CARD32)(~0) / (CARD32)MILLI_PER_SECOND;

    if (seconds > maxSecs)
    { /* only come here if we want to wait more than 49 days */
	pAuth->secondsRemaining = seconds - maxSecs;
	return maxSecs * MILLI_PER_SECOND;
    }
    else
    { /* by far the common case */
	pAuth->secondsRemaining = 0;
	return seconds * MILLI_PER_SECOND;
    }
} /* SecurityStartAuthorizationTimer */

/* SecurityAuthorizationExpired
 *
 * This function is passed as an argument to TimerSet and gets called from
 * the timer manager in the os layer when its time is up.
 *
 * Arguments:
 *	timer is the timer for this authorization.
 *	time is the current time.
 *	pval is the authorization whose time is up.
 *
 * Returns:
 *	A new time delay in milliseconds if the timer should wait some
 *	more, else zero.
 *
 * Side Effects:
 *	Frees the authorization resource if the timeout period is really
 *	over, otherwise recomputes pAuth->secondsRemaining.
 */

static CARD32
SecurityAuthorizationExpired(
    OsTimerPtr timer,
    CARD32 time,
    pointer pval)
{
    SecurityAuthorizationPtr pAuth = (SecurityAuthorizationPtr)pval;

    assert(pAuth->timer == timer);

    if (pAuth->secondsRemaining)
    {
	return SecurityComputeAuthorizationTimeout(pAuth,
						   pAuth->secondsRemaining);
    }
    else
    {
	FreeResource(pAuth->id, RT_NONE);
	return 0;
    }
} /* SecurityAuthorizationExpired */

/* SecurityStartAuthorizationTimer
 *
 * Arguments:
 *	pAuth is the authorization whose timer should be started.
 *
 * Returns: nothing.
 *
 * Side Effects:
 *	A timer is started, set to expire after the timeout period for
 *	this authorization.  When it expires, the function
 *	SecurityAuthorizationExpired will be called.
 */

static void
SecurityStartAuthorizationTimer(
    SecurityAuthorizationPtr pAuth)
{
    pAuth->timer = TimerSet(pAuth->timer, 0,
	SecurityComputeAuthorizationTimeout(pAuth, pAuth->timeout),
			    SecurityAuthorizationExpired, pAuth);
} /* SecurityStartAuthorizationTimer */


/* Proc functions all take a client argument, execute the request in
 * client->requestBuffer, and return a protocol error status.
 */

static int
ProcSecurityQueryVersion(
    ClientPtr client)
{
    /* REQUEST(xSecurityQueryVersionReq); */
    xSecurityQueryVersionReply 	rep;

    /* paranoia: this "can't happen" because this extension is hidden
     * from untrusted clients, but just in case...
     */
    if (client->trustLevel != XSecurityClientTrusted)
	return BadRequest;

    REQUEST_SIZE_MATCH(xSecurityQueryVersionReq);
    rep.type        	= X_Reply;
    rep.sequenceNumber 	= client->sequence;
    rep.length         	= 0;
    rep.majorVersion  	= SECURITY_MAJOR_VERSION;
    rep.minorVersion  	= SECURITY_MINOR_VERSION;
    if(client->swapped)
    {
	register char n;
    	swaps(&rep.sequenceNumber, n);
	swaps(&rep.majorVersion, n);
	swaps(&rep.minorVersion, n);
    }
    (void)WriteToClient(client, SIZEOF(xSecurityQueryVersionReply),
			(char *)&rep);
    return (client->noClientException);
} /* ProcSecurityQueryVersion */


static int
SecurityEventSelectForAuthorization(
    SecurityAuthorizationPtr pAuth,
    ClientPtr client,
    Mask mask)
{
    OtherClients *pEventClient;

    for (pEventClient = pAuth->eventClients;
	 pEventClient;
	 pEventClient = pEventClient->next)
    {
	if (SameClient(pEventClient, client))
	{
	    if (mask == 0)
		FreeResource(pEventClient->resource, RT_NONE);
	    else
		pEventClient->mask = mask;
	    return Success;
	}
    }
    
    pEventClient = (OtherClients *) xalloc(sizeof(OtherClients));
    if (!pEventClient)
	return BadAlloc;
    pEventClient->mask = mask;
    pEventClient->resource = FakeClientID(client->index);
    pEventClient->next = pAuth->eventClients;
    if (!AddResource(pEventClient->resource, RTEventClient,
		     (pointer)pAuth))
    {
	xfree(pEventClient);
	return BadAlloc;
    }
    pAuth->eventClients = pEventClient;

    return Success;
} /* SecurityEventSelectForAuthorization */


static int
ProcSecurityGenerateAuthorization(
    ClientPtr client)
{
    REQUEST(xSecurityGenerateAuthorizationReq);
    int len;			/* request length in CARD32s*/
    Bool removeAuth = FALSE;	/* if bailout, call RemoveAuthorization? */
    SecurityAuthorizationPtr pAuth = NULL;  /* auth we are creating */
    int err;			/* error to return from this function */
    XID authId;			/* authorization ID assigned by os layer */
    xSecurityGenerateAuthorizationReply rep; /* reply struct */
    unsigned int trustLevel;    /* trust level of new auth */
    XID group;			/* group of new auth */
    CARD32 timeout;		/* timeout of new auth */
    CARD32 *values;		/* list of supplied attributes */
    char *protoname;		/* auth proto name sent in request */
    char *protodata;		/* auth proto data sent in request */
    unsigned int authdata_len;  /* # bytes of generated auth data */
    char *pAuthdata;		/* generated auth data */
    Mask eventMask;		/* what events on this auth does client want */

    /* paranoia: this "can't happen" because this extension is hidden
     * from untrusted clients, but just in case...
     */
    if (client->trustLevel != XSecurityClientTrusted)
	return BadRequest;

    /* check request length */

    REQUEST_AT_LEAST_SIZE(xSecurityGenerateAuthorizationReq);
    len = SIZEOF(xSecurityGenerateAuthorizationReq) >> 2;
    len += (stuff->nbytesAuthProto + (unsigned)3) >> 2;
    len += (stuff->nbytesAuthData  + (unsigned)3) >> 2;
    values = ((CARD32 *)stuff) + len;
    len += Ones(stuff->valueMask);
    if (client->req_len != len)
	return BadLength;

    /* check valuemask */
    if (stuff->valueMask & ~XSecurityAllAuthorizationAttributes)
    {
	client->errorValue = stuff->valueMask;
	return BadValue;
    }

    /* check timeout */
    timeout = 60;
    if (stuff->valueMask & XSecurityTimeout)
    {
	timeout = *values++;
    }

    /* check trustLevel */
    trustLevel = XSecurityClientUntrusted;
    if (stuff->valueMask & XSecurityTrustLevel)
    {
	trustLevel = *values++;
	if (trustLevel != XSecurityClientTrusted &&
	    trustLevel != XSecurityClientUntrusted)
	{
	    client->errorValue = trustLevel;
	    return BadValue;
	}
    }

    /* check group */
    group = None;
    if (stuff->valueMask & XSecurityGroup)
    {
	group = *values++;
	if (SecurityValidateGroupCallback)
	{
	    SecurityValidateGroupInfoRec vgi;
	    vgi.group = group;
	    vgi.valid = FALSE;
	    CallCallbacks(&SecurityValidateGroupCallback, (pointer)&vgi);

	    /* if nobody said they recognized it, it's an error */

	    if (!vgi.valid)
	    {
		client->errorValue = group;
		return BadValue;
	    }
	}
    }

    /* check event mask */
    eventMask = 0;
    if (stuff->valueMask & XSecurityEventMask)
    {
	eventMask = *values++;
	if (eventMask & ~XSecurityAllEventMasks)
	{
	    client->errorValue = eventMask;
	    return BadValue;
	}
    }

    protoname = (char *)&stuff[1];
    protodata = protoname + ((stuff->nbytesAuthProto + (unsigned)3) >> 2);

    /* call os layer to generate the authorization */

    authId = GenerateAuthorization(stuff->nbytesAuthProto, protoname,
				   stuff->nbytesAuthData,  protodata,
				   &authdata_len, &pAuthdata);
    if ((XID) ~0L == authId)
    {
	err = SecurityErrorBase + XSecurityBadAuthorizationProtocol;
	goto bailout;
    }

    /* now that we've added the auth, remember to remove it if we have to
     * abort the request for some reason (like allocation failure)
     */
    removeAuth = TRUE;

    /* associate additional information with this auth ID */

    pAuth = (SecurityAuthorizationPtr)xalloc(sizeof(SecurityAuthorizationRec));
    if (!pAuth)
    {
	err = BadAlloc;
	goto bailout;
    }

    /* fill in the auth fields */

    pAuth->id = authId;
    pAuth->timeout = timeout;
    pAuth->group = group;
    pAuth->trustLevel = trustLevel;
    pAuth->refcnt = 0;	/* the auth was just created; nobody's using it yet */
    pAuth->secondsRemaining = 0;
    pAuth->timer = NULL;
    pAuth->eventClients = NULL;

    /* handle event selection */
    if (eventMask)
    {
	err = SecurityEventSelectForAuthorization(pAuth, client, eventMask);
	if (err != Success)
	    goto bailout;
    }

    if (!AddResource(authId, SecurityAuthorizationResType, pAuth))
    {
	err = BadAlloc;
	goto bailout;
    }

    /* start the timer ticking */

    if (pAuth->timeout != 0)
	SecurityStartAuthorizationTimer(pAuth);

    /* tell client the auth id and data */

    rep.type = X_Reply;
    rep.length = (authdata_len + 3) >> 2;
    rep.sequenceNumber = client->sequence;
    rep.authId = authId;
    rep.dataLength = authdata_len;

    if (client->swapped)
    {
	register char n;
    	swapl(&rep.length, n);
    	swaps(&rep.sequenceNumber, n);
    	swapl(&rep.authId, n);
    	swaps(&rep.dataLength, n);
    }

    WriteToClient(client, SIZEOF(xSecurityGenerateAuthorizationReply),
		  (char *)&rep);
    WriteToClient(client, authdata_len, pAuthdata);

    SecurityAudit("client %d generated authorization %d trust %d timeout %d group %d events %d\n",
		  client->index, pAuth->id, pAuth->trustLevel, pAuth->timeout,
		  pAuth->group, eventMask);

    /* the request succeeded; don't call RemoveAuthorization or free pAuth */

    removeAuth = FALSE;
    pAuth = NULL;
    err = client->noClientException;

bailout:
    if (removeAuth)
	RemoveAuthorization(stuff->nbytesAuthProto, protoname,
			    authdata_len, pAuthdata);
    if (pAuth) xfree(pAuth);
    return err;

} /* ProcSecurityGenerateAuthorization */

static int
ProcSecurityRevokeAuthorization(
    ClientPtr client)
{
    REQUEST(xSecurityRevokeAuthorizationReq);
    SecurityAuthorizationPtr pAuth;

    /* paranoia: this "can't happen" because this extension is hidden
     * from untrusted clients, but just in case...
     */
    if (client->trustLevel != XSecurityClientTrusted)
	return BadRequest;

    REQUEST_SIZE_MATCH(xSecurityRevokeAuthorizationReq);

    pAuth = (SecurityAuthorizationPtr)SecurityLookupIDByType(client,
	stuff->authId, SecurityAuthorizationResType, SecurityDestroyAccess);
    if (!pAuth)
	return SecurityErrorBase + XSecurityBadAuthorization;

    FreeResource(stuff->authId, RT_NONE);
    return Success;
} /* ProcSecurityRevokeAuthorization */


static int
ProcSecurityDispatch(
    ClientPtr client)
{
    REQUEST(xReq);

    switch (stuff->data)
    {
	case X_SecurityQueryVersion:
	    return ProcSecurityQueryVersion(client);
	case X_SecurityGenerateAuthorization:
	    return ProcSecurityGenerateAuthorization(client);
	case X_SecurityRevokeAuthorization:
	    return ProcSecurityRevokeAuthorization(client);
	default:
	    return BadRequest;
    }
} /* ProcSecurityDispatch */

static int
SProcSecurityQueryVersion(
    ClientPtr client)
{
    REQUEST(xSecurityQueryVersionReq);
    register char 	n;

    swaps(&stuff->length, n);
    REQUEST_SIZE_MATCH(xSecurityQueryVersionReq);
    swaps(&stuff->majorVersion, n);
    swaps(&stuff->minorVersion,n);
    return ProcSecurityQueryVersion(client);
} /* SProcSecurityQueryVersion */


static int
SProcSecurityGenerateAuthorization(
    ClientPtr client)
{
    REQUEST(xSecurityGenerateAuthorizationReq);
    register char 	n;
    CARD32 *values;
    unsigned long nvalues;

    swaps(&stuff->length, n);
    REQUEST_AT_LEAST_SIZE(xSecurityGenerateAuthorizationReq);
    swaps(&stuff->nbytesAuthProto, n);
    swaps(&stuff->nbytesAuthData, n);
    swapl(&stuff->valueMask, n);
    values = (CARD32 *)(&stuff[1]) +
	((stuff->nbytesAuthProto + (unsigned)3) >> 2) +
	((stuff->nbytesAuthData + (unsigned)3) >> 2);
    nvalues = (((CARD32 *)stuff) + stuff->length) - values;
    SwapLongs(values, nvalues);
    return ProcSecurityGenerateAuthorization(client);
} /* SProcSecurityGenerateAuthorization */


static int
SProcSecurityRevokeAuthorization(
    ClientPtr client)
{
    REQUEST(xSecurityRevokeAuthorizationReq);
    register char 	n;

    swaps(&stuff->length, n);
    REQUEST_SIZE_MATCH(xSecurityRevokeAuthorizationReq);
    swapl(&stuff->authId, n);
    return ProcSecurityRevokeAuthorization(client);
} /* SProcSecurityRevokeAuthorization */


static int
SProcSecurityDispatch(
    ClientPtr client)
{
    REQUEST(xReq);

    switch (stuff->data)
    {
	case X_SecurityQueryVersion:
	    return SProcSecurityQueryVersion(client);
	case X_SecurityGenerateAuthorization:
	    return SProcSecurityGenerateAuthorization(client);
	case X_SecurityRevokeAuthorization:
	    return SProcSecurityRevokeAuthorization(client);
	default:
	    return BadRequest;
    }
} /* SProcSecurityDispatch */

static void 
SwapSecurityAuthorizationRevokedEvent(
    xSecurityAuthorizationRevokedEvent *from,
    xSecurityAuthorizationRevokedEvent *to)
{
    to->type = from->type;
    to->detail = from->detail;
    cpswaps(from->sequenceNumber, to->sequenceNumber);
    cpswapl(from->authId, to->authId);
}

/* SecurityDetermineEventPropogationLimits
 *
 * This is a helper function for SecurityCheckDeviceAccess.
 *
 * Arguments:
 *	dev is the device for which the starting and stopping windows for
 *	event propogation should be determined.
 *	The values pointed to by ppWin and ppStopWin are not used.
 *
 * Returns:
 *	ppWin is filled in with a pointer to the window at which event
 *	propogation for the given device should start given the current
 *	state of the server (pointer position, window layout, etc.)
 *	ppStopWin is filled in with the window at which event propogation
 *	should stop; events should not go to ppStopWin.
 *
 * Side Effects: none.
 */

static void
SecurityDetermineEventPropogationLimits(
    DeviceIntPtr dev,
    WindowPtr *ppWin,
    WindowPtr *ppStopWin)
{
    WindowPtr pFocusWin = dev->focus ? dev->focus->win : NoneWin;

    if (pFocusWin == NoneWin)
    { /* no focus -- events don't go anywhere */
	*ppWin = *ppStopWin = NULL;
	return;
    }

    if (pFocusWin == PointerRootWin)
    { /* focus follows the pointer */
	*ppWin = GetSpriteWindow();
	*ppStopWin = NULL; /* propogate all the way to the root */
    }
    else
    { /* a real window is set for the focus */
	WindowPtr pSpriteWin = GetSpriteWindow();
	*ppStopWin = pFocusWin->parent; /* don't go past the focus window */

	/* if the pointer is in a subwindow of the focus window, start
	 * at that subwindow, else start at the focus window itself
	 */
	if (IsParent(pFocusWin, pSpriteWin))
	     *ppWin = pSpriteWin;
	else *ppWin = pFocusWin;
    }
} /* SecurityDetermineEventPropogationLimits */


/* SecurityCheckDeviceAccess
 *
 * Arguments:
 *	client is the client attempting to access a device.
 *	dev is the device being accessed.
 *	fromRequest is TRUE if the device access is a direct result of
 *	  the client executing some request and FALSE if it is a
 *	  result of the server trying to send an event (e.g. KeymapNotify)
 *	  to the client.
 * Returns:
 *	TRUE if the device access should be allowed, else FALSE.
 *
 * Side Effects:
 *	An audit message is generated if access is denied.
 */

Bool
SecurityCheckDeviceAccess(client, dev, fromRequest)
    ClientPtr client;
    DeviceIntPtr dev;
    Bool fromRequest;
{
    WindowPtr pWin, pStopWin;
    Bool untrusted_got_event;
    Bool found_event_window;
    Mask eventmask;
    int reqtype = 0;

    /* trusted clients always allowed to do anything */
    if (client->trustLevel == XSecurityClientTrusted)
	return TRUE;

    /* device security other than keyboard is not implemented yet */
    if (dev != inputInfo.keyboard)
	return TRUE;

    /* some untrusted client wants access */

    if (fromRequest)
    {
	reqtype = ((xReq *)client->requestBuffer)->reqType;
	switch (reqtype)
	{
	    /* never allow these */
	    case X_ChangeKeyboardMapping:
	    case X_ChangeKeyboardControl:
	    case X_SetModifierMapping:
		SecurityAudit("client %d attempted request %d\n",
			      client->index, reqtype);
		return FALSE;
	    default:
		break;
	}
    }

    untrusted_got_event = FALSE;
    found_event_window = FALSE;

    if (dev->grab)
    {
	untrusted_got_event =
	    ((rClient(dev->grab))->trustLevel != XSecurityClientTrusted);
    }
    else
    {
	SecurityDetermineEventPropogationLimits(dev, &pWin, &pStopWin);

	eventmask = KeyPressMask | KeyReleaseMask;
	while ( (pWin != pStopWin) && !found_event_window)
	{
	    OtherClients *other;

	    if (pWin->eventMask & eventmask)
	    {
		found_event_window = TRUE;
		client = wClient(pWin);
		if (client->trustLevel != XSecurityClientTrusted)
		{
		    untrusted_got_event = TRUE;
		}
	    }
	    if (wOtherEventMasks(pWin) & eventmask)
	    {
		found_event_window = TRUE;
		for (other = wOtherClients(pWin); other; other = other->next)
		{
		    if (other->mask & eventmask)
		    {
			client = rClient(other);
			if (client->trustLevel != XSecurityClientTrusted)
			{
			    untrusted_got_event = TRUE;
			    break;
			}
		    }
		}
	    }
	    if (wDontPropagateMask(pWin) & eventmask)
		break;
	    pWin = pWin->parent;
	} /* while propogating the event */
    }

    /* allow access by untrusted clients only if an event would have gone 
     * to an untrusted client
     */
    
    if (!untrusted_got_event)
    {
	char *devname = dev->name;
	if (!devname) devname = "unnamed";
	if (fromRequest)
	    SecurityAudit("client %d attempted request %d device %d (%s)\n",
			  client->index, reqtype, dev->id, devname);
	else
	    SecurityAudit("client %d attempted to access device %d (%s)\n",
			  client->index, dev->id, devname);
    }
    return untrusted_got_event;
} /* SecurityCheckDeviceAccess */



/* SecurityAuditResourceIDAccess
 *
 * Arguments:
 *	client is the client doing the resource access.
 *	id is the resource id.
 *
 * Returns: NULL
 *
 * Side Effects:
 *	An audit message is generated with details of the denied
 *	resource access.
 */

static pointer
SecurityAuditResourceIDAccess(
    ClientPtr client,
    XID id)
{
    int cid = CLIENT_ID(id);
    int reqtype = ((xReq *)client->requestBuffer)->reqType;
    switch (reqtype)
    {
	case X_ChangeProperty:
	case X_DeleteProperty:
	case X_GetProperty:
	{
	    xChangePropertyReq *req =
		(xChangePropertyReq *)client->requestBuffer;
	    int propertyatom = req->property;
	    char *propertyname = NameForAtom(propertyatom);

	    SecurityAudit("client %d attempted request %d with window 0x%x property %s of client %d\n",
		   client->index, reqtype, id, propertyname, cid);
	    break;
	}
	default:
	{
	    SecurityAudit("client %d attempted request %d with resource 0x%x of client %d\n",
		   client->index, reqtype, id, cid);
	    break;
	}   
    }
    return NULL;
} /* SecurityAuditResourceIDAccess */


/* SecurityCheckResourceIDAccess
 *
 * This function gets plugged into client->CheckAccess and is called from
 * SecurityLookupIDByType/Class to determine if the client can access the
 * resource.
 *
 * Arguments:
 *	client is the client doing the resource access.
 *	id is the resource id.
 *	rtype is its type or class.
 *	access_mode represents the intended use of the resource; see
 *	  resource.h.
 *	rval is a pointer to the resource structure for this resource.
 *
 * Returns:
 *	If access is granted, the value of rval that was passed in, else NULL.
 *
 * Side Effects:
 *	Disallowed resource accesses are audited.
 */

static pointer
SecurityCheckResourceIDAccess(
    ClientPtr client,
    XID id,
    RESTYPE rtype,
    Mask access_mode,
    pointer rval)
{
    int cid = CLIENT_ID(id);
    int reqtype = ((xReq *)client->requestBuffer)->reqType;

    if (SecurityUnknownAccess == access_mode)
	return rval;  /* for compatibility, we have to allow access */

    switch (reqtype)
    { /* these are always allowed */
	case X_QueryTree:
        case X_TranslateCoords:
        case X_GetGeometry:
	/* property access is controlled in SecurityCheckPropertyAccess */
	case X_GetProperty:
	case X_ChangeProperty:
	case X_DeleteProperty:
	case X_RotateProperties:
        case X_ListProperties:
	    return rval;
	default:
	    break;
    }

    if (cid != 0)
    { /* not a server-owned resource */
     /*
      * The following 'if' restricts clients to only access resources at
      * the same trustLevel.  Since there are currently only two trust levels,
      * and trusted clients never call this function, this degenerates into
      * saying that untrusted clients can only access resources of other
      * untrusted clients.  One way to add the notion of groups would be to
      * allow values other than Trusted (0) and Untrusted (1) for this field.
      * Clients at the same trust level would be able to use each other's
      * resources, but not those of clients at other trust levels.  I haven't
      * tried it, but this probably mostly works already.  The obvious
      * competing alternative for grouping clients for security purposes is to
      * use app groups.  dpw
      */
	if (client->trustLevel == clients[cid]->trustLevel
#ifdef XAPPGROUP
	    || (RT_COLORMAP == rtype && 
		XagDefaultColormap (client) == (Colormap) id)
#endif
	)
	    return rval;
	else
	    return SecurityAuditResourceIDAccess(client, id);
    }
    else /* server-owned resource - probably a default colormap or root window */
    {
	if (RT_WINDOW == rtype || RC_DRAWABLE == rtype)
	{
	    switch (reqtype)
	    {   /* the following operations are allowed on root windows */
	        case X_CreatePixmap:
	        case X_CreateGC:
	        case X_CreateWindow:
	        case X_CreateColormap:
		case X_ListProperties:
		case X_GrabPointer:
	        case X_UngrabButton:
		case X_QueryBestSize:
		case X_GetWindowAttributes:
		    break;
		case X_SendEvent:
		{ /* see if it is an event specified by the ICCCM */
		    xSendEventReq *req = (xSendEventReq *)
						(client->requestBuffer);
		    if (req->propagate == xTrue
			||
			  (req->eventMask != ColormapChangeMask &&
			   req->eventMask != StructureNotifyMask &&
			   req->eventMask !=
			      (SubstructureRedirectMask|SubstructureNotifyMask)
			  )
			||
			  (req->event.u.u.type != UnmapNotify &&
			   req->event.u.u.type != ConfigureRequest &&
			   req->event.u.u.type != ClientMessage
			  )
		       )
		    { /* not an ICCCM event */
			return SecurityAuditResourceIDAccess(client, id);
		    }
		    break;
		} /* case X_SendEvent on root */

		case X_ChangeWindowAttributes:
		{ /* Allow selection of PropertyNotify and StructureNotify
		   * events on the root.
		   */
		    xChangeWindowAttributesReq *req =
			(xChangeWindowAttributesReq *)(client->requestBuffer);
		    if (req->valueMask == CWEventMask)
		    {
			CARD32 value = *((CARD32 *)(req + 1));
			if ( (value &
			      ~(PropertyChangeMask|StructureNotifyMask)) == 0)
			    break;
		    }
		    return SecurityAuditResourceIDAccess(client, id);
		} /* case X_ChangeWindowAttributes on root */

		default:
		{
#ifdef LBX
		    /* XXX really need per extension dispatching */
		    if (reqtype == LbxReqCode) {
			switch (((xReq *)client->requestBuffer)->data) {
			case X_LbxGetProperty:
			case X_LbxChangeProperty:
			    return rval;
			default:
			    break;
			}
		    }
#endif
		    /* others not allowed */
		    return SecurityAuditResourceIDAccess(client, id);
		}
	    }
	} /* end server-owned window or drawable */
	else if (SecurityAuthorizationResType == rtype)
	{
	    SecurityAuthorizationPtr pAuth = (SecurityAuthorizationPtr)rval;
	    if (pAuth->trustLevel != client->trustLevel)
		return SecurityAuditResourceIDAccess(client, id);
	}
	else if (RT_COLORMAP != rtype)
	{ /* don't allow anything else besides colormaps */
	    return SecurityAuditResourceIDAccess(client, id);
	}
    }
    return rval;
} /* SecurityCheckResourceIDAccess */


/* SecurityClientStateCallback
 *
 * Arguments:
 *	pcbl is &ClientStateCallback.
 *	nullata is NULL.
 *	calldata is a pointer to a NewClientInfoRec (include/dixstruct.h)
 *	which contains information about client state changes.
 *
 * Returns: nothing.
 *
 * Side Effects:
 * 
 * If a new client is connecting, its authorization ID is copied to
 * client->authID.  If this is a generated authorization, its reference
 * count is bumped, its timer is cancelled if it was running, and its
 * trustlevel is copied to client->trustLevel.
 * 
 * If a client is disconnecting and the client was using a generated
 * authorization, the authorization's reference count is decremented, and
 * if it is now zero, the timer for this authorization is started.
 */

static void
SecurityClientStateCallback(
    CallbackListPtr *pcbl,
    pointer nulldata,
    pointer calldata)
{
    NewClientInfoRec *pci = (NewClientInfoRec *)calldata;
    ClientPtr client = pci->client;

    switch (client->clientState)
    {
	case ClientStateRunning:
	{ 
	    XID authId = AuthorizationIDOfClient(client);
	    SecurityAuthorizationPtr pAuth;

	    client->authId = authId;
	    pAuth = (SecurityAuthorizationPtr)LookupIDByType(authId,
						SecurityAuthorizationResType);
	    if (pAuth)
	    { /* it is a generated authorization */
		pAuth->refcnt++;
		if (pAuth->refcnt == 1)
		{
		    if (pAuth->timer) TimerCancel(pAuth->timer);
		}
		client->trustLevel = pAuth->trustLevel;
		if (client->trustLevel != XSecurityClientTrusted)
		{
		    client->CheckAccess = SecurityCheckResourceIDAccess;
		    client->requestVector = client->swapped ?
			SwappedUntrustedProcVector : UntrustedProcVector;
		}
	    }
	    break;
	}
	case ClientStateGone:
	case ClientStateRetained: /* client disconnected */
	{
	    XID authId = client->authId;
	    SecurityAuthorizationPtr pAuth;

	    pAuth = (SecurityAuthorizationPtr)LookupIDByType(authId,
						SecurityAuthorizationResType);
	    if (pAuth)
	    { /* it is a generated authorization */
		pAuth->refcnt--;
		if (pAuth->refcnt == 0)
		{
		    SecurityStartAuthorizationTimer(pAuth);
		}
	    }	    
	    break;
	}
	default: break; 
    }
} /* SecurityClientStateCallback */

#ifdef LBX
Bool
SecuritySameLevel(client, authId)
    ClientPtr client;
    XID authId;
{
    SecurityAuthorizationPtr pAuth;

    pAuth = (SecurityAuthorizationPtr)LookupIDByType(authId,
						SecurityAuthorizationResType);
    if (pAuth)
	return client->trustLevel == pAuth->trustLevel;
    return client->trustLevel == XSecurityClientTrusted;
}
#endif

/* SecurityCensorImage
 *
 * Called after pScreen->GetImage to prevent pieces or trusted windows from
 * being returned in image data from an untrusted window.
 *
 * Arguments:
 *	client is the client doing the GetImage.
 *      pVisibleRegion is the visible region of the window.
 *	widthBytesLine is the width in bytes of one horizontal line in pBuf.
 *	pDraw is the source window.
 *	x, y, w, h is the rectangle of image data from pDraw in pBuf.
 *	format is the format of the image data in pBuf: ZPixmap or XYPixmap.
 *	pBuf is the image data.
 *
 * Returns: nothing.
 *
 * Side Effects:
 *	Any part of the rectangle (x, y, w, h) that is outside the visible
 *	region of the window will be destroyed (overwritten) in pBuf.
 */
void
SecurityCensorImage(client, pVisibleRegion, widthBytesLine, pDraw, x, y, w, h,
		    format, pBuf)
    ClientPtr client;
    RegionPtr pVisibleRegion;
    long widthBytesLine;
    DrawablePtr pDraw;
    int x, y, w, h;
    unsigned int format;
    char * pBuf;
{
    ScreenPtr pScreen = pDraw->pScreen;
    RegionRec imageRegion;  /* region representing x,y,w,h */
    RegionRec censorRegion; /* region to obliterate */
    BoxRec imageBox;
    int nRects;

    imageBox.x1 = x;
    imageBox.y1 = y;
    imageBox.x2 = x + w;
    imageBox.y2 = y + h;
    REGION_INIT(pScreen, &imageRegion, &imageBox, 1);
    REGION_NULL(pScreen, &censorRegion);

    /* censorRegion = imageRegion - visibleRegion */
    REGION_SUBTRACT(pScreen, &censorRegion, &imageRegion, pVisibleRegion);
    nRects = REGION_NUM_RECTS(&censorRegion);
    if (nRects > 0)
    { /* we have something to censor */
	GCPtr pScratchGC = NULL;
	PixmapPtr pPix = NULL;
	xRectangle *pRects = NULL;
	Bool failed = FALSE;
	int depth = 1;
	int bitsPerPixel = 1;
	int i;
	BoxPtr pBox;

	/* convert region to list-of-rectangles for PolyFillRect */

	pRects = (xRectangle *)ALLOCATE_LOCAL(nRects * sizeof(xRectangle *));
	if (!pRects)
	{
	    failed = TRUE;
	    goto failSafe;
	}
	for (pBox = REGION_RECTS(&censorRegion), i = 0;
	     i < nRects;
	     i++, pBox++)
	{
	    pRects[i].x = pBox->x1;
	    pRects[i].y = pBox->y1 - imageBox.y1;
	    pRects[i].width  = pBox->x2 - pBox->x1;
	    pRects[i].height = pBox->y2 - pBox->y1;
	}

	/* use pBuf as a fake pixmap */

	if (format == ZPixmap)
	{
	    depth = pDraw->depth;
	    bitsPerPixel = pDraw->bitsPerPixel;
	}

	pPix = GetScratchPixmapHeader(pDraw->pScreen, w, h,
		    depth, bitsPerPixel,
		    widthBytesLine, (pointer)pBuf);
	if (!pPix)
	{
	    failed = TRUE;
	    goto failSafe;
	}

	pScratchGC = GetScratchGC(depth, pPix->drawable.pScreen);
	if (!pScratchGC)
	{
	    failed = TRUE;
	    goto failSafe;
	}

	ValidateGC(&pPix->drawable, pScratchGC);
	(* pScratchGC->ops->PolyFillRect)(&pPix->drawable,
			    pScratchGC, nRects, pRects);

    failSafe:
	if (failed)
	{
	    /* Censoring was not completed above.  To be safe, wipe out
	     * all the image data so that nothing trusted gets out.
	     */
	    bzero(pBuf, (int)(widthBytesLine * h));
	}
	if (pRects)     DEALLOCATE_LOCAL(pRects);
	if (pScratchGC) FreeScratchGC(pScratchGC);
	if (pPix)       FreeScratchPixmapHeader(pPix);
    }
    REGION_UNINIT(pScreen, &imageRegion);
    REGION_UNINIT(pScreen, &censorRegion);
} /* SecurityCensorImage */

/**********************************************************************/

typedef struct _PropertyAccessRec {
    ATOM name;
    ATOM mustHaveProperty;
    char *mustHaveValue;
    char windowRestriction;
#define SecurityAnyWindow          0
#define SecurityRootWindow         1
#define SecurityWindowWithProperty 2
    char readAction;
    char writeAction;
    char destroyAction;
    struct _PropertyAccessRec *next;
} PropertyAccessRec, *PropertyAccessPtr;

static PropertyAccessPtr PropertyAccessList = NULL;
static char SecurityDefaultAction = SecurityErrorOperation;
static char *SecurityPolicyFile = DEFAULTPOLICYFILE;
static ATOM SecurityMaxPropertyName = 0;

static char *SecurityKeywords[] = {
#define SecurityKeywordComment 0
    "#",
#define SecurityKeywordProperty 1
    "property",
#define SecurityKeywordSitePolicy 2
    "sitepolicy",
#define SecurityKeywordRoot 3
    "root",
#define SecurityKeywordAny 4
    "any"
};

#define NUMKEYWORDS (sizeof(SecurityKeywords) / sizeof(char *))

#undef PROPDEBUG
/*#define PROPDEBUG  1*/

static void
SecurityFreePropertyAccessList(void)
{
    while (PropertyAccessList)
    {
	PropertyAccessPtr freeit = PropertyAccessList;
	PropertyAccessList = PropertyAccessList->next;
	xfree(freeit);
    }
} /* SecurityFreePropertyAccessList */

#ifndef __UNIXOS2__
#define SecurityIsWhitespace(c) ( (c == ' ') || (c == '\t') || (c == '\n') )
#else
#define SecurityIsWhitespace(c) ( (c == ' ') || (c == '\t') || (c == '\n') || (c == '\r') )
#endif

static char *
SecuritySkipWhitespace(
    char *p)
{
    while (SecurityIsWhitespace(*p))
	p++;
    return p;
} /* SecuritySkipWhitespace */


static char *
SecurityParseString(
    char **rest)
{
    char *startOfString;
    char *s = *rest;
    char endChar = 0;

    s = SecuritySkipWhitespace(s);

    if (*s == '"' || *s == '\'')
    {
	endChar = *s++;
	startOfString = s;
	while (*s && (*s != endChar))
	    s++;
    }
    else
    {
	startOfString = s;
	while (*s && !SecurityIsWhitespace(*s))
	    s++;
    }
    if (*s)
    {
	*s = '\0';
	*rest = s + 1;
	return startOfString;
    }
    else
    {
	*rest = s;
	return (endChar) ? NULL : startOfString;
    }
} /* SecurityParseString */


static int
SecurityParseKeyword(
    char **p)
{
    int i;
    char *s = *p;
    s = SecuritySkipWhitespace(s);
    for (i = 0; i < NUMKEYWORDS; i++)
    {
	int len = strlen(SecurityKeywords[i]);
	if (strncmp(s, SecurityKeywords[i], len) == 0)
	{
	    *p = s + len;
	    return (i);
	}
    }
    *p = s;
    return -1;
} /* SecurityParseKeyword */


static Bool
SecurityParsePropertyAccessRule(
    char *p)
{
    char *propname;
    char c;
    char action = SecurityDefaultAction;
    char readAction, writeAction, destroyAction;
    PropertyAccessPtr pacl, prev, cur;
    char *mustHaveProperty = NULL;
    char *mustHaveValue = NULL;
    Bool invalid;
    char windowRestriction;
    int size;
    int keyword;

    /* get property name */
    propname = SecurityParseString(&p);
    if (!propname || (strlen(propname) == 0))
	return FALSE;

    /* get window on which property must reside for rule to apply */

    keyword = SecurityParseKeyword(&p);
    if (keyword == SecurityKeywordRoot)
	windowRestriction = SecurityRootWindow;
    else if (keyword == SecurityKeywordAny) 
	windowRestriction = SecurityAnyWindow;
    else /* not root or any, must be a property name */
    {
	mustHaveProperty = SecurityParseString(&p);
	if (!mustHaveProperty || (strlen(mustHaveProperty) == 0))
	    return FALSE;
	windowRestriction = SecurityWindowWithProperty;
	p = SecuritySkipWhitespace(p);
	if (*p == '=')
	{ /* property value is specified too */
	    p++; /* skip over '=' */
	    mustHaveValue = SecurityParseString(&p);
	    if (!mustHaveValue)
		return FALSE;
	}
    }

    /* get operations and actions */

    invalid = FALSE;
    readAction = writeAction = destroyAction = SecurityDefaultAction;
    while ( (c = *p++) && !invalid)
    {
	switch (c)
	{
	    case 'i': action = SecurityIgnoreOperation; break;
	    case 'a': action = SecurityAllowOperation;  break;
	    case 'e': action = SecurityErrorOperation;  break;

	    case 'r': readAction    = action; break;
	    case 'w': writeAction   = action; break;
	    case 'd': destroyAction = action; break;

	    default :
		if (!SecurityIsWhitespace(c))
		    invalid = TRUE;
	    break;
	}
    }
    if (invalid)
	return FALSE;

    /* We've successfully collected all the information needed for this
     * property access rule.  Now record it in a PropertyAccessRec.
     */
    size = sizeof(PropertyAccessRec);

    /* If there is a property value string, allocate space for it 
     * right after the PropertyAccessRec.
     */
    if (mustHaveValue)
	size += strlen(mustHaveValue) + 1;
    pacl = (PropertyAccessPtr)Xalloc(size);
    if (!pacl)
	return FALSE;

    pacl->name = MakeAtom(propname, strlen(propname), TRUE);
    if (pacl->name == BAD_RESOURCE)
    {
	Xfree(pacl);
	return FALSE;
    }
    if (mustHaveProperty)
    {
	pacl->mustHaveProperty = MakeAtom(mustHaveProperty,
					  strlen(mustHaveProperty), TRUE);
	if (pacl->mustHaveProperty == BAD_RESOURCE)
	{
	    Xfree(pacl);
	    return FALSE;
	}
    }
    else
	pacl->mustHaveProperty = 0;

    if (mustHaveValue)
    {
	pacl->mustHaveValue = (char *)(pacl + 1);
	strcpy(pacl->mustHaveValue, mustHaveValue);
    }
    else
	pacl->mustHaveValue = NULL;

    SecurityMaxPropertyName = max(SecurityMaxPropertyName, pacl->name);

    pacl->windowRestriction = windowRestriction;
    pacl->readAction  = readAction;
    pacl->writeAction = writeAction;
    pacl->destroyAction = destroyAction;

    /* link the new rule into the list of rules in order of increasing
     * property name (atom) value to make searching easier
     */

    for (prev = NULL,  cur = PropertyAccessList;
	 cur && cur->name <= pacl->name;
	 prev = cur, cur = cur->next)
	;
    if (!prev)
    {
	pacl->next = cur;
	PropertyAccessList = pacl;
    }
    else
    {
	prev->next = pacl;
	pacl->next = cur;
    }
    return TRUE;
} /* SecurityParsePropertyAccessRule */

static char **SecurityPolicyStrings = NULL;
static int nSecurityPolicyStrings = 0;

static Bool
SecurityParseSitePolicy(
    char *p)
{
    char *policyStr = SecurityParseString(&p);
    char *copyPolicyStr;
    char **newStrings;

    if (!policyStr)
	return FALSE;

    copyPolicyStr = (char *)Xalloc(strlen(policyStr) + 1);
    if (!copyPolicyStr)
	return TRUE;
    strcpy(copyPolicyStr, policyStr);
    newStrings = (char **)Xrealloc(SecurityPolicyStrings,
			  sizeof (char *) * (nSecurityPolicyStrings + 1));
    if (!newStrings)
    {
	Xfree(copyPolicyStr);
	return TRUE;
    }

    SecurityPolicyStrings = newStrings;
    SecurityPolicyStrings[nSecurityPolicyStrings++] = copyPolicyStr;

    return TRUE;

} /* SecurityParseSitePolicy */


char **
SecurityGetSitePolicyStrings(n)
    int *n;
{
    *n = nSecurityPolicyStrings;
    return SecurityPolicyStrings;
} /* SecurityGetSitePolicyStrings */

static void
SecurityFreeSitePolicyStrings(void)
{
    if (SecurityPolicyStrings)
    {
	assert(nSecurityPolicyStrings);
	while (nSecurityPolicyStrings--)
	{
	    Xfree(SecurityPolicyStrings[nSecurityPolicyStrings]);
	}
	Xfree(SecurityPolicyStrings);
	SecurityPolicyStrings = NULL;
	nSecurityPolicyStrings = 0;
    }
} /* SecurityFreeSitePolicyStrings */


static void
SecurityLoadPropertyAccessList(void)
{
    FILE *f;
    int lineNumber = 0;

    SecurityMaxPropertyName = 0;

    if (!SecurityPolicyFile)
	return;

#ifndef __UNIXOS2__
    f = fopen(SecurityPolicyFile, "r");
#else
    f = fopen((char*)__XOS2RedirRoot(SecurityPolicyFile), "r");
#endif    
    if (!f)
    {
	ErrorF("error opening security policy file %s\n",
	       SecurityPolicyFile);
	return;
    }

    while (!feof(f))
    {
	char buf[200];
	Bool validLine;
	char *p;

	if (!(p = fgets(buf, sizeof(buf), f)))
	    break;
	lineNumber++;

	/* if first line, check version number */
	if (lineNumber == 1)
	{
	    char *v = SecurityParseString(&p);
	    if (strcmp(v, SECURITY_POLICY_FILE_VERSION) != 0)
	    {
		ErrorF("%s: invalid security policy file version, ignoring file\n",
		       SecurityPolicyFile);
		break;
	    }
	    validLine = TRUE;
	}
	else
	{
	    switch (SecurityParseKeyword(&p))
	    {
		case SecurityKeywordComment:
		    validLine = TRUE;
		break;

		case SecurityKeywordProperty:
		    validLine = SecurityParsePropertyAccessRule(p);
		break;

		case SecurityKeywordSitePolicy:
		    validLine = SecurityParseSitePolicy(p);
		break;

		default:
		    validLine = (*p == '\0'); /* blank lines OK, others not */
		break;
	    }
	}

	if (!validLine)
	    ErrorF("Line %d of %s invalid, ignoring\n",
		   lineNumber, SecurityPolicyFile);
    } /* end while more input */

#ifdef PROPDEBUG
    {
	PropertyAccessPtr pacl;
	char *op = "aie";
	for (pacl = PropertyAccessList; pacl; pacl = pacl->next)
	{
	    ErrorF("property %s ", NameForAtom(pacl->name));
	    switch (pacl->windowRestriction)
	    {
		case SecurityAnyWindow: ErrorF("any "); break;
		case SecurityRootWindow: ErrorF("root "); break;
		case SecurityWindowWithProperty:
		{
		    ErrorF("%s ", NameForAtom(pacl->mustHaveProperty));
		    if (pacl->mustHaveValue)
			ErrorF(" = \"%s\" ", pacl->mustHaveValue);

		}
		break;
	    }
	    ErrorF("%cr %cw %cd\n", op[pacl->readAction],
		   op[pacl->writeAction], op[pacl->destroyAction]);
	}
    }
#endif /* PROPDEBUG */

    fclose(f);
} /* SecurityLoadPropertyAccessList */


static Bool
SecurityMatchString(
    char *ws,
    char *cs)
{
    while (*ws && *cs)
    {
	if (*ws == '*')
	{
	    Bool match = FALSE;
	    ws++;
	    while (!(match = SecurityMatchString(ws, cs)) && *cs)
	    {
		cs++;
	    }
	    return match;
	}
	else if (*ws == *cs)
	{
	    ws++;
	    cs++;
	}
	else break;
    }
    return ( ( (*ws == '\0') || ((*ws == '*') && *(ws+1) == '\0') )
	     && (*cs == '\0') );
} /* SecurityMatchString */

#ifdef PROPDEBUG
#include <sys/types.h>
#include <sys/stat.h>
#endif


char
SecurityCheckPropertyAccess(client, pWin, propertyName, access_mode)
    ClientPtr client;
    WindowPtr pWin;
    ATOM propertyName;
    Mask access_mode;
{
    PropertyAccessPtr pacl;
    char action = SecurityDefaultAction;

    /* if client trusted or window untrusted, allow operation */

    if ( (client->trustLevel == XSecurityClientTrusted) ||
	 (wClient(pWin)->trustLevel != XSecurityClientTrusted) )
	return SecurityAllowOperation;

#ifdef PROPDEBUG
    /* For testing, it's more convenient if the property rules file gets
     * reloaded whenever it changes, so we can rapidly try things without
     * having to reset the server.
     */
    {
	struct stat buf;
	static time_t lastmod = 0;
	int ret = stat(SecurityPolicyFile , &buf);
	if ( (ret == 0) && (buf.st_mtime > lastmod) )
	{
	    ErrorF("reloading property rules\n");
	    SecurityFreePropertyAccessList();
	    SecurityLoadPropertyAccessList();
	    lastmod = buf.st_mtime;
	}
    }
#endif

    /* If the property atom is bigger than any atoms on the list, 
     * we know we won't find it, so don't even bother looking.
     */
    if (propertyName <= SecurityMaxPropertyName)
    {
	/* untrusted client operating on trusted window; see if it's allowed */

	for (pacl = PropertyAccessList; pacl; pacl = pacl->next)
	{
	    if (pacl->name < propertyName)
		continue;
	    if (pacl->name > propertyName)
		break;

	    /* pacl->name == propertyName, so see if it applies to this window */

	    switch (pacl->windowRestriction)
	    {
		case SecurityAnyWindow: /* always applies */
		    break;

		case SecurityRootWindow:
		{
		    /* if not a root window, this rule doesn't apply */
		    if (pWin->parent)
			continue;
		}
		break;

		case SecurityWindowWithProperty:
		{
		    PropertyPtr pProp = wUserProps (pWin);
		    Bool match = FALSE;
		    char *p;
		    char *pEndData;

		    while (pProp)
		    {
			if (pProp->propertyName == pacl->mustHaveProperty)
			    break;
			pProp = pProp->next;
		    }
		    if (!pProp)
			continue;
		    if (!pacl->mustHaveValue)
			break;
		    if (pProp->type != XA_STRING || pProp->format != 8)
			continue;

		    p = pProp->data;
		    pEndData = ((char *)pProp->data) + pProp->size;
		    while (!match && p < pEndData)
		    {
			 if (SecurityMatchString(pacl->mustHaveValue, p))
			     match = TRUE;
			 else
			 { /* skip to the next string */
			     while (*p++ && p < pEndData)
				 ;
			 }
		    }
		    if (!match)
			continue;
		}
		break; /* end case SecurityWindowWithProperty */
	    } /* end switch on windowRestriction */

	    /* If we get here, the property access rule pacl applies.
	     * If pacl doesn't apply, something above should have
	     * executed a continue, which will skip the follwing code.
	     */
	    action = SecurityAllowOperation;
	    if (access_mode & SecurityReadAccess)
		action = max(action, pacl->readAction);
	    if (access_mode & SecurityWriteAccess)
		action = max(action, pacl->writeAction);
	    if (access_mode & SecurityDestroyAccess)
		action = max(action, pacl->destroyAction);
	    break;
	} /* end for each pacl */
    } /* end if propertyName <= SecurityMaxPropertyName */

    if (SecurityAllowOperation != action)
    { /* audit the access violation */
	int cid = CLIENT_ID(pWin->drawable.id);
	int reqtype = ((xReq *)client->requestBuffer)->reqType;
	char *actionstr = (SecurityIgnoreOperation == action) ?
							"ignored" : "error";
	SecurityAudit("client %d attempted request %d with window 0x%x property %s (atom 0x%x) of client %d, %s\n",
		client->index, reqtype, pWin->drawable.id,
		      NameForAtom(propertyName), propertyName, cid, actionstr);
    }
    return action;
} /* SecurityCheckPropertyAccess */


/* SecurityResetProc
 *
 * Arguments:
 *	extEntry is the extension information for the security extension.
 *
 * Returns: nothing.
 *
 * Side Effects:
 *	Performs any cleanup needed by Security at server shutdown time.
 */

static void
SecurityResetProc(
    ExtensionEntry *extEntry)
{
    SecurityFreePropertyAccessList();
    SecurityFreeSitePolicyStrings();
} /* SecurityResetProc */


int
XSecurityOptions(argc, argv, i)
    int argc;
    char **argv;
    int i;
{
    if (strcmp(argv[i], "-sp") == 0)
    {
	if (i < argc)
	    SecurityPolicyFile = argv[++i];
	return (i + 1);
    }
    return (i);
} /* XSecurityOptions */



/* SecurityExtensionInit
 *
 * Arguments: none.
 *
 * Returns: nothing.
 *
 * Side Effects:
 *	Enables the Security extension if possible.
 */

void
SecurityExtensionInit(INITARGS)
{
    ExtensionEntry	*extEntry;
    int i;

    SecurityAuthorizationResType =
	CreateNewResourceType(SecurityDeleteAuthorization);

    RTEventClient = CreateNewResourceType(
				SecurityDeleteAuthorizationEventClient);

    if (!SecurityAuthorizationResType || !RTEventClient)
	return;

    RTEventClient |= RC_NEVERRETAIN;

    if (!AddCallback(&ClientStateCallback, SecurityClientStateCallback, NULL))
	return;

    extEntry = AddExtension(SECURITY_EXTENSION_NAME,
			    XSecurityNumberEvents, XSecurityNumberErrors,
			    ProcSecurityDispatch, SProcSecurityDispatch,
                            SecurityResetProc, StandardMinorOpcode);

    SecurityErrorBase = extEntry->errorBase;
    SecurityEventBase = extEntry->eventBase;

    EventSwapVector[SecurityEventBase + XSecurityAuthorizationRevoked] =
	(EventSwapPtr)SwapSecurityAuthorizationRevokedEvent;

    /* initialize untrusted proc vectors */

    for (i = 0; i < 128; i++)
    {
	UntrustedProcVector[i] = ProcVector[i];
	SwappedUntrustedProcVector[i] = SwappedProcVector[i];
    }

    /* make sure insecure extensions are not allowed */

    for (i = 128; i < 256; i++)
    {
	if (!UntrustedProcVector[i])
	{
	    UntrustedProcVector[i] = ProcBadRequest;
	    SwappedUntrustedProcVector[i] = ProcBadRequest;
	}
    }

    SecurityLoadPropertyAccessList();

} /* SecurityExtensionInit */