This file is indexed.

/usr/share/pyshared/twisted/conch/test/test_transport.py is in python-twisted-conch 1:11.1.0-1.

This file is owned by root:root, with mode 0o644.

The actual contents of the file can be viewed below.

   1
   2
   3
   4
   5
   6
   7
   8
   9
  10
  11
  12
  13
  14
  15
  16
  17
  18
  19
  20
  21
  22
  23
  24
  25
  26
  27
  28
  29
  30
  31
  32
  33
  34
  35
  36
  37
  38
  39
  40
  41
  42
  43
  44
  45
  46
  47
  48
  49
  50
  51
  52
  53
  54
  55
  56
  57
  58
  59
  60
  61
  62
  63
  64
  65
  66
  67
  68
  69
  70
  71
  72
  73
  74
  75
  76
  77
  78
  79
  80
  81
  82
  83
  84
  85
  86
  87
  88
  89
  90
  91
  92
  93
  94
  95
  96
  97
  98
  99
 100
 101
 102
 103
 104
 105
 106
 107
 108
 109
 110
 111
 112
 113
 114
 115
 116
 117
 118
 119
 120
 121
 122
 123
 124
 125
 126
 127
 128
 129
 130
 131
 132
 133
 134
 135
 136
 137
 138
 139
 140
 141
 142
 143
 144
 145
 146
 147
 148
 149
 150
 151
 152
 153
 154
 155
 156
 157
 158
 159
 160
 161
 162
 163
 164
 165
 166
 167
 168
 169
 170
 171
 172
 173
 174
 175
 176
 177
 178
 179
 180
 181
 182
 183
 184
 185
 186
 187
 188
 189
 190
 191
 192
 193
 194
 195
 196
 197
 198
 199
 200
 201
 202
 203
 204
 205
 206
 207
 208
 209
 210
 211
 212
 213
 214
 215
 216
 217
 218
 219
 220
 221
 222
 223
 224
 225
 226
 227
 228
 229
 230
 231
 232
 233
 234
 235
 236
 237
 238
 239
 240
 241
 242
 243
 244
 245
 246
 247
 248
 249
 250
 251
 252
 253
 254
 255
 256
 257
 258
 259
 260
 261
 262
 263
 264
 265
 266
 267
 268
 269
 270
 271
 272
 273
 274
 275
 276
 277
 278
 279
 280
 281
 282
 283
 284
 285
 286
 287
 288
 289
 290
 291
 292
 293
 294
 295
 296
 297
 298
 299
 300
 301
 302
 303
 304
 305
 306
 307
 308
 309
 310
 311
 312
 313
 314
 315
 316
 317
 318
 319
 320
 321
 322
 323
 324
 325
 326
 327
 328
 329
 330
 331
 332
 333
 334
 335
 336
 337
 338
 339
 340
 341
 342
 343
 344
 345
 346
 347
 348
 349
 350
 351
 352
 353
 354
 355
 356
 357
 358
 359
 360
 361
 362
 363
 364
 365
 366
 367
 368
 369
 370
 371
 372
 373
 374
 375
 376
 377
 378
 379
 380
 381
 382
 383
 384
 385
 386
 387
 388
 389
 390
 391
 392
 393
 394
 395
 396
 397
 398
 399
 400
 401
 402
 403
 404
 405
 406
 407
 408
 409
 410
 411
 412
 413
 414
 415
 416
 417
 418
 419
 420
 421
 422
 423
 424
 425
 426
 427
 428
 429
 430
 431
 432
 433
 434
 435
 436
 437
 438
 439
 440
 441
 442
 443
 444
 445
 446
 447
 448
 449
 450
 451
 452
 453
 454
 455
 456
 457
 458
 459
 460
 461
 462
 463
 464
 465
 466
 467
 468
 469
 470
 471
 472
 473
 474
 475
 476
 477
 478
 479
 480
 481
 482
 483
 484
 485
 486
 487
 488
 489
 490
 491
 492
 493
 494
 495
 496
 497
 498
 499
 500
 501
 502
 503
 504
 505
 506
 507
 508
 509
 510
 511
 512
 513
 514
 515
 516
 517
 518
 519
 520
 521
 522
 523
 524
 525
 526
 527
 528
 529
 530
 531
 532
 533
 534
 535
 536
 537
 538
 539
 540
 541
 542
 543
 544
 545
 546
 547
 548
 549
 550
 551
 552
 553
 554
 555
 556
 557
 558
 559
 560
 561
 562
 563
 564
 565
 566
 567
 568
 569
 570
 571
 572
 573
 574
 575
 576
 577
 578
 579
 580
 581
 582
 583
 584
 585
 586
 587
 588
 589
 590
 591
 592
 593
 594
 595
 596
 597
 598
 599
 600
 601
 602
 603
 604
 605
 606
 607
 608
 609
 610
 611
 612
 613
 614
 615
 616
 617
 618
 619
 620
 621
 622
 623
 624
 625
 626
 627
 628
 629
 630
 631
 632
 633
 634
 635
 636
 637
 638
 639
 640
 641
 642
 643
 644
 645
 646
 647
 648
 649
 650
 651
 652
 653
 654
 655
 656
 657
 658
 659
 660
 661
 662
 663
 664
 665
 666
 667
 668
 669
 670
 671
 672
 673
 674
 675
 676
 677
 678
 679
 680
 681
 682
 683
 684
 685
 686
 687
 688
 689
 690
 691
 692
 693
 694
 695
 696
 697
 698
 699
 700
 701
 702
 703
 704
 705
 706
 707
 708
 709
 710
 711
 712
 713
 714
 715
 716
 717
 718
 719
 720
 721
 722
 723
 724
 725
 726
 727
 728
 729
 730
 731
 732
 733
 734
 735
 736
 737
 738
 739
 740
 741
 742
 743
 744
 745
 746
 747
 748
 749
 750
 751
 752
 753
 754
 755
 756
 757
 758
 759
 760
 761
 762
 763
 764
 765
 766
 767
 768
 769
 770
 771
 772
 773
 774
 775
 776
 777
 778
 779
 780
 781
 782
 783
 784
 785
 786
 787
 788
 789
 790
 791
 792
 793
 794
 795
 796
 797
 798
 799
 800
 801
 802
 803
 804
 805
 806
 807
 808
 809
 810
 811
 812
 813
 814
 815
 816
 817
 818
 819
 820
 821
 822
 823
 824
 825
 826
 827
 828
 829
 830
 831
 832
 833
 834
 835
 836
 837
 838
 839
 840
 841
 842
 843
 844
 845
 846
 847
 848
 849
 850
 851
 852
 853
 854
 855
 856
 857
 858
 859
 860
 861
 862
 863
 864
 865
 866
 867
 868
 869
 870
 871
 872
 873
 874
 875
 876
 877
 878
 879
 880
 881
 882
 883
 884
 885
 886
 887
 888
 889
 890
 891
 892
 893
 894
 895
 896
 897
 898
 899
 900
 901
 902
 903
 904
 905
 906
 907
 908
 909
 910
 911
 912
 913
 914
 915
 916
 917
 918
 919
 920
 921
 922
 923
 924
 925
 926
 927
 928
 929
 930
 931
 932
 933
 934
 935
 936
 937
 938
 939
 940
 941
 942
 943
 944
 945
 946
 947
 948
 949
 950
 951
 952
 953
 954
 955
 956
 957
 958
 959
 960
 961
 962
 963
 964
 965
 966
 967
 968
 969
 970
 971
 972
 973
 974
 975
 976
 977
 978
 979
 980
 981
 982
 983
 984
 985
 986
 987
 988
 989
 990
 991
 992
 993
 994
 995
 996
 997
 998
 999
1000
1001
1002
1003
1004
1005
1006
1007
1008
1009
1010
1011
1012
1013
1014
1015
1016
1017
1018
1019
1020
1021
1022
1023
1024
1025
1026
1027
1028
1029
1030
1031
1032
1033
1034
1035
1036
1037
1038
1039
1040
1041
1042
1043
1044
1045
1046
1047
1048
1049
1050
1051
1052
1053
1054
1055
1056
1057
1058
1059
1060
1061
1062
1063
1064
1065
1066
1067
1068
1069
1070
1071
1072
1073
1074
1075
1076
1077
1078
1079
1080
1081
1082
1083
1084
1085
1086
1087
1088
1089
1090
1091
1092
1093
1094
1095
1096
1097
1098
1099
1100
1101
1102
1103
1104
1105
1106
1107
1108
1109
1110
1111
1112
1113
1114
1115
1116
1117
1118
1119
1120
1121
1122
1123
1124
1125
1126
1127
1128
1129
1130
1131
1132
1133
1134
1135
1136
1137
1138
1139
1140
1141
1142
1143
1144
1145
1146
1147
1148
1149
1150
1151
1152
1153
1154
1155
1156
1157
1158
1159
1160
1161
1162
1163
1164
1165
1166
1167
1168
1169
1170
1171
1172
1173
1174
1175
1176
1177
1178
1179
1180
1181
1182
1183
1184
1185
1186
1187
1188
1189
1190
1191
1192
1193
1194
1195
1196
1197
1198
1199
1200
1201
1202
1203
1204
1205
1206
1207
1208
1209
1210
1211
1212
1213
1214
1215
1216
1217
1218
1219
1220
1221
1222
1223
1224
1225
1226
1227
1228
1229
1230
1231
1232
1233
1234
1235
1236
1237
1238
1239
1240
1241
1242
1243
1244
1245
1246
1247
1248
1249
1250
1251
1252
1253
1254
1255
1256
1257
1258
1259
1260
1261
1262
1263
1264
1265
1266
1267
1268
1269
1270
1271
1272
1273
1274
1275
1276
1277
1278
1279
1280
1281
1282
1283
1284
1285
1286
1287
1288
1289
1290
1291
1292
1293
1294
1295
1296
1297
1298
1299
1300
1301
1302
1303
1304
1305
1306
1307
1308
1309
1310
1311
1312
1313
1314
1315
1316
1317
1318
1319
1320
1321
1322
1323
1324
1325
1326
1327
1328
1329
1330
1331
1332
1333
1334
1335
1336
1337
1338
1339
1340
1341
1342
1343
1344
1345
1346
1347
1348
1349
1350
1351
1352
1353
1354
1355
1356
1357
1358
1359
1360
1361
1362
1363
1364
1365
1366
1367
1368
1369
1370
1371
1372
1373
1374
1375
1376
1377
1378
1379
1380
1381
1382
1383
1384
1385
1386
1387
1388
1389
1390
1391
1392
1393
1394
1395
1396
1397
1398
1399
1400
1401
1402
1403
1404
1405
1406
1407
1408
1409
1410
1411
1412
1413
1414
1415
1416
1417
1418
1419
1420
1421
1422
1423
1424
1425
1426
1427
1428
1429
1430
1431
1432
1433
1434
1435
1436
1437
1438
1439
1440
1441
1442
1443
1444
1445
1446
1447
1448
1449
1450
1451
1452
1453
1454
1455
1456
1457
1458
1459
1460
1461
1462
1463
1464
1465
1466
1467
1468
1469
1470
1471
1472
1473
1474
1475
1476
1477
1478
1479
1480
1481
1482
1483
1484
1485
1486
1487
1488
1489
1490
1491
1492
1493
1494
1495
1496
1497
1498
1499
1500
1501
1502
1503
1504
1505
1506
1507
1508
1509
1510
1511
1512
1513
1514
1515
1516
1517
1518
1519
1520
1521
1522
1523
1524
1525
1526
1527
1528
1529
1530
1531
1532
1533
1534
1535
1536
1537
1538
1539
1540
1541
1542
1543
1544
1545
1546
1547
1548
1549
1550
1551
1552
1553
1554
1555
1556
1557
1558
1559
1560
1561
1562
1563
1564
1565
1566
1567
1568
1569
1570
1571
1572
1573
1574
1575
1576
1577
1578
1579
1580
1581
1582
1583
1584
1585
1586
1587
1588
1589
1590
1591
1592
1593
1594
1595
1596
1597
1598
1599
1600
1601
1602
1603
1604
1605
1606
1607
1608
1609
1610
1611
1612
1613
1614
1615
1616
1617
1618
1619
1620
1621
1622
1623
1624
1625
1626
1627
1628
1629
1630
1631
1632
1633
1634
1635
1636
1637
1638
1639
1640
1641
1642
1643
1644
1645
1646
1647
1648
1649
1650
1651
1652
1653
1654
1655
1656
1657
1658
1659
1660
1661
1662
1663
1664
1665
1666
1667
1668
1669
1670
1671
1672
1673
1674
1675
1676
1677
1678
1679
1680
1681
1682
1683
1684
1685
1686
1687
1688
1689
1690
1691
1692
1693
1694
1695
1696
1697
1698
1699
1700
1701
1702
1703
1704
1705
1706
1707
1708
1709
1710
1711
1712
1713
1714
1715
1716
1717
1718
1719
1720
1721
1722
1723
1724
1725
1726
1727
1728
1729
1730
1731
1732
1733
1734
1735
1736
1737
1738
1739
1740
1741
1742
1743
1744
1745
1746
1747
1748
1749
1750
1751
1752
1753
1754
1755
1756
1757
1758
1759
1760
1761
1762
1763
1764
1765
1766
1767
1768
1769
1770
1771
1772
1773
1774
1775
1776
1777
1778
1779
1780
1781
1782
1783
1784
1785
1786
1787
1788
1789
1790
1791
1792
1793
1794
1795
1796
1797
1798
1799
1800
1801
1802
1803
1804
1805
1806
1807
1808
1809
1810
1811
1812
1813
1814
1815
1816
1817
1818
1819
1820
1821
1822
1823
1824
1825
1826
1827
1828
1829
1830
1831
1832
1833
1834
1835
1836
1837
1838
1839
1840
1841
1842
1843
1844
1845
1846
1847
1848
1849
1850
1851
1852
1853
1854
1855
1856
1857
1858
1859
1860
1861
1862
1863
1864
1865
1866
1867
1868
1869
1870
1871
1872
1873
1874
1875
1876
1877
1878
1879
1880
1881
1882
1883
1884
1885
1886
1887
1888
1889
1890
1891
1892
1893
1894
1895
1896
1897
1898
1899
1900
1901
1902
1903
1904
1905
1906
1907
1908
1909
1910
1911
1912
1913
1914
1915
1916
1917
1918
1919
1920
1921
1922
1923
1924
1925
1926
1927
1928
1929
1930
1931
1932
1933
1934
1935
1936
1937
1938
1939
1940
1941
1942
1943
1944
1945
1946
1947
1948
1949
1950
1951
1952
1953
1954
1955
1956
1957
1958
1959
1960
1961
1962
1963
1964
1965
1966
1967
1968
1969
1970
1971
1972
1973
1974
1975
1976
1977
1978
1979
1980
1981
1982
1983
1984
1985
1986
1987
1988
1989
1990
1991
1992
1993
1994
1995
1996
1997
1998
1999
2000
2001
2002
2003
2004
2005
2006
2007
2008
2009
2010
2011
2012
2013
2014
2015
2016
2017
2018
2019
2020
2021
2022
2023
2024
2025
2026
2027
2028
2029
2030
2031
2032
2033
2034
2035
2036
2037
2038
2039
2040
2041
2042
2043
2044
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
# Copyright (c) Twisted Matrix Laboratories.
# See LICENSE for details.

"""
Tests for ssh/transport.py and the classes therein.
"""

try:
    import pyasn1
except ImportError:
    pyasn1 = None

try:
    import Crypto.Cipher.DES3
except ImportError:
    Crypto = None

if pyasn1 is not None and Crypto is not None:
    dependencySkip = None
    from twisted.conch.ssh import transport, keys, factory
    from twisted.conch.test import keydata
else:
    if pyasn1 is None:
        dependencySkip = "can't run w/o PyASN1"
    elif Crypto is None:
        dependencySkip = "can't run w/o PyCrypto"

    class transport: # fictional modules to make classes work
        class SSHTransportBase: pass
        class SSHServerTransport: pass
        class SSHClientTransport: pass
    class factory:
        class SSHFactory:
            pass

from twisted.trial import unittest
from twisted.internet import defer
from twisted.protocols import loopback
from twisted.python import randbytes
from twisted.python.reflect import qual
from twisted.python.hashlib import md5, sha1
from twisted.conch.ssh import service, common
from twisted.test import proto_helpers

from twisted.conch.error import ConchError



class MockTransportBase(transport.SSHTransportBase):
    """
    A base class for the client and server protocols.  Stores the messages
    it receieves instead of ignoring them.

    @ivar errors: a list of tuples: (reasonCode, description)
    @ivar unimplementeds: a list of integers: sequence number
    @ivar debugs: a list of tuples: (alwaysDisplay, message, lang)
    @ivar ignoreds: a list of strings: ignored data
    """

    def connectionMade(self):
        """
        Set up instance variables.
        """
        transport.SSHTransportBase.connectionMade(self)
        self.errors = []
        self.unimplementeds = []
        self.debugs = []
        self.ignoreds = []
        self.gotUnsupportedVersion = None


    def _unsupportedVersionReceived(self, remoteVersion):
        """
        Intercept unsupported version call.

        @type remoteVersion: C{str}
        """
        self.gotUnsupportedVersion = remoteVersion
        return transport.SSHTransportBase._unsupportedVersionReceived(self, remoteVersion)


    def receiveError(self, reasonCode, description):
        """
        Store any errors received.

        @type reasonCode: C{int}
        @type description: C{str}
        """
        self.errors.append((reasonCode, description))


    def receiveUnimplemented(self, seqnum):
        """
        Store any unimplemented packet messages.

        @type seqnum: C{int}
        """
        self.unimplementeds.append(seqnum)


    def receiveDebug(self, alwaysDisplay, message, lang):
        """
        Store any debug messages.

        @type alwaysDisplay: C{bool}
        @type message: C{str}
        @type lang: C{str}
        """
        self.debugs.append((alwaysDisplay, message, lang))


    def ssh_IGNORE(self, packet):
        """
        Store any ignored data.

        @type packet: C{str}
        """
        self.ignoreds.append(packet)


class MockCipher(object):
    """
    A mocked-up version of twisted.conch.ssh.transport.SSHCiphers.
    """
    outCipType = 'test'
    encBlockSize = 6
    inCipType = 'test'
    decBlockSize = 6
    inMACType = 'test'
    outMACType = 'test'
    verifyDigestSize = 1
    usedEncrypt = False
    usedDecrypt = False
    outMAC = (None, '', '', 1)
    inMAC = (None, '', '', 1)
    keys = ()


    def encrypt(self, x):
        """
        Called to encrypt the packet.  Simply record that encryption was used
        and return the data unchanged.
        """
        self.usedEncrypt = True
        if (len(x) % self.encBlockSize) != 0:
            raise RuntimeError("length %i modulo blocksize %i is not 0: %i" %
                    (len(x), self.encBlockSize, len(x) % self.encBlockSize))
        return x


    def decrypt(self, x):
        """
        Called to decrypt the packet.  Simply record that decryption was used
        and return the data unchanged.
        """
        self.usedDecrypt = True
        if (len(x) % self.encBlockSize) != 0:
            raise RuntimeError("length %i modulo blocksize %i is not 0: %i" %
                    (len(x), self.decBlockSize, len(x) % self.decBlockSize))
        return x


    def makeMAC(self, outgoingPacketSequence, payload):
        """
        Make a Message Authentication Code by sending the character value of
        the outgoing packet.
        """
        return chr(outgoingPacketSequence)


    def verify(self, incomingPacketSequence, packet, macData):
        """
        Verify the Message Authentication Code by checking that the packet
        sequence number is the same.
        """
        return chr(incomingPacketSequence) == macData


    def setKeys(self, ivOut, keyOut, ivIn, keyIn, macIn, macOut):
        """
        Record the keys.
        """
        self.keys = (ivOut, keyOut, ivIn, keyIn, macIn, macOut)



class MockCompression:
    """
    A mocked-up compression, based on the zlib interface.  Instead of
    compressing, it reverses the data and adds a 0x66 byte to the end.
    """


    def compress(self, payload):
        return payload[::-1] # reversed


    def decompress(self, payload):
        return payload[:-1][::-1]


    def flush(self, kind):
        return '\x66'



class MockService(service.SSHService):
    """
    A mocked-up service, based on twisted.conch.ssh.service.SSHService.

    @ivar started: True if this service has been started.
    @ivar stopped: True if this service has been stopped.
    """
    name = "MockService"
    started = False
    stopped = False
    protocolMessages = {0xff: "MSG_TEST", 71: "MSG_fiction"}


    def logPrefix(self):
        return "MockService"


    def serviceStarted(self):
        """
        Record that the service was started.
        """
        self.started = True


    def serviceStopped(self):
        """
        Record that the service was stopped.
        """
        self.stopped = True


    def ssh_TEST(self, packet):
        """
        A message that this service responds to.
        """
        self.transport.sendPacket(0xff, packet)


class MockFactory(factory.SSHFactory):
    """
    A mocked-up factory based on twisted.conch.ssh.factory.SSHFactory.
    """
    services = {
        'ssh-userauth': MockService}


    def getPublicKeys(self):
        """
        Return the public keys that authenticate this server.
        """
        return {
            'ssh-rsa': keys.Key.fromString(keydata.publicRSA_openssh),
            'ssh-dsa': keys.Key.fromString(keydata.publicDSA_openssh)}


    def getPrivateKeys(self):
        """
        Return the private keys that authenticate this server.
        """
        return {
            'ssh-rsa': keys.Key.fromString(keydata.privateRSA_openssh),
            'ssh-dsa': keys.Key.fromString(keydata.privateDSA_openssh)}


    def getPrimes(self):
        """
        Return the Diffie-Hellman primes that can be used for the
        diffie-hellman-group-exchange-sha1 key exchange.
        """
        return {
            1024: ((2, transport.DH_PRIME),),
            2048: ((3, transport.DH_PRIME),),
            4096: ((5, 7),)}



class MockOldFactoryPublicKeys(MockFactory):
    """
    The old SSHFactory returned mappings from key names to strings from
    getPublicKeys().  We return those here for testing.
    """


    def getPublicKeys(self):
        """
        We used to map key types to public key blobs as strings.
        """
        keys = MockFactory.getPublicKeys(self)
        for name, key in keys.items()[:]:
            keys[name] = key.blob()
        return keys



class MockOldFactoryPrivateKeys(MockFactory):
    """
    The old SSHFactory returned mappings from key names to PyCrypto key
    objects from getPrivateKeys().  We return those here for testing.
    """


    def getPrivateKeys(self):
        """
        We used to map key types to PyCrypto key objects.
        """
        keys = MockFactory.getPrivateKeys(self)
        for name, key  in keys.items()[:]:
            keys[name] = key.keyObject
        return keys



class TransportTestCase(unittest.TestCase):
    """
    Base class for transport test cases.
    """
    klass = None

    if Crypto is None:
        skip = "cannot run w/o PyCrypto"

    if pyasn1 is None:
        skip = "cannot run w/o PyASN1"


    def setUp(self):
        self.transport = proto_helpers.StringTransport()
        self.proto = self.klass()
        self.packets = []
        def secureRandom(len):
            """
            Return a consistent entropy value
            """
            return '\x99' * len
        self.oldSecureRandom = randbytes.secureRandom
        randbytes.secureRandom = secureRandom
        def stubSendPacket(messageType, payload):
            self.packets.append((messageType, payload))
        self.proto.makeConnection(self.transport)
        # we just let the kex packet go into the transport
        self.proto.sendPacket = stubSendPacket


    def finishKeyExchange(self, proto):
        """
        Deliver enough additional messages to C{proto} so that the key exchange
        which is started in L{SSHTransportBase.connectionMade} completes and
        non-key exchange messages can be sent and received.
        """
        proto.dataReceived("SSH-2.0-BogoClient-1.2i\r\n")
        proto.dispatchMessage(
            transport.MSG_KEXINIT, self._A_KEXINIT_MESSAGE)
        proto._keySetup("foo", "bar")
        # SSHTransportBase can't handle MSG_NEWKEYS, or it would be the right
        # thing to deliver next.  _newKeys won't work either, because
        # sendKexInit (probably) hasn't been called.  sendKexInit is responsible
        # for setting up certain state _newKeys relies on.  So, just change the
        # key exchange state to what it would be when key exchange is finished.
        proto._keyExchangeState = proto._KEY_EXCHANGE_NONE


    def tearDown(self):
        randbytes.secureRandom = self.oldSecureRandom
        self.oldSecureRandom = None


    def simulateKeyExchange(self, sharedSecret, exchangeHash):
        """
        Finish a key exchange by calling C{_keySetup} with the given arguments.
        Also do extra whitebox stuff to satisfy that method's assumption that
        some kind of key exchange has actually taken place.
        """
        self.proto._keyExchangeState = self.proto._KEY_EXCHANGE_REQUESTED
        self.proto._blockedByKeyExchange = []
        self.proto._keySetup(sharedSecret, exchangeHash)



class BaseSSHTransportTestCase(TransportTestCase):
    """
    Test TransportBase.  It implements the non-server/client specific
    parts of the SSH transport protocol.
    """

    klass = MockTransportBase

    _A_KEXINIT_MESSAGE = (
        "\xAA" * 16 +
        common.NS('diffie-hellman-group1-sha1') +
        common.NS('ssh-rsa') +
        common.NS('aes256-ctr') +
        common.NS('aes256-ctr') +
        common.NS('hmac-sha1') +
        common.NS('hmac-sha1') +
        common.NS('none') +
        common.NS('none') +
        common.NS('') +
        common.NS('') +
        '\x00' + '\x00\x00\x00\x00')

    def test_sendVersion(self):
        """
        Test that the first thing sent over the connection is the version
        string.
        """
        # the other setup was done in the setup method
        self.assertEqual(self.transport.value().split('\r\n', 1)[0],
                          "SSH-2.0-Twisted")


    def test_sendPacketPlain(self):
        """
        Test that plain (unencrypted, uncompressed) packets are sent
        correctly.  The format is::
            uint32 length (including type and padding length)
            byte padding length
            byte type
            bytes[length-padding length-2] data
            bytes[padding length] padding
        """
        proto = MockTransportBase()
        proto.makeConnection(self.transport)
        self.finishKeyExchange(proto)
        self.transport.clear()
        message = ord('A')
        payload = 'BCDEFG'
        proto.sendPacket(message, payload)
        value = self.transport.value()
        self.assertEqual(value, '\x00\x00\x00\x0c\x04ABCDEFG\x99\x99\x99\x99')


    def test_sendPacketEncrypted(self):
        """
        Test that packets sent while encryption is enabled are sent
        correctly.  The whole packet should be encrypted.
        """
        proto = MockTransportBase()
        proto.makeConnection(self.transport)
        self.finishKeyExchange(proto)
        proto.currentEncryptions = testCipher = MockCipher()
        message = ord('A')
        payload = 'BC'
        self.transport.clear()
        proto.sendPacket(message, payload)
        self.assertTrue(testCipher.usedEncrypt)
        value = self.transport.value()
        self.assertEqual(
            value,
            # Four byte length prefix
            '\x00\x00\x00\x08'
            # One byte padding length
            '\x04'
            # The actual application data
            'ABC'
            # "Random" padding - see the secureRandom monkeypatch in setUp
            '\x99\x99\x99\x99'
            # The MAC
            '\x02')


    def test_sendPacketCompressed(self):
        """
        Test that packets sent while compression is enabled are sent
        correctly.  The packet type and data should be encrypted.
        """
        proto = MockTransportBase()
        proto.makeConnection(self.transport)
        self.finishKeyExchange(proto)
        proto.outgoingCompression = MockCompression()
        self.transport.clear()
        proto.sendPacket(ord('A'), 'B')
        value = self.transport.value()
        self.assertEqual(
            value,
            '\x00\x00\x00\x0c\x08BA\x66\x99\x99\x99\x99\x99\x99\x99\x99')


    def test_sendPacketBoth(self):
        """
        Test that packets sent while compression and encryption are
        enabled are sent correctly.  The packet type and data should be
        compressed and then the whole packet should be encrypted.
        """
        proto = MockTransportBase()
        proto.makeConnection(self.transport)
        self.finishKeyExchange(proto)
        proto.currentEncryptions = testCipher = MockCipher()
        proto.outgoingCompression = MockCompression()
        message = ord('A')
        payload = 'BC'
        self.transport.clear()
        proto.sendPacket(message, payload)
        self.assertTrue(testCipher.usedEncrypt)
        value = self.transport.value()
        self.assertEqual(
            value,
            # Four byte length prefix
            '\x00\x00\x00\x0e'
            # One byte padding length
            '\x09'
            # Compressed application data
            'CBA\x66'
            # "Random" padding - see the secureRandom monkeypatch in setUp
            '\x99\x99\x99\x99\x99\x99\x99\x99\x99'
            # The MAC
            '\x02')


    def test_getPacketPlain(self):
        """
        Test that packets are retrieved correctly out of the buffer when
        no encryption is enabled.
        """
        proto = MockTransportBase()
        proto.makeConnection(self.transport)
        self.finishKeyExchange(proto)
        self.transport.clear()
        proto.sendPacket(ord('A'), 'BC')
        proto.buf = self.transport.value() + 'extra'
        self.assertEqual(proto.getPacket(), 'ABC')
        self.assertEqual(proto.buf, 'extra')


    def test_getPacketEncrypted(self):
        """
        Test that encrypted packets are retrieved correctly.
        See test_sendPacketEncrypted.
        """
        proto = MockTransportBase()
        proto.sendKexInit = lambda: None # don't send packets
        proto.makeConnection(self.transport)
        self.transport.clear()
        proto.currentEncryptions = testCipher = MockCipher()
        proto.sendPacket(ord('A'), 'BCD')
        value = self.transport.value()
        proto.buf = value[:MockCipher.decBlockSize]
        self.assertEqual(proto.getPacket(), None)
        self.assertTrue(testCipher.usedDecrypt)
        self.assertEqual(proto.first, '\x00\x00\x00\x0e\x09A')
        proto.buf += value[MockCipher.decBlockSize:]
        self.assertEqual(proto.getPacket(), 'ABCD')
        self.assertEqual(proto.buf, '')


    def test_getPacketCompressed(self):
        """
        Test that compressed packets are retrieved correctly.  See
        test_sendPacketCompressed.
        """
        proto = MockTransportBase()
        proto.makeConnection(self.transport)
        self.finishKeyExchange(proto)
        self.transport.clear()
        proto.outgoingCompression = MockCompression()
        proto.incomingCompression = proto.outgoingCompression
        proto.sendPacket(ord('A'), 'BCD')
        proto.buf = self.transport.value()
        self.assertEqual(proto.getPacket(), 'ABCD')


    def test_getPacketBoth(self):
        """
        Test that compressed and encrypted packets are retrieved correctly.
        See test_sendPacketBoth.
        """
        proto = MockTransportBase()
        proto.sendKexInit = lambda: None
        proto.makeConnection(self.transport)
        self.transport.clear()
        proto.currentEncryptions = testCipher = MockCipher()
        proto.outgoingCompression = MockCompression()
        proto.incomingCompression = proto.outgoingCompression
        proto.sendPacket(ord('A'), 'BCDEFG')
        proto.buf = self.transport.value()
        self.assertEqual(proto.getPacket(), 'ABCDEFG')


    def test_ciphersAreValid(self):
        """
        Test that all the supportedCiphers are valid.
        """
        ciphers = transport.SSHCiphers('A', 'B', 'C', 'D')
        iv = key = '\x00' * 16
        for cipName in self.proto.supportedCiphers:
            self.assertTrue(ciphers._getCipher(cipName, iv, key))


    def test_sendKexInit(self):
        """
        Test that the KEXINIT (key exchange initiation) message is sent
        correctly.  Payload::
            bytes[16] cookie
            string key exchange algorithms
            string public key algorithms
            string outgoing ciphers
            string incoming ciphers
            string outgoing MACs
            string incoming MACs
            string outgoing compressions
            string incoming compressions
            bool first packet follows
            uint32 0
        """
        value = self.transport.value().split('\r\n', 1)[1]
        self.proto.buf = value
        packet = self.proto.getPacket()
        self.assertEqual(packet[0], chr(transport.MSG_KEXINIT))
        self.assertEqual(packet[1:17], '\x99' * 16)
        (kex, pubkeys, ciphers1, ciphers2, macs1, macs2, compressions1,
         compressions2, languages1, languages2,
         buf) = common.getNS(packet[17:], 10)

        self.assertEqual(kex, ','.join(self.proto.supportedKeyExchanges))
        self.assertEqual(pubkeys, ','.join(self.proto.supportedPublicKeys))
        self.assertEqual(ciphers1, ','.join(self.proto.supportedCiphers))
        self.assertEqual(ciphers2, ','.join(self.proto.supportedCiphers))
        self.assertEqual(macs1, ','.join(self.proto.supportedMACs))
        self.assertEqual(macs2, ','.join(self.proto.supportedMACs))
        self.assertEqual(compressions1,
                          ','.join(self.proto.supportedCompressions))
        self.assertEqual(compressions2,
                          ','.join(self.proto.supportedCompressions))
        self.assertEqual(languages1, ','.join(self.proto.supportedLanguages))
        self.assertEqual(languages2, ','.join(self.proto.supportedLanguages))
        self.assertEqual(buf, '\x00' * 5)


    def test_receiveKEXINITReply(self):
        """
        Immediately after connecting, the transport expects a KEXINIT message
        and does not reply to it.
        """
        self.transport.clear()
        self.proto.dispatchMessage(
            transport.MSG_KEXINIT, self._A_KEXINIT_MESSAGE)
        self.assertEqual(self.packets, [])


    def test_sendKEXINITReply(self):
        """
        When a KEXINIT message is received which is not a reply to an earlier
        KEXINIT message which was sent, a KEXINIT reply is sent.
        """
        self.finishKeyExchange(self.proto)
        del self.packets[:]

        self.proto.dispatchMessage(
            transport.MSG_KEXINIT, self._A_KEXINIT_MESSAGE)
        self.assertEqual(len(self.packets), 1)
        self.assertEqual(self.packets[0][0], transport.MSG_KEXINIT)


    def test_sendKexInitTwiceFails(self):
        """
        A new key exchange cannot be started while a key exchange is already in
        progress.  If an attempt is made to send a I{KEXINIT} message using
        L{SSHTransportBase.sendKexInit} while a key exchange is in progress
        causes that method to raise a L{RuntimeError}.
        """
        self.assertRaises(RuntimeError, self.proto.sendKexInit)


    def test_sendKexInitBlocksOthers(self):
        """
        After L{SSHTransportBase.sendKexInit} has been called, messages types
        other than the following are queued and not sent until after I{NEWKEYS}
        is sent by L{SSHTransportBase._keySetup}.

        RFC 4253, section 7.1.
        """
        # sendKexInit is called by connectionMade, which is called in setUp.  So
        # we're in the state already.
        disallowedMessageTypes = [
            transport.MSG_SERVICE_REQUEST,
            transport.MSG_KEXINIT,
            ]

        # Drop all the bytes sent by setUp, they're not relevant to this test.
        self.transport.clear()

        # Get rid of the sendPacket monkey patch, we are testing the behavior of
        # sendPacket.
        del self.proto.sendPacket

        for messageType in disallowedMessageTypes:
            self.proto.sendPacket(messageType, 'foo')
            self.assertEqual(self.transport.value(), "")

        self.finishKeyExchange(self.proto)
        # Make the bytes written to the transport cleartext so it's easier to
        # make an assertion about them.
        self.proto.nextEncryptions = MockCipher()

        # Pseudo-deliver the peer's NEWKEYS message, which should flush the
        # messages which were queued above.
        self.proto._newKeys()
        self.assertEqual(self.transport.value().count("foo"), 2)


    def test_sendDebug(self):
        """
        Test that debug messages are sent correctly.  Payload::
            bool always display
            string debug message
            string language
        """
        self.proto.sendDebug("test", True, 'en')
        self.assertEqual(
            self.packets,
            [(transport.MSG_DEBUG,
              "\x01\x00\x00\x00\x04test\x00\x00\x00\x02en")])


    def test_receiveDebug(self):
        """
        Test that debug messages are received correctly.  See test_sendDebug.
        """
        self.proto.dispatchMessage(
            transport.MSG_DEBUG,
            '\x01\x00\x00\x00\x04test\x00\x00\x00\x02en')
        self.assertEqual(self.proto.debugs, [(True, 'test', 'en')])


    def test_sendIgnore(self):
        """
        Test that ignored messages are sent correctly.  Payload::
            string ignored data
        """
        self.proto.sendIgnore("test")
        self.assertEqual(
            self.packets, [(transport.MSG_IGNORE,
                            '\x00\x00\x00\x04test')])


    def test_receiveIgnore(self):
        """
        Test that ignored messages are received correctly.  See
        test_sendIgnore.
        """
        self.proto.dispatchMessage(transport.MSG_IGNORE, 'test')
        self.assertEqual(self.proto.ignoreds, ['test'])


    def test_sendUnimplemented(self):
        """
        Test that unimplemented messages are sent correctly.  Payload::
            uint32 sequence number
        """
        self.proto.sendUnimplemented()
        self.assertEqual(
            self.packets, [(transport.MSG_UNIMPLEMENTED,
                            '\x00\x00\x00\x00')])


    def test_receiveUnimplemented(self):
        """
        Test that unimplemented messages are received correctly.  See
        test_sendUnimplemented.
        """
        self.proto.dispatchMessage(transport.MSG_UNIMPLEMENTED,
                                   '\x00\x00\x00\xff')
        self.assertEqual(self.proto.unimplementeds, [255])


    def test_sendDisconnect(self):
        """
        Test that disconnection messages are sent correctly.  Payload::
            uint32 reason code
            string reason description
            string language
        """
        disconnected = [False]
        def stubLoseConnection():
            disconnected[0] = True
        self.transport.loseConnection = stubLoseConnection
        self.proto.sendDisconnect(0xff, "test")
        self.assertEqual(
            self.packets,
            [(transport.MSG_DISCONNECT,
              "\x00\x00\x00\xff\x00\x00\x00\x04test\x00\x00\x00\x00")])
        self.assertTrue(disconnected[0])


    def test_receiveDisconnect(self):
        """
        Test that disconnection messages are received correctly.  See
        test_sendDisconnect.
        """
        disconnected = [False]
        def stubLoseConnection():
            disconnected[0] = True
        self.transport.loseConnection = stubLoseConnection
        self.proto.dispatchMessage(transport.MSG_DISCONNECT,
                                   '\x00\x00\x00\xff\x00\x00\x00\x04test')
        self.assertEqual(self.proto.errors, [(255, 'test')])
        self.assertTrue(disconnected[0])


    def test_dataReceived(self):
        """
        Test that dataReceived parses packets and dispatches them to
        ssh_* methods.
        """
        kexInit = [False]
        def stubKEXINIT(packet):
            kexInit[0] = True
        self.proto.ssh_KEXINIT = stubKEXINIT
        self.proto.dataReceived(self.transport.value())
        self.assertTrue(self.proto.gotVersion)
        self.assertEqual(self.proto.ourVersionString,
                          self.proto.otherVersionString)
        self.assertTrue(kexInit[0])


    def test_service(self):
        """
        Test that the transport can set the running service and dispatches
        packets to the service's packetReceived method.
        """
        service = MockService()
        self.proto.setService(service)
        self.assertEqual(self.proto.service, service)
        self.assertTrue(service.started)
        self.proto.dispatchMessage(0xff, "test")
        self.assertEqual(self.packets, [(0xff, "test")])

        service2 = MockService()
        self.proto.setService(service2)
        self.assertTrue(service2.started)
        self.assertTrue(service.stopped)

        self.proto.connectionLost(None)
        self.assertTrue(service2.stopped)


    def test_avatar(self):
        """
        Test that the transport notifies the avatar of disconnections.
        """
        disconnected = [False]
        def logout():
            disconnected[0] = True
        self.proto.logoutFunction = logout
        self.proto.avatar = True

        self.proto.connectionLost(None)
        self.assertTrue(disconnected[0])


    def test_isEncrypted(self):
        """
        Test that the transport accurately reflects its encrypted status.
        """
        self.assertFalse(self.proto.isEncrypted('in'))
        self.assertFalse(self.proto.isEncrypted('out'))
        self.assertFalse(self.proto.isEncrypted('both'))
        self.proto.currentEncryptions = MockCipher()
        self.assertTrue(self.proto.isEncrypted('in'))
        self.assertTrue(self.proto.isEncrypted('out'))
        self.assertTrue(self.proto.isEncrypted('both'))
        self.proto.currentEncryptions = transport.SSHCiphers('none', 'none',
                                                             'none', 'none')
        self.assertFalse(self.proto.isEncrypted('in'))
        self.assertFalse(self.proto.isEncrypted('out'))
        self.assertFalse(self.proto.isEncrypted('both'))

        self.assertRaises(TypeError, self.proto.isEncrypted, 'bad')


    def test_isVerified(self):
        """
        Test that the transport accurately reflects its verified status.
        """
        self.assertFalse(self.proto.isVerified('in'))
        self.assertFalse(self.proto.isVerified('out'))
        self.assertFalse(self.proto.isVerified('both'))
        self.proto.currentEncryptions = MockCipher()
        self.assertTrue(self.proto.isVerified('in'))
        self.assertTrue(self.proto.isVerified('out'))
        self.assertTrue(self.proto.isVerified('both'))
        self.proto.currentEncryptions = transport.SSHCiphers('none', 'none',
                                                             'none', 'none')
        self.assertFalse(self.proto.isVerified('in'))
        self.assertFalse(self.proto.isVerified('out'))
        self.assertFalse(self.proto.isVerified('both'))

        self.assertRaises(TypeError, self.proto.isVerified, 'bad')


    def test_loseConnection(self):
        """
        Test that loseConnection sends a disconnect message and closes the
        connection.
        """
        disconnected = [False]
        def stubLoseConnection():
            disconnected[0] = True
        self.transport.loseConnection = stubLoseConnection
        self.proto.loseConnection()
        self.assertEqual(self.packets[0][0], transport.MSG_DISCONNECT)
        self.assertEqual(self.packets[0][1][3],
                          chr(transport.DISCONNECT_CONNECTION_LOST))


    def test_badVersion(self):
        """
        Test that the transport disconnects when it receives a bad version.
        """
        def testBad(version):
            self.packets = []
            self.proto.gotVersion = False
            disconnected = [False]
            def stubLoseConnection():
                disconnected[0] = True
            self.transport.loseConnection = stubLoseConnection
            for c in version + '\r\n':
                self.proto.dataReceived(c)
            self.assertTrue(disconnected[0])
            self.assertEqual(self.packets[0][0], transport.MSG_DISCONNECT)
            self.assertEqual(
                self.packets[0][1][3],
                chr(transport.DISCONNECT_PROTOCOL_VERSION_NOT_SUPPORTED))
        testBad('SSH-1.5-OpenSSH')
        testBad('SSH-3.0-Twisted')
        testBad('GET / HTTP/1.1')


    def test_dataBeforeVersion(self):
        """
        Test that the transport ignores data sent before the version string.
        """
        proto = MockTransportBase()
        proto.makeConnection(proto_helpers.StringTransport())
        data = ("""here's some stuff beforehand
here's some other stuff
""" + proto.ourVersionString + "\r\n")
        [proto.dataReceived(c) for c in data]
        self.assertTrue(proto.gotVersion)
        self.assertEqual(proto.otherVersionString, proto.ourVersionString)


    def test_compatabilityVersion(self):
        """
        Test that the transport treats the compatbility version (1.99)
        as equivalent to version 2.0.
        """
        proto = MockTransportBase()
        proto.makeConnection(proto_helpers.StringTransport())
        proto.dataReceived("SSH-1.99-OpenSSH\n")
        self.assertTrue(proto.gotVersion)
        self.assertEqual(proto.otherVersionString, "SSH-1.99-OpenSSH")


    def test_supportedVersionsAreAllowed(self):
        """
        If an unusual SSH version is received and is included in
        C{supportedVersions}, an unsupported version error is not emitted.
        """
        proto = MockTransportBase()
        proto.supportedVersions = ("9.99", )
        proto.makeConnection(proto_helpers.StringTransport())
        proto.dataReceived("SSH-9.99-OpenSSH\n")
        self.assertFalse(proto.gotUnsupportedVersion)


    def test_unsupportedVersionsCallUnsupportedVersionReceived(self):
        """
        If an unusual SSH version is received and is not included in
        C{supportedVersions}, an unsupported version error is emitted.
        """
        proto = MockTransportBase()
        proto.supportedVersions = ("2.0", )
        proto.makeConnection(proto_helpers.StringTransport())
        proto.dataReceived("SSH-9.99-OpenSSH\n")
        self.assertEqual("9.99", proto.gotUnsupportedVersion)


    def test_badPackets(self):
        """
        Test that the transport disconnects with an error when it receives
        bad packets.
        """
        def testBad(packet, error=transport.DISCONNECT_PROTOCOL_ERROR):
            self.packets = []
            self.proto.buf = packet
            self.assertEqual(self.proto.getPacket(), None)
            self.assertEqual(len(self.packets), 1)
            self.assertEqual(self.packets[0][0], transport.MSG_DISCONNECT)
            self.assertEqual(self.packets[0][1][3], chr(error))

        testBad('\xff' * 8) # big packet
        testBad('\x00\x00\x00\x05\x00BCDE') # length not modulo blocksize
        oldEncryptions = self.proto.currentEncryptions
        self.proto.currentEncryptions = MockCipher()
        testBad('\x00\x00\x00\x08\x06AB123456', # bad MAC
                transport.DISCONNECT_MAC_ERROR)
        self.proto.currentEncryptions.decrypt = lambda x: x[:-1]
        testBad('\x00\x00\x00\x08\x06BCDEFGHIJK') # bad decryption
        self.proto.currentEncryptions = oldEncryptions
        self.proto.incomingCompression = MockCompression()
        def stubDecompress(payload):
            raise Exception('bad compression')
        self.proto.incomingCompression.decompress = stubDecompress
        testBad('\x00\x00\x00\x04\x00BCDE', # bad decompression
                transport.DISCONNECT_COMPRESSION_ERROR)
        self.flushLoggedErrors()


    def test_unimplementedPackets(self):
        """
        Test that unimplemented packet types cause MSG_UNIMPLEMENTED packets
        to be sent.
        """
        seqnum = self.proto.incomingPacketSequence
        def checkUnimplemented(seqnum=seqnum):
            self.assertEqual(self.packets[0][0],
                              transport.MSG_UNIMPLEMENTED)
            self.assertEqual(self.packets[0][1][3], chr(seqnum))
            self.proto.packets = []
            seqnum += 1

        self.proto.dispatchMessage(40, '')
        checkUnimplemented()
        transport.messages[41] = 'MSG_fiction'
        self.proto.dispatchMessage(41, '')
        checkUnimplemented()
        self.proto.dispatchMessage(60, '')
        checkUnimplemented()
        self.proto.setService(MockService())
        self.proto.dispatchMessage(70, '')
        checkUnimplemented()
        self.proto.dispatchMessage(71, '')
        checkUnimplemented()


    def test_getKey(self):
        """
        Test that _getKey generates the correct keys.
        """
        self.proto.sessionID = 'EF'

        k1 = sha1('AB' + 'CD' + 'K' + self.proto.sessionID).digest()
        k2 = sha1('ABCD' + k1).digest()
        self.assertEqual(self.proto._getKey('K', 'AB', 'CD'), k1 + k2)


    def test_multipleClasses(self):
        """
        Test that multiple instances have distinct states.
        """
        proto = self.proto
        proto.dataReceived(self.transport.value())
        proto.currentEncryptions = MockCipher()
        proto.outgoingCompression = MockCompression()
        proto.incomingCompression = MockCompression()
        proto.setService(MockService())
        proto2 = MockTransportBase()
        proto2.makeConnection(proto_helpers.StringTransport())
        proto2.sendIgnore('')
        self.failIfEquals(proto.gotVersion, proto2.gotVersion)
        self.failIfEquals(proto.transport, proto2.transport)
        self.failIfEquals(proto.outgoingPacketSequence,
                          proto2.outgoingPacketSequence)
        self.failIfEquals(proto.incomingPacketSequence,
                          proto2.incomingPacketSequence)
        self.failIfEquals(proto.currentEncryptions,
                          proto2.currentEncryptions)
        self.failIfEquals(proto.service, proto2.service)



class ServerAndClientSSHTransportBaseCase:
    """
    Tests that need to be run on both the server and the client.
    """


    def checkDisconnected(self, kind=None):
        """
        Helper function to check if the transport disconnected.
        """
        if kind is None:
            kind = transport.DISCONNECT_PROTOCOL_ERROR
        self.assertEqual(self.packets[-1][0], transport.MSG_DISCONNECT)
        self.assertEqual(self.packets[-1][1][3], chr(kind))


    def connectModifiedProtocol(self, protoModification,
            kind=None):
        """
        Helper function to connect a modified protocol to the test protocol
        and test for disconnection.
        """
        if kind is None:
            kind = transport.DISCONNECT_KEY_EXCHANGE_FAILED
        proto2 = self.klass()
        protoModification(proto2)
        proto2.makeConnection(proto_helpers.StringTransport())
        self.proto.dataReceived(proto2.transport.value())
        if kind:
            self.checkDisconnected(kind)
        return proto2


    def test_disconnectIfCantMatchKex(self):
        """
        Test that the transport disconnects if it can't match the key
        exchange
        """
        def blankKeyExchanges(proto2):
            proto2.supportedKeyExchanges = []
        self.connectModifiedProtocol(blankKeyExchanges)


    def test_disconnectIfCantMatchKeyAlg(self):
        """
        Like test_disconnectIfCantMatchKex, but for the key algorithm.
        """
        def blankPublicKeys(proto2):
            proto2.supportedPublicKeys = []
        self.connectModifiedProtocol(blankPublicKeys)


    def test_disconnectIfCantMatchCompression(self):
        """
        Like test_disconnectIfCantMatchKex, but for the compression.
        """
        def blankCompressions(proto2):
            proto2.supportedCompressions = []
        self.connectModifiedProtocol(blankCompressions)


    def test_disconnectIfCantMatchCipher(self):
        """
        Like test_disconnectIfCantMatchKex, but for the encryption.
        """
        def blankCiphers(proto2):
            proto2.supportedCiphers = []
        self.connectModifiedProtocol(blankCiphers)


    def test_disconnectIfCantMatchMAC(self):
        """
        Like test_disconnectIfCantMatchKex, but for the MAC.
        """
        def blankMACs(proto2):
            proto2.supportedMACs = []
        self.connectModifiedProtocol(blankMACs)



class ServerSSHTransportTestCase(ServerAndClientSSHTransportBaseCase,
        TransportTestCase):
    """
    Tests for the SSHServerTransport.
    """

    klass = transport.SSHServerTransport


    def setUp(self):
        TransportTestCase.setUp(self)
        self.proto.factory = MockFactory()
        self.proto.factory.startFactory()


    def tearDown(self):
        TransportTestCase.tearDown(self)
        self.proto.factory.stopFactory()
        del self.proto.factory


    def test_KEXINIT(self):
        """
        Test that receiving a KEXINIT packet sets up the correct values on the
        server.
        """
        self.proto.dataReceived( 'SSH-2.0-Twisted\r\n\x00\x00\x01\xd4\t\x14'
                '\x99\x99\x99\x99\x99\x99\x99\x99\x99\x99\x99\x99\x99\x99\x99'
                '\x99\x00\x00\x00=diffie-hellman-group1-sha1,diffie-hellman-g'
                'roup-exchange-sha1\x00\x00\x00\x0fssh-dss,ssh-rsa\x00\x00\x00'
                '\x85aes128-ctr,aes128-cbc,aes192-ctr,aes192-cbc,aes256-ctr,ae'
                's256-cbc,cast128-ctr,cast128-cbc,blowfish-ctr,blowfish-cbc,3d'
                'es-ctr,3des-cbc\x00\x00\x00\x85aes128-ctr,aes128-cbc,aes192-c'
                'tr,aes192-cbc,aes256-ctr,aes256-cbc,cast128-ctr,cast128-cbc,b'
                'lowfish-ctr,blowfish-cbc,3des-ctr,3des-cbc\x00\x00\x00\x12hma'
                'c-md5,hmac-sha1\x00\x00\x00\x12hmac-md5,hmac-sha1\x00\x00\x00'
                '\tnone,zlib\x00\x00\x00\tnone,zlib\x00\x00\x00\x00\x00\x00'
                '\x00\x00\x00\x00\x00\x00\x00\x99\x99\x99\x99\x99\x99\x99\x99'
                '\x99')
        self.assertEqual(self.proto.kexAlg,
                          'diffie-hellman-group1-sha1')
        self.assertEqual(self.proto.keyAlg,
                          'ssh-dss')
        self.assertEqual(self.proto.outgoingCompressionType,
                          'none')
        self.assertEqual(self.proto.incomingCompressionType,
                          'none')
        ne = self.proto.nextEncryptions
        self.assertEqual(ne.outCipType, 'aes128-ctr')
        self.assertEqual(ne.inCipType, 'aes128-ctr')
        self.assertEqual(ne.outMACType, 'hmac-md5')
        self.assertEqual(ne.inMACType, 'hmac-md5')


    def test_ignoreGuessPacketKex(self):
        """
        The client is allowed to send a guessed key exchange packet
        after it sends the KEXINIT packet.  However, if the key exchanges
        do not match, that guess packet must be ignored.  This tests that
        the packet is ignored in the case of the key exchange method not
        matching.
        """
        kexInitPacket = '\x00' * 16 + (
            ''.join([common.NS(x) for x in
                     [','.join(y) for y in
                      [self.proto.supportedKeyExchanges[::-1],
                       self.proto.supportedPublicKeys,
                       self.proto.supportedCiphers,
                       self.proto.supportedCiphers,
                       self.proto.supportedMACs,
                       self.proto.supportedMACs,
                       self.proto.supportedCompressions,
                       self.proto.supportedCompressions,
                       self.proto.supportedLanguages,
                       self.proto.supportedLanguages]]])) + (
            '\xff\x00\x00\x00\x00')
        self.proto.ssh_KEXINIT(kexInitPacket)
        self.assertTrue(self.proto.ignoreNextPacket)
        self.proto.ssh_DEBUG("\x01\x00\x00\x00\x04test\x00\x00\x00\x00")
        self.assertTrue(self.proto.ignoreNextPacket)


        self.proto.ssh_KEX_DH_GEX_REQUEST_OLD('\x00\x00\x08\x00')
        self.assertFalse(self.proto.ignoreNextPacket)
        self.assertEqual(self.packets, [])
        self.proto.ignoreNextPacket = True

        self.proto.ssh_KEX_DH_GEX_REQUEST('\x00\x00\x08\x00' * 3)
        self.assertFalse(self.proto.ignoreNextPacket)
        self.assertEqual(self.packets, [])


    def test_ignoreGuessPacketKey(self):
        """
        Like test_ignoreGuessPacketKex, but for an incorrectly guessed
        public key format.
        """
        kexInitPacket = '\x00' * 16 + (
            ''.join([common.NS(x) for x in
                     [','.join(y) for y in
                      [self.proto.supportedKeyExchanges,
                       self.proto.supportedPublicKeys[::-1],
                       self.proto.supportedCiphers,
                       self.proto.supportedCiphers,
                       self.proto.supportedMACs,
                       self.proto.supportedMACs,
                       self.proto.supportedCompressions,
                       self.proto.supportedCompressions,
                       self.proto.supportedLanguages,
                       self.proto.supportedLanguages]]])) + (
            '\xff\x00\x00\x00\x00')
        self.proto.ssh_KEXINIT(kexInitPacket)
        self.assertTrue(self.proto.ignoreNextPacket)
        self.proto.ssh_DEBUG("\x01\x00\x00\x00\x04test\x00\x00\x00\x00")
        self.assertTrue(self.proto.ignoreNextPacket)

        self.proto.ssh_KEX_DH_GEX_REQUEST_OLD('\x00\x00\x08\x00')
        self.assertFalse(self.proto.ignoreNextPacket)
        self.assertEqual(self.packets, [])
        self.proto.ignoreNextPacket = True

        self.proto.ssh_KEX_DH_GEX_REQUEST('\x00\x00\x08\x00' * 3)
        self.assertFalse(self.proto.ignoreNextPacket)
        self.assertEqual(self.packets, [])


    def test_KEXDH_INIT(self):
        """
        Test that the KEXDH_INIT packet causes the server to send a
        KEXDH_REPLY with the server's public key and a signature.
        """
        self.proto.supportedKeyExchanges = ['diffie-hellman-group1-sha1']
        self.proto.supportedPublicKeys = ['ssh-rsa']
        self.proto.dataReceived(self.transport.value())
        e = pow(transport.DH_GENERATOR, 5000,
                transport.DH_PRIME)

        self.proto.ssh_KEX_DH_GEX_REQUEST_OLD(common.MP(e))
        y = common.getMP('\x00\x00\x00\x40' + '\x99' * 64)[0]
        f = common._MPpow(transport.DH_GENERATOR, y, transport.DH_PRIME)
        sharedSecret = common._MPpow(e, y, transport.DH_PRIME)

        h = sha1()
        h.update(common.NS(self.proto.ourVersionString) * 2)
        h.update(common.NS(self.proto.ourKexInitPayload) * 2)
        h.update(common.NS(self.proto.factory.publicKeys['ssh-rsa'].blob()))
        h.update(common.MP(e))
        h.update(f)
        h.update(sharedSecret)
        exchangeHash = h.digest()

        signature = self.proto.factory.privateKeys['ssh-rsa'].sign(
                exchangeHash)

        self.assertEqual(
            self.packets,
            [(transport.MSG_KEXDH_REPLY,
              common.NS(self.proto.factory.publicKeys['ssh-rsa'].blob())
              + f + common.NS(signature)),
             (transport.MSG_NEWKEYS, '')])


    def test_KEX_DH_GEX_REQUEST_OLD(self):
        """
        Test that the KEX_DH_GEX_REQUEST_OLD message causes the server
        to reply with a KEX_DH_GEX_GROUP message with the correct
        Diffie-Hellman group.
        """
        self.proto.supportedKeyExchanges = [
                'diffie-hellman-group-exchange-sha1']
        self.proto.supportedPublicKeys = ['ssh-rsa']
        self.proto.dataReceived(self.transport.value())
        self.proto.ssh_KEX_DH_GEX_REQUEST_OLD('\x00\x00\x04\x00')
        self.assertEqual(
            self.packets,
            [(transport.MSG_KEX_DH_GEX_GROUP,
              common.MP(transport.DH_PRIME) + '\x00\x00\x00\x01\x02')])
        self.assertEqual(self.proto.g, 2)
        self.assertEqual(self.proto.p, transport.DH_PRIME)


    def test_KEX_DH_GEX_REQUEST_OLD_badKexAlg(self):
        """
        Test that if the server recieves a KEX_DH_GEX_REQUEST_OLD message
        and the key exchange algorithm is not 'diffie-hellman-group1-sha1' or
        'diffie-hellman-group-exchange-sha1', we raise a ConchError.
        """
        self.proto.kexAlg = None
        self.assertRaises(ConchError, self.proto.ssh_KEX_DH_GEX_REQUEST_OLD,
                None)


    def test_KEX_DH_GEX_REQUEST(self):
        """
        Test that the KEX_DH_GEX_REQUEST message causes the server to reply
        with a KEX_DH_GEX_GROUP message with the correct Diffie-Hellman
        group.
        """
        self.proto.supportedKeyExchanges = [
            'diffie-hellman-group-exchange-sha1']
        self.proto.supportedPublicKeys = ['ssh-rsa']
        self.proto.dataReceived(self.transport.value())
        self.proto.ssh_KEX_DH_GEX_REQUEST('\x00\x00\x04\x00\x00\x00\x08\x00' +
                                          '\x00\x00\x0c\x00')
        self.assertEqual(
            self.packets,
            [(transport.MSG_KEX_DH_GEX_GROUP,
              common.MP(transport.DH_PRIME) + '\x00\x00\x00\x01\x03')])
        self.assertEqual(self.proto.g, 3)
        self.assertEqual(self.proto.p, transport.DH_PRIME)


    def test_KEX_DH_GEX_INIT_after_REQUEST(self):
        """
        Test that the KEX_DH_GEX_INIT message after the client sends
        KEX_DH_GEX_REQUEST causes the server to send a KEX_DH_GEX_INIT message
        with a public key and signature.
        """
        self.test_KEX_DH_GEX_REQUEST()
        e = pow(self.proto.g, 3, self.proto.p)
        y = common.getMP('\x00\x00\x00\x80' + '\x99' * 128)[0]
        f = common._MPpow(self.proto.g, y, self.proto.p)
        sharedSecret = common._MPpow(e, y, self.proto.p)
        h = sha1()
        h.update(common.NS(self.proto.ourVersionString) * 2)
        h.update(common.NS(self.proto.ourKexInitPayload) * 2)
        h.update(common.NS(self.proto.factory.publicKeys['ssh-rsa'].blob()))
        h.update('\x00\x00\x04\x00\x00\x00\x08\x00\x00\x00\x0c\x00')
        h.update(common.MP(self.proto.p))
        h.update(common.MP(self.proto.g))
        h.update(common.MP(e))
        h.update(f)
        h.update(sharedSecret)
        exchangeHash = h.digest()
        self.proto.ssh_KEX_DH_GEX_INIT(common.MP(e))
        self.assertEqual(
            self.packets[1],
            (transport.MSG_KEX_DH_GEX_REPLY,
             common.NS(self.proto.factory.publicKeys['ssh-rsa'].blob()) +
             f + common.NS(self.proto.factory.privateKeys['ssh-rsa'].sign(
                        exchangeHash))))


    def test_KEX_DH_GEX_INIT_after_REQUEST_OLD(self):
        """
        Test that the KEX_DH_GEX_INIT message after the client sends
        KEX_DH_GEX_REQUEST_OLD causes the server to sent a KEX_DH_GEX_INIT
        message with a public key and signature.
        """
        self.test_KEX_DH_GEX_REQUEST_OLD()
        e = pow(self.proto.g, 3, self.proto.p)
        y = common.getMP('\x00\x00\x00\x80' + '\x99' * 128)[0]
        f = common._MPpow(self.proto.g, y, self.proto.p)
        sharedSecret = common._MPpow(e, y, self.proto.p)
        h = sha1()
        h.update(common.NS(self.proto.ourVersionString) * 2)
        h.update(common.NS(self.proto.ourKexInitPayload) * 2)
        h.update(common.NS(self.proto.factory.publicKeys['ssh-rsa'].blob()))
        h.update('\x00\x00\x04\x00')
        h.update(common.MP(self.proto.p))
        h.update(common.MP(self.proto.g))
        h.update(common.MP(e))
        h.update(f)
        h.update(sharedSecret)
        exchangeHash = h.digest()
        self.proto.ssh_KEX_DH_GEX_INIT(common.MP(e))
        self.assertEqual(
            self.packets[1:],
            [(transport.MSG_KEX_DH_GEX_REPLY,
              common.NS(self.proto.factory.publicKeys['ssh-rsa'].blob()) +
              f + common.NS(self.proto.factory.privateKeys['ssh-rsa'].sign(
                            exchangeHash))),
             (transport.MSG_NEWKEYS, '')])


    def test_keySetup(self):
        """
        Test that _keySetup sets up the next encryption keys.
        """
        self.proto.nextEncryptions = MockCipher()
        self.simulateKeyExchange('AB', 'CD')
        self.assertEqual(self.proto.sessionID, 'CD')
        self.simulateKeyExchange('AB', 'EF')
        self.assertEqual(self.proto.sessionID, 'CD')
        self.assertEqual(self.packets[-1], (transport.MSG_NEWKEYS, ''))
        newKeys = [self.proto._getKey(c, 'AB', 'EF') for c in 'ABCDEF']
        self.assertEqual(
            self.proto.nextEncryptions.keys,
            (newKeys[1], newKeys[3], newKeys[0], newKeys[2], newKeys[5],
             newKeys[4]))


    def test_NEWKEYS(self):
        """
        Test that NEWKEYS transitions the keys in nextEncryptions to
        currentEncryptions.
        """
        self.test_KEXINIT()

        self.proto.nextEncryptions = transport.SSHCiphers('none', 'none',
                                                          'none', 'none')
        self.proto.ssh_NEWKEYS('')
        self.assertIdentical(self.proto.currentEncryptions,
                             self.proto.nextEncryptions)
        self.assertIdentical(self.proto.outgoingCompression, None)
        self.assertIdentical(self.proto.incomingCompression, None)
        self.proto.outgoingCompressionType = 'zlib'
        self.simulateKeyExchange('AB', 'CD')
        self.proto.ssh_NEWKEYS('')
        self.failIfIdentical(self.proto.outgoingCompression, None)
        self.proto.incomingCompressionType = 'zlib'
        self.simulateKeyExchange('AB', 'EF')
        self.proto.ssh_NEWKEYS('')
        self.failIfIdentical(self.proto.incomingCompression, None)


    def test_SERVICE_REQUEST(self):
        """
        Test that the SERVICE_REQUEST message requests and starts a
        service.
        """
        self.proto.ssh_SERVICE_REQUEST(common.NS('ssh-userauth'))
        self.assertEqual(self.packets, [(transport.MSG_SERVICE_ACCEPT,
                                          common.NS('ssh-userauth'))])
        self.assertEqual(self.proto.service.name, 'MockService')


    def test_disconnectNEWKEYSData(self):
        """
        Test that NEWKEYS disconnects if it receives data.
        """
        self.proto.ssh_NEWKEYS("bad packet")
        self.checkDisconnected()


    def test_disconnectSERVICE_REQUESTBadService(self):
        """
        Test that SERVICE_REQUESTS disconnects if an unknown service is
        requested.
        """
        self.proto.ssh_SERVICE_REQUEST(common.NS('no service'))
        self.checkDisconnected(transport.DISCONNECT_SERVICE_NOT_AVAILABLE)



class ClientSSHTransportTestCase(ServerAndClientSSHTransportBaseCase,
        TransportTestCase):
    """
    Tests for SSHClientTransport.
    """

    klass = transport.SSHClientTransport


    def test_KEXINIT(self):
        """
        Test that receiving a KEXINIT packet sets up the correct values on the
        client.  The way algorithms are picks is that the first item in the
        client's list that is also in the server's list is chosen.
        """
        self.proto.dataReceived( 'SSH-2.0-Twisted\r\n\x00\x00\x01\xd4\t\x14'
                '\x99\x99\x99\x99\x99\x99\x99\x99\x99\x99\x99\x99\x99\x99\x99'
                '\x99\x00\x00\x00=diffie-hellman-group1-sha1,diffie-hellman-g'
                'roup-exchange-sha1\x00\x00\x00\x0fssh-dss,ssh-rsa\x00\x00\x00'
                '\x85aes128-ctr,aes128-cbc,aes192-ctr,aes192-cbc,aes256-ctr,ae'
                's256-cbc,cast128-ctr,cast128-cbc,blowfish-ctr,blowfish-cbc,3d'
                'es-ctr,3des-cbc\x00\x00\x00\x85aes128-ctr,aes128-cbc,aes192-c'
                'tr,aes192-cbc,aes256-ctr,aes256-cbc,cast128-ctr,cast128-cbc,b'
                'lowfish-ctr,blowfish-cbc,3des-ctr,3des-cbc\x00\x00\x00\x12hma'
                'c-md5,hmac-sha1\x00\x00\x00\x12hmac-md5,hmac-sha1\x00\x00\x00'
                '\tzlib,none\x00\x00\x00\tzlib,none\x00\x00\x00\x00\x00\x00'
                '\x00\x00\x00\x00\x00\x00\x00\x99\x99\x99\x99\x99\x99\x99\x99'
                '\x99')
        self.assertEqual(self.proto.kexAlg,
                          'diffie-hellman-group-exchange-sha1')
        self.assertEqual(self.proto.keyAlg,
                          'ssh-rsa')
        self.assertEqual(self.proto.outgoingCompressionType,
                          'none')
        self.assertEqual(self.proto.incomingCompressionType,
                          'none')
        ne = self.proto.nextEncryptions
        self.assertEqual(ne.outCipType, 'aes256-ctr')
        self.assertEqual(ne.inCipType, 'aes256-ctr')
        self.assertEqual(ne.outMACType, 'hmac-sha1')
        self.assertEqual(ne.inMACType, 'hmac-sha1')


    def verifyHostKey(self, pubKey, fingerprint):
        """
        Mock version of SSHClientTransport.verifyHostKey.
        """
        self.calledVerifyHostKey = True
        self.assertEqual(pubKey, self.blob)
        self.assertEqual(fingerprint.replace(':', ''),
                          md5(pubKey).hexdigest())
        return defer.succeed(True)


    def setUp(self):
        TransportTestCase.setUp(self)
        self.blob = keys.Key.fromString(keydata.publicRSA_openssh).blob()
        self.privObj = keys.Key.fromString(keydata.privateRSA_openssh)
        self.calledVerifyHostKey = False
        self.proto.verifyHostKey = self.verifyHostKey


    def test_notImplementedClientMethods(self):
        """
        verifyHostKey() should return a Deferred which fails with a
        NotImplementedError exception.  connectionSecure() should raise
        NotImplementedError().
        """
        self.assertRaises(NotImplementedError, self.klass().connectionSecure)
        def _checkRaises(f):
            f.trap(NotImplementedError)
        d = self.klass().verifyHostKey(None, None)
        return d.addCallback(self.fail).addErrback(_checkRaises)


    def test_KEXINIT_groupexchange(self):
        """
        Test that a KEXINIT packet with a group-exchange key exchange results
        in a KEX_DH_GEX_REQUEST_OLD message..
        """
        self.proto.supportedKeyExchanges = [
            'diffie-hellman-group-exchange-sha1']
        self.proto.dataReceived(self.transport.value())
        self.assertEqual(self.packets, [(transport.MSG_KEX_DH_GEX_REQUEST_OLD,
                                          '\x00\x00\x08\x00')])


    def test_KEXINIT_group1(self):
        """
        Like test_KEXINIT_groupexchange, but for the group-1 key exchange.
        """
        self.proto.supportedKeyExchanges = ['diffie-hellman-group1-sha1']
        self.proto.dataReceived(self.transport.value())
        self.assertEqual(common.MP(self.proto.x)[5:], '\x99' * 64)
        self.assertEqual(self.packets,
                          [(transport.MSG_KEXDH_INIT, self.proto.e)])


    def test_KEXINIT_badKexAlg(self):
        """
        Test that the client raises a ConchError if it receives a
        KEXINIT message bug doesn't have a key exchange algorithm that we
        understand.
        """
        self.proto.supportedKeyExchanges = ['diffie-hellman-group2-sha1']
        data = self.transport.value().replace('group1', 'group2')
        self.assertRaises(ConchError, self.proto.dataReceived, data)


    def test_KEXDH_REPLY(self):
        """
        Test that the KEXDH_REPLY message verifies the server.
        """
        self.test_KEXINIT_group1()

        sharedSecret = common._MPpow(transport.DH_GENERATOR,
                                     self.proto.x, transport.DH_PRIME)
        h = sha1()
        h.update(common.NS(self.proto.ourVersionString) * 2)
        h.update(common.NS(self.proto.ourKexInitPayload) * 2)
        h.update(common.NS(self.blob))
        h.update(self.proto.e)
        h.update('\x00\x00\x00\x01\x02') # f
        h.update(sharedSecret)
        exchangeHash = h.digest()

        def _cbTestKEXDH_REPLY(value):
            self.assertIdentical(value, None)
            self.assertEqual(self.calledVerifyHostKey, True)
            self.assertEqual(self.proto.sessionID, exchangeHash)

        signature = self.privObj.sign(exchangeHash)

        d = self.proto.ssh_KEX_DH_GEX_GROUP(
            (common.NS(self.blob) + '\x00\x00\x00\x01\x02' +
             common.NS(signature)))
        d.addCallback(_cbTestKEXDH_REPLY)

        return d


    def test_KEX_DH_GEX_GROUP(self):
        """
        Test that the KEX_DH_GEX_GROUP message results in a
        KEX_DH_GEX_INIT message with the client's Diffie-Hellman public key.
        """
        self.test_KEXINIT_groupexchange()
        self.proto.ssh_KEX_DH_GEX_GROUP(
            '\x00\x00\x00\x01\x0f\x00\x00\x00\x01\x02')
        self.assertEqual(self.proto.p, 15)
        self.assertEqual(self.proto.g, 2)
        self.assertEqual(common.MP(self.proto.x)[5:], '\x99' * 40)
        self.assertEqual(self.proto.e,
                          common.MP(pow(2, self.proto.x, 15)))
        self.assertEqual(self.packets[1:], [(transport.MSG_KEX_DH_GEX_INIT,
                                              self.proto.e)])


    def test_KEX_DH_GEX_REPLY(self):
        """
        Test that the KEX_DH_GEX_REPLY message results in a verified
        server.
        """

        self.test_KEX_DH_GEX_GROUP()
        sharedSecret = common._MPpow(3, self.proto.x, self.proto.p)
        h = sha1()
        h.update(common.NS(self.proto.ourVersionString) * 2)
        h.update(common.NS(self.proto.ourKexInitPayload) * 2)
        h.update(common.NS(self.blob))
        h.update('\x00\x00\x08\x00\x00\x00\x00\x01\x0f\x00\x00\x00\x01\x02')
        h.update(self.proto.e)
        h.update('\x00\x00\x00\x01\x03') # f
        h.update(sharedSecret)
        exchangeHash = h.digest()

        def _cbTestKEX_DH_GEX_REPLY(value):
            self.assertIdentical(value, None)
            self.assertEqual(self.calledVerifyHostKey, True)
            self.assertEqual(self.proto.sessionID, exchangeHash)

        signature = self.privObj.sign(exchangeHash)

        d = self.proto.ssh_KEX_DH_GEX_REPLY(
            common.NS(self.blob) +
            '\x00\x00\x00\x01\x03' +
            common.NS(signature))
        d.addCallback(_cbTestKEX_DH_GEX_REPLY)
        return d


    def test_keySetup(self):
        """
        Test that _keySetup sets up the next encryption keys.
        """
        self.proto.nextEncryptions = MockCipher()
        self.simulateKeyExchange('AB', 'CD')
        self.assertEqual(self.proto.sessionID, 'CD')
        self.simulateKeyExchange('AB', 'EF')
        self.assertEqual(self.proto.sessionID, 'CD')
        self.assertEqual(self.packets[-1], (transport.MSG_NEWKEYS, ''))
        newKeys = [self.proto._getKey(c, 'AB', 'EF') for c in 'ABCDEF']
        self.assertEqual(self.proto.nextEncryptions.keys,
                          (newKeys[0], newKeys[2], newKeys[1], newKeys[3],
                           newKeys[4], newKeys[5]))


    def test_NEWKEYS(self):
        """
        Test that NEWKEYS transitions the keys from nextEncryptions to
        currentEncryptions.
        """
        self.test_KEXINIT()
        secure = [False]
        def stubConnectionSecure():
            secure[0] = True
        self.proto.connectionSecure = stubConnectionSecure

        self.proto.nextEncryptions = transport.SSHCiphers(
            'none', 'none', 'none', 'none')
        self.simulateKeyExchange('AB', 'CD')
        self.assertNotIdentical(
            self.proto.currentEncryptions, self.proto.nextEncryptions)

        self.proto.nextEncryptions = MockCipher()
        self.proto.ssh_NEWKEYS('')
        self.assertIdentical(self.proto.outgoingCompression, None)
        self.assertIdentical(self.proto.incomingCompression, None)
        self.assertIdentical(self.proto.currentEncryptions,
                             self.proto.nextEncryptions)
        self.assertTrue(secure[0])
        self.proto.outgoingCompressionType = 'zlib'
        self.simulateKeyExchange('AB', 'GH')
        self.proto.ssh_NEWKEYS('')
        self.failIfIdentical(self.proto.outgoingCompression, None)
        self.proto.incomingCompressionType = 'zlib'
        self.simulateKeyExchange('AB', 'IJ')
        self.proto.ssh_NEWKEYS('')
        self.failIfIdentical(self.proto.incomingCompression, None)


    def test_SERVICE_ACCEPT(self):
        """
        Test that the SERVICE_ACCEPT packet starts the requested service.
        """
        self.proto.instance = MockService()
        self.proto.ssh_SERVICE_ACCEPT('\x00\x00\x00\x0bMockService')
        self.assertTrue(self.proto.instance.started)


    def test_requestService(self):
        """
        Test that requesting a service sends a SERVICE_REQUEST packet.
        """
        self.proto.requestService(MockService())
        self.assertEqual(self.packets, [(transport.MSG_SERVICE_REQUEST,
                                          '\x00\x00\x00\x0bMockService')])


    def test_disconnectKEXDH_REPLYBadSignature(self):
        """
        Test that KEXDH_REPLY disconnects if the signature is bad.
        """
        self.test_KEXDH_REPLY()
        self.proto._continueKEXDH_REPLY(None, self.blob, 3, "bad signature")
        self.checkDisconnected(transport.DISCONNECT_KEY_EXCHANGE_FAILED)


    def test_disconnectGEX_REPLYBadSignature(self):
        """
        Like test_disconnectKEXDH_REPLYBadSignature, but for DH_GEX_REPLY.
        """
        self.test_KEX_DH_GEX_REPLY()
        self.proto._continueGEX_REPLY(None, self.blob, 3, "bad signature")
        self.checkDisconnected(transport.DISCONNECT_KEY_EXCHANGE_FAILED)


    def test_disconnectNEWKEYSData(self):
        """
        Test that NEWKEYS disconnects if it receives data.
        """
        self.proto.ssh_NEWKEYS("bad packet")
        self.checkDisconnected()


    def test_disconnectSERVICE_ACCEPT(self):
        """
        Test that SERVICE_ACCEPT disconnects if the accepted protocol is
        differet from the asked-for protocol.
        """
        self.proto.instance = MockService()
        self.proto.ssh_SERVICE_ACCEPT('\x00\x00\x00\x03bad')
        self.checkDisconnected()



class SSHCiphersTestCase(unittest.TestCase):
    """
    Tests for the SSHCiphers helper class.
    """
    if Crypto is None:
        skip = "cannot run w/o PyCrypto"

    if pyasn1 is None:
        skip = "cannot run w/o PyASN1"


    def test_init(self):
        """
        Test that the initializer sets up the SSHCiphers object.
        """
        ciphers = transport.SSHCiphers('A', 'B', 'C', 'D')
        self.assertEqual(ciphers.outCipType, 'A')
        self.assertEqual(ciphers.inCipType, 'B')
        self.assertEqual(ciphers.outMACType, 'C')
        self.assertEqual(ciphers.inMACType, 'D')


    def test_getCipher(self):
        """
        Test that the _getCipher method returns the correct cipher.
        """
        ciphers = transport.SSHCiphers('A', 'B', 'C', 'D')
        iv = key = '\x00' * 16
        for cipName, (modName, keySize, counter) in ciphers.cipherMap.items():
            cip = ciphers._getCipher(cipName, iv, key)
            if cipName == 'none':
                self.assertIsInstance(cip, transport._DummyCipher)
            else:
                self.assertTrue(str(cip).startswith('<' + modName))


    def test_getMAC(self):
        """
        Test that the _getMAC method returns the correct MAC.
        """
        ciphers = transport.SSHCiphers('A', 'B', 'C', 'D')
        key = '\x00' * 64
        for macName, mac in ciphers.macMap.items():
            mod = ciphers._getMAC(macName, key)
            if macName == 'none':
                self.assertIdentical(mac, None)
            else:
                self.assertEqual(mod[0], mac)
                self.assertEqual(mod[1],
                                  Crypto.Cipher.XOR.new('\x36').encrypt(key))
                self.assertEqual(mod[2],
                                  Crypto.Cipher.XOR.new('\x5c').encrypt(key))
                self.assertEqual(mod[3], len(mod[0]().digest()))


    def test_setKeysCiphers(self):
        """
        Test that setKeys sets up the ciphers.
        """
        key = '\x00' * 64
        cipherItems = transport.SSHCiphers.cipherMap.items()
        for cipName, (modName, keySize, counter) in cipherItems:
            encCipher = transport.SSHCiphers(cipName, 'none', 'none', 'none')
            decCipher = transport.SSHCiphers('none', cipName, 'none', 'none')
            cip = encCipher._getCipher(cipName, key, key)
            bs = cip.block_size
            encCipher.setKeys(key, key, '', '', '', '')
            decCipher.setKeys('', '', key, key, '', '')
            self.assertEqual(encCipher.encBlockSize, bs)
            self.assertEqual(decCipher.decBlockSize, bs)
            enc = cip.encrypt(key[:bs])
            enc2 = cip.encrypt(key[:bs])
            if counter:
                self.failIfEquals(enc, enc2)
            self.assertEqual(encCipher.encrypt(key[:bs]), enc)
            self.assertEqual(encCipher.encrypt(key[:bs]), enc2)
            self.assertEqual(decCipher.decrypt(enc), key[:bs])
            self.assertEqual(decCipher.decrypt(enc2), key[:bs])


    def test_setKeysMACs(self):
        """
        Test that setKeys sets up the MACs.
        """
        key = '\x00' * 64
        for macName, mod in transport.SSHCiphers.macMap.items():
            outMac = transport.SSHCiphers('none', 'none', macName, 'none')
            inMac = transport.SSHCiphers('none', 'none', 'none', macName)
            outMac.setKeys('', '', '', '', key, '')
            inMac.setKeys('', '', '', '', '', key)
            if mod:
                ds = mod().digest_size
            else:
                ds = 0
            self.assertEqual(inMac.verifyDigestSize, ds)
            if mod:
                mod, i, o, ds = outMac._getMAC(macName, key)
            seqid = 0
            data = key
            packet = '\x00' * 4 + key
            if mod:
                mac = mod(o + mod(i + packet).digest()).digest()
            else:
                mac = ''
            self.assertEqual(outMac.makeMAC(seqid, data), mac)
            self.assertTrue(inMac.verify(seqid, data, mac))



class CounterTestCase(unittest.TestCase):
    """
    Tests for the _Counter helper class.
    """
    if Crypto is None:
        skip = "cannot run w/o PyCrypto"

    if pyasn1 is None:
        skip = "cannot run w/o PyASN1"


    def test_init(self):
        """
        Test that the counter is initialized correctly.
        """
        counter = transport._Counter('\x00' * 8 + '\xff' * 8, 8)
        self.assertEqual(counter.blockSize, 8)
        self.assertEqual(counter.count.tostring(), '\x00' * 8)


    def test_count(self):
        """
        Test that the counter counts incrementally and wraps at the top.
        """
        counter = transport._Counter('\x00', 1)
        self.assertEqual(counter(), '\x01')
        self.assertEqual(counter(), '\x02')
        [counter() for i in range(252)]
        self.assertEqual(counter(), '\xff')
        self.assertEqual(counter(), '\x00')



class TransportLoopbackTestCase(unittest.TestCase):
    """
    Test the server transport and client transport against each other,
    """
    if Crypto is None:
        skip = "cannot run w/o PyCrypto"

    if pyasn1 is None:
        skip = "cannot run w/o PyASN1"


    def _runClientServer(self, mod):
        """
        Run an async client and server, modifying each using the mod function
        provided.  Returns a Deferred called back when both Protocols have
        disconnected.

        @type mod: C{func}
        @rtype: C{defer.Deferred}
        """
        factory = MockFactory()
        server = transport.SSHServerTransport()
        server.factory = factory
        factory.startFactory()
        server.errors = []
        server.receiveError = lambda code, desc: server.errors.append((
                code, desc))
        client = transport.SSHClientTransport()
        client.verifyHostKey = lambda x, y: defer.succeed(None)
        client.errors = []
        client.receiveError = lambda code, desc: client.errors.append((
                code, desc))
        client.connectionSecure = lambda: client.loseConnection()
        server = mod(server)
        client = mod(client)
        def check(ignored, server, client):
            name = repr([server.supportedCiphers[0],
                         server.supportedMACs[0],
                         server.supportedKeyExchanges[0],
                         server.supportedCompressions[0]])
            self.assertEqual(client.errors, [])
            self.assertEqual(server.errors, [(
                        transport.DISCONNECT_CONNECTION_LOST,
                        "user closed connection")])
            if server.supportedCiphers[0] == 'none':
                self.assertFalse(server.isEncrypted(), name)
                self.assertFalse(client.isEncrypted(), name)
            else:
                self.assertTrue(server.isEncrypted(), name)
                self.assertTrue(client.isEncrypted(), name)
            if server.supportedMACs[0] == 'none':
                self.assertFalse(server.isVerified(), name)
                self.assertFalse(client.isVerified(), name)
            else:
                self.assertTrue(server.isVerified(), name)
                self.assertTrue(client.isVerified(), name)

        d = loopback.loopbackAsync(server, client)
        d.addCallback(check, server, client)
        return d


    def test_ciphers(self):
        """
        Test that the client and server play nicely together, in all
        the various combinations of ciphers.
        """
        deferreds = []
        for cipher in transport.SSHTransportBase.supportedCiphers + ['none']:
            def setCipher(proto):
                proto.supportedCiphers = [cipher]
                return proto
            deferreds.append(self._runClientServer(setCipher))
        return defer.DeferredList(deferreds, fireOnOneErrback=True)


    def test_macs(self):
        """
        Like test_ciphers, but for the various MACs.
        """
        deferreds = []
        for mac in transport.SSHTransportBase.supportedMACs + ['none']:
            def setMAC(proto):
                proto.supportedMACs = [mac]
                return proto
            deferreds.append(self._runClientServer(setMAC))
        return defer.DeferredList(deferreds, fireOnOneErrback=True)


    def test_keyexchanges(self):
        """
        Like test_ciphers, but for the various key exchanges.
        """
        deferreds = []
        for kex in transport.SSHTransportBase.supportedKeyExchanges:
            def setKeyExchange(proto):
                proto.supportedKeyExchanges = [kex]
                return proto
            deferreds.append(self._runClientServer(setKeyExchange))
        return defer.DeferredList(deferreds, fireOnOneErrback=True)


    def test_compressions(self):
        """
        Like test_ciphers, but for the various compressions.
        """
        deferreds = []
        for compression in transport.SSHTransportBase.supportedCompressions:
            def setCompression(proto):
                proto.supportedCompressions = [compression]
                return proto
            deferreds.append(self._runClientServer(setCompression))
        return defer.DeferredList(deferreds, fireOnOneErrback=True)


class RandomNumberTestCase(unittest.TestCase):
    """
    Tests for the random number generator L{_getRandomNumber} and private
    key generator L{_generateX}.
    """
    skip = dependencySkip

    def test_usesSuppliedRandomFunction(self):
        """
        L{_getRandomNumber} returns an integer constructed directly from the
        bytes returned by the random byte generator passed to it.
        """
        def random(bytes):
            # The number of bytes requested will be the value of each byte
            # we return.
            return chr(bytes) * bytes
        self.assertEqual(
            transport._getRandomNumber(random, 32),
            4 << 24 | 4 << 16 | 4 << 8 | 4)


    def test_rejectsNonByteMultiples(self):
        """
        L{_getRandomNumber} raises L{ValueError} if the number of bits
        passed to L{_getRandomNumber} is not a multiple of 8.
        """
        self.assertRaises(
            ValueError,
            transport._getRandomNumber, None, 9)


    def test_excludesSmall(self):
        """
        If the random byte generator passed to L{_generateX} produces bytes
        which would result in 0 or 1 being returned, these bytes are
        discarded and another attempt is made to produce a larger value.
        """
        results = [chr(0), chr(1), chr(127)]
        def random(bytes):
            return results.pop(0) * bytes
        self.assertEqual(
            transport._generateX(random, 8),
            127)


    def test_excludesLarge(self):
        """
        If the random byte generator passed to L{_generateX} produces bytes
        which would result in C{(2 ** bits) - 1} being returned, these bytes
        are discarded and another attempt is made to produce a smaller
        value.
        """
        results = [chr(255), chr(64)]
        def random(bytes):
            return results.pop(0) * bytes
        self.assertEqual(
            transport._generateX(random, 8),
            64)



class OldFactoryTestCase(unittest.TestCase):
    """
    The old C{SSHFactory.getPublicKeys}() returned mappings of key names to
    strings of key blobs and mappings of key names to PyCrypto key objects from
    C{SSHFactory.getPrivateKeys}() (they could also be specified with the
    C{publicKeys} and C{privateKeys} attributes).  This is no longer supported
    by the C{SSHServerTransport}, so we warn the user if they create an old
    factory.
    """

    if Crypto is None:
        skip = "cannot run w/o PyCrypto"

    if pyasn1 is None:
        skip = "cannot run w/o PyASN1"


    def test_getPublicKeysWarning(self):
        """
        If the return value of C{getPublicKeys}() isn't a mapping from key
        names to C{Key} objects, then warn the user and convert the mapping.
        """
        sshFactory = MockOldFactoryPublicKeys()
        self.assertWarns(DeprecationWarning,
                "Returning a mapping from strings to strings from"
                " getPublicKeys()/publicKeys (in %s) is deprecated.  Return "
                "a mapping from strings to Key objects instead." %
                (qual(MockOldFactoryPublicKeys),),
                factory.__file__, sshFactory.startFactory)
        self.assertEqual(sshFactory.publicKeys, MockFactory().getPublicKeys())


    def test_getPrivateKeysWarning(self):
        """
        If the return value of C{getPrivateKeys}() isn't a mapping from key
        names to C{Key} objects, then warn the user and convert the mapping.
        """
        sshFactory = MockOldFactoryPrivateKeys()
        self.assertWarns(DeprecationWarning,
                "Returning a mapping from strings to PyCrypto key objects from"
                " getPrivateKeys()/privateKeys (in %s) is deprecated.  Return"
                " a mapping from strings to Key objects instead." %
                (qual(MockOldFactoryPrivateKeys),),
                factory.__file__, sshFactory.startFactory)
        self.assertEqual(sshFactory.privateKeys,
                          MockFactory().getPrivateKeys())


    def test_publicKeysWarning(self):
        """
        If the value of the C{publicKeys} attribute isn't a mapping from key
        names to C{Key} objects, then warn the user and convert the mapping.
        """
        sshFactory = MockOldFactoryPublicKeys()
        sshFactory.publicKeys = sshFactory.getPublicKeys()
        self.assertWarns(DeprecationWarning,
                "Returning a mapping from strings to strings from"
                " getPublicKeys()/publicKeys (in %s) is deprecated.  Return "
                "a mapping from strings to Key objects instead." %
                (qual(MockOldFactoryPublicKeys),),
                factory.__file__, sshFactory.startFactory)
        self.assertEqual(sshFactory.publicKeys, MockFactory().getPublicKeys())


    def test_privateKeysWarning(self):
        """
        If the return value of C{privateKeys} attribute isn't a mapping from
        key names to C{Key} objects, then warn the user and convert the
        mapping.
        """
        sshFactory = MockOldFactoryPrivateKeys()
        sshFactory.privateKeys = sshFactory.getPrivateKeys()
        self.assertWarns(DeprecationWarning,
                "Returning a mapping from strings to PyCrypto key objects from"
                " getPrivateKeys()/privateKeys (in %s) is deprecated.  Return"
                " a mapping from strings to Key objects instead." %
                (qual(MockOldFactoryPrivateKeys),),
                factory.__file__, sshFactory.startFactory)
        self.assertEqual(sshFactory.privateKeys,
                          MockFactory().getPrivateKeys())