This file is indexed.

/usr/lib/python2.7/dist-packages/twisted/conch/test/test_knownhosts.py is in python-twisted-conch 1:13.2.0-1ubuntu1.

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
# Copyright (c) Twisted Matrix Laboratories.
# See LICENSE for details.

"""
Tests for L{twisted.conch.client.knownhosts}.
"""

import os
from binascii import Error as BinasciiError, b2a_base64, a2b_base64

try:
    import Crypto
    import pyasn1
except ImportError:
    skip = "PyCrypto and PyASN1 required for twisted.conch.knownhosts."
else:
    from twisted.conch.ssh.keys import Key, BadKeyError
    from twisted.conch.client.knownhosts import \
        PlainEntry, HashedEntry, KnownHostsFile, UnparsedEntry, ConsoleUI
    from twisted.conch.client import default

from zope.interface.verify import verifyObject

from twisted.python.filepath import FilePath
from twisted.trial.unittest import TestCase
from twisted.internet.defer import Deferred
from twisted.conch.interfaces import IKnownHostEntry
from twisted.conch.error import HostKeyChanged, UserRejectedKey, InvalidEntry
from twisted.test.testutils import ComparisonTestsMixin


sampleEncodedKey = (
    'AAAAB3NzaC1yc2EAAAABIwAAAQEAsV0VMRbGmzhqxxayLRHmvnFvtyNqgbNKV46dU1bVFB+3y'
    'tNvue4Riqv/SVkPRNwMb7eWH29SviXaBxUhYyzKkDoNUq3rTNnH1Vnif6d6X4JCrUb5d3W+Dm'
    'YClyJrZ5HgD/hUpdSkTRqdbQ2TrvSAxRacj+vHHT4F4dm1bJSewm3B2D8HVOoi/CbVh3dsIiC'
    'dp8VltdZx4qYVfYe2LwVINCbAa3d3tj9ma7RVfw3OH2Mfb+toLd1N5tBQFb7oqTt2nC6I/6Bd'
    '4JwPUld+IEitw/suElq/AIJVQXXujeyiZlea90HE65U2mF1ytr17HTAIT2ySokJWyuBANGACk'
    '6iIaw==')

otherSampleEncodedKey = (
    'AAAAB3NzaC1yc2EAAAABIwAAAIEAwaeCZd3UCuPXhX39+/p9qO028jTF76DMVd9mPvYVDVXuf'
    'WckKZauF7+0b7qm+ChT7kan6BzRVo4++gCVNfAlMzLysSt3ylmOR48tFpAfygg9UCX3DjHz0E'
    'lOOUKh3iifc9aUShD0OPaK3pR5JJ8jfiBfzSYWt/hDi/iZ4igsSs8=')

thirdSampleEncodedKey = (
    'AAAAB3NzaC1yc2EAAAABIwAAAQEAl/TQakPkePlnwCBRPitIVUTg6Z8VzN1en+DGkyo/evkmLw'
    '7o4NWR5qbysk9A9jXW332nxnEuAnbcCam9SHe1su1liVfyIK0+3bdn0YRB0sXIbNEtMs2LtCho'
    '/aV3cXPS+Cf1yut3wvIpaRnAzXxuKPCTXQ7/y0IXa8TwkRBH58OJa3RqfQ/NsSp5SAfdsrHyH2'
    'aitiVKm2jfbTKzSEqOQG/zq4J9GXTkq61gZugory/Tvl5/yPgSnOR6C9jVOMHf27ZPoRtyj9SY'
    '343Hd2QHiIE0KPZJEgCynKeWoKz8v6eTSK8n4rBnaqWdp8MnGZK1WGy05MguXbyCDuTC8AmJXQ'
    '==')

sampleKey = a2b_base64(sampleEncodedKey)
otherSampleKey = a2b_base64(otherSampleEncodedKey)
thirdSampleKey = a2b_base64(thirdSampleEncodedKey)

samplePlaintextLine = (
    "www.twistedmatrix.com ssh-rsa " + sampleEncodedKey + "\n")

otherSamplePlaintextLine = (
    "divmod.com ssh-rsa " + otherSampleEncodedKey + "\n")

sampleHostIPLine = (
    "www.twistedmatrix.com,198.49.126.131 ssh-rsa " + sampleEncodedKey + "\n")

sampleHashedLine = (
    "|1|gJbSEPBG9ZSBoZpHNtZBD1bHKBA=|bQv+0Xa0dByrwkA1EB0E7Xop/Fo= ssh-rsa " +
    sampleEncodedKey + "\n")


class EntryTestsMixin:
    """
    Tests for implementations of L{IKnownHostEntry}.  Subclasses must set the
    'entry' attribute to a provider of that interface, the implementation of
    that interface under test.

    @ivar entry: a provider of L{IKnownHostEntry} with a hostname of
    www.twistedmatrix.com and an RSA key of sampleKey.
    """

    def test_providesInterface(self):
        """
        The given entry should provide IKnownHostEntry.
        """
        verifyObject(IKnownHostEntry, self.entry)


    def test_fromString(self):
        """
        Constructing a plain text entry from an unhashed known_hosts entry will
        result in an L{IKnownHostEntry} provider with 'keyString', 'hostname',
        and 'keyType' attributes.  While outside the interface in question,
        these attributes are held in common by L{PlainEntry} and L{HashedEntry}
        implementations; other implementations should override this method in
        subclasses.
        """
        entry = self.entry
        self.assertEqual(entry.publicKey, Key.fromString(sampleKey))
        self.assertEqual(entry.keyType, "ssh-rsa")


    def test_matchesKey(self):
        """
        L{IKnownHostEntry.matchesKey} checks to see if an entry matches a given
        SSH key.
        """
        twistedmatrixDotCom = Key.fromString(sampleKey)
        divmodDotCom = Key.fromString(otherSampleKey)
        self.assertEqual(
            True,
            self.entry.matchesKey(twistedmatrixDotCom))
        self.assertEqual(
            False,
            self.entry.matchesKey(divmodDotCom))


    def test_matchesHost(self):
        """
        L{IKnownHostEntry.matchesHost} checks to see if an entry matches a
        given hostname.
        """
        self.assertEqual(True, self.entry.matchesHost(
                "www.twistedmatrix.com"))
        self.assertEqual(False, self.entry.matchesHost(
                "www.divmod.com"))



class PlainEntryTests(EntryTestsMixin, TestCase):
    """
    Test cases for L{PlainEntry}.
    """
    plaintextLine = samplePlaintextLine
    hostIPLine = sampleHostIPLine

    def setUp(self):
        """
        Set 'entry' to a sample plain-text entry with sampleKey as its key.
        """
        self.entry = PlainEntry.fromString(self.plaintextLine)


    def test_matchesHostIP(self):
        """
        A "hostname,ip" formatted line will match both the host and the IP.
        """
        self.entry = PlainEntry.fromString(self.hostIPLine)
        self.assertEqual(True, self.entry.matchesHost("198.49.126.131"))
        self.test_matchesHost()


    def test_toString(self):
        """
        L{PlainEntry.toString} generates the serialized OpenSSL format string
        for the entry, sans newline.
        """
        self.assertEqual(self.entry.toString(), self.plaintextLine.rstrip("\n"))
        multiHostEntry = PlainEntry.fromString(self.hostIPLine)
        self.assertEqual(multiHostEntry.toString(),
                         self.hostIPLine.rstrip("\n"))



class PlainTextWithCommentTests(PlainEntryTests):
    """
    Test cases for L{PlainEntry} when parsed from a line with a comment.
    """

    plaintextLine = samplePlaintextLine[:-1] + " plain text comment.\n"
    hostIPLine = sampleHostIPLine[:-1] + " text following host/IP line\n"



class HashedEntryTests(EntryTestsMixin, ComparisonTestsMixin, TestCase):
    """
    Tests for L{HashedEntry}.

    This suite doesn't include any tests for host/IP pairs because hashed
    entries store IP addresses the same way as hostnames and does not support
    comma-separated lists.  (If you hash the IP and host together you can't
    tell if you've got the key already for one or the other.)
    """
    hashedLine = sampleHashedLine

    def setUp(self):
        """
        Set 'entry' to a sample hashed entry for twistedmatrix.com with
        sampleKey as its key.
        """
        self.entry = HashedEntry.fromString(self.hashedLine)


    def test_toString(self):
        """
        L{HashedEntry.toString} generates the serialized OpenSSL format string
        for the entry, sans the newline.
        """
        self.assertEqual(self.entry.toString(), self.hashedLine.rstrip("\n"))


    def test_equality(self):
        """
        Two L{HashedEntry} instances compare equal if and only if they represent
        the same host and key in exactly the same way: the host salt, host hash,
        public key type, public key, and comment fields must all be equal.
        """
        hostSalt = "gJbSEPBG9ZSBoZpHNtZBD1bHKBA"
        hostHash = "bQv+0Xa0dByrwkA1EB0E7Xop/Fo"
        publicKey = Key.fromString(sampleKey)
        comment = "hello, world"

        entry = HashedEntry(
            hostSalt, hostHash, publicKey.type(), publicKey, comment)
        duplicate = HashedEntry(
            hostSalt, hostHash, publicKey.type(), publicKey, comment)

        # Vary the host salt
        self.assertNormalEqualityImplementation(
            entry, duplicate,
            HashedEntry(
                hostSalt[::-1], hostHash, publicKey.type(), publicKey,
                comment))

        # Vary the host hash
        self.assertNormalEqualityImplementation(
            entry, duplicate,
            HashedEntry(
                hostSalt, hostHash[::-1], publicKey.type(), publicKey,
                comment))

        # Vary the key type
        self.assertNormalEqualityImplementation(
            entry, duplicate,
            HashedEntry(
                hostSalt, hostHash, publicKey.type()[::-1], publicKey,
                comment))

        # Vary the key
        self.assertNormalEqualityImplementation(
            entry, duplicate,
            HashedEntry(
                hostSalt, hostHash, publicKey.type(),
                Key.fromString(otherSampleKey), comment))

        # Vary the comment
        self.assertNormalEqualityImplementation(
            entry, duplicate,
            HashedEntry(
                hostSalt, hostHash, publicKey.type(), publicKey,
                comment[::-1]))



class HashedEntryWithCommentTests(HashedEntryTests):
    """
    Test cases for L{PlainEntry} when parsed from a line with a comment.
    """

    hashedLine = sampleHashedLine[:-1] + " plain text comment.\n"



class UnparsedEntryTests(TestCase, EntryTestsMixin):
    """
    Tests for L{UnparsedEntry}
    """
    def setUp(self):
        """
        Set up the 'entry' to be an unparsed entry for some random text.
        """
        self.entry = UnparsedEntry("    This is a bogus entry.  \n")


    def test_fromString(self):
        """
        Creating an L{UnparsedEntry} should simply record the string it was
        passed.
        """
        self.assertEqual("    This is a bogus entry.  \n",
                         self.entry._string)


    def test_matchesHost(self):
        """
        An unparsed entry can't match any hosts.
        """
        self.assertEqual(False, self.entry.matchesHost("www.twistedmatrix.com"))


    def test_matchesKey(self):
        """
        An unparsed entry can't match any keys.
        """
        self.assertEqual(False, self.entry.matchesKey(Key.fromString(sampleKey)))


    def test_toString(self):
        """
        L{UnparsedEntry.toString} returns its input string, sans trailing
        newline.
        """
        self.assertEqual("    This is a bogus entry.  ", self.entry.toString())



class ParseErrorTests(TestCase):
    """
    L{HashedEntry.fromString} and L{PlainEntry.fromString} can raise a variety
    of errors depending on misformattings of certain strings.  These tests make
    sure those errors are caught.  Since many of the ways that this can go
    wrong are in the lower-level APIs being invoked by the parsing logic,
    several of these are integration tests with the C{base64} and
    L{twisted.conch.ssh.keys} modules.
    """

    def invalidEntryTest(self, cls):
        """
        If there are fewer than three elements, C{fromString} should raise
        L{InvalidEntry}.
        """
        self.assertRaises(InvalidEntry, cls.fromString, "invalid")


    def notBase64Test(self, cls):
        """
        If the key is not base64, C{fromString} should raise L{BinasciiError}.
        """
        self.assertRaises(BinasciiError, cls.fromString, "x x x")


    def badKeyTest(self, cls, prefix):
        """
        If the key portion of the entry is valid base64, but is not actually an
        SSH key, C{fromString} should raise L{BadKeyError}.
        """
        self.assertRaises(BadKeyError, cls.fromString, ' '.join(
                [prefix, "ssh-rsa", b2a_base64(
                        "Hey, this isn't an SSH key!").strip()]))


    def test_invalidPlainEntry(self):
        """
        If there are fewer than three whitespace-separated elements in an
        entry, L{PlainEntry.fromString} should raise L{InvalidEntry}.
        """
        self.invalidEntryTest(PlainEntry)


    def test_invalidHashedEntry(self):
        """
        If there are fewer than three whitespace-separated elements in an
        entry, or the hostname salt/hash portion has more than two elements,
        L{HashedEntry.fromString} should raise L{InvalidEntry}.
        """
        self.invalidEntryTest(HashedEntry)
        a, b, c = sampleHashedLine.split()
        self.assertRaises(InvalidEntry, HashedEntry.fromString, ' '.join(
                [a + "||", b, c]))


    def test_plainNotBase64(self):
        """
        If the key portion of a plain entry is not decodable as base64,
        C{fromString} should raise L{BinasciiError}.
        """
        self.notBase64Test(PlainEntry)


    def test_hashedNotBase64(self):
        """
        If the key, host salt, or host hash portion of a hashed entry is not
        encoded, it will raise L{BinasciiError}.
        """
        self.notBase64Test(HashedEntry)
        a, b, c = sampleHashedLine.split()
        # Salt not valid base64.
        self.assertRaises(
            BinasciiError, HashedEntry.fromString,
            ' '.join(["|1|x|" + b2a_base64("stuff").strip(), b, c]))
        # Host hash not valid base64.
        self.assertRaises(
            BinasciiError, HashedEntry.fromString,
            ' '.join([HashedEntry.MAGIC + b2a_base64("stuff").strip() + "|x",
            b, c]))
        # Neither salt nor hash valid base64.
        self.assertRaises(
            BinasciiError, HashedEntry.fromString,
            ' '.join(["|1|x|x", b, c]))


    def test_hashedBadKey(self):
        """
        If the key portion of the entry is valid base64, but is not actually an
        SSH key, C{HashedEntry.fromString} should raise L{BadKeyError}.
        """
        a, b, c = sampleHashedLine.split()
        self.badKeyTest(HashedEntry, a)


    def test_plainBadKey(self):
        """
        If the key portion of the entry is valid base64, but is not actually an
        SSH key, C{PlainEntry.fromString} should raise L{BadKeyError}.
        """
        self.badKeyTest(PlainEntry, "hostname")



class KnownHostsDatabaseTests(TestCase):
    """
    Tests for L{KnownHostsFile}.
    """

    def pathWithContent(self, content):
        """
        Return a FilePath with the given initial content.
        """
        fp = FilePath(self.mktemp())
        fp.setContent(content)
        return fp


    def loadSampleHostsFile(self, content=(
            sampleHashedLine + otherSamplePlaintextLine +
            "\n# That was a blank line.\n"
            "This is just unparseable.\n"
            "|1|This also unparseable.\n")):
        """
        Return a sample hosts file, with keys for www.twistedmatrix.com and
        divmod.com present.
        """
        return KnownHostsFile.fromPath(self.pathWithContent(content))


    def test_readOnlySavePath(self):
        """
        L{KnownHostsFile.savePath} is read-only; if an assignment is made to
        it, L{AttributeError} is raised and the value is unchanged.
        """
        path = FilePath(self.mktemp())
        new = FilePath(self.mktemp())
        hostsFile = KnownHostsFile(path)
        self.assertRaises(AttributeError, setattr, hostsFile, "savePath", new)
        self.assertEqual(path, hostsFile.savePath)


    def test_defaultInitializerIgnoresExisting(self):
        """
        The default initializer for L{KnownHostsFile} disregards any existing
        contents in the save path.
        """
        hostsFile = KnownHostsFile(self.pathWithContent(sampleHashedLine))
        self.assertEqual([], list(hostsFile.iterentries()))


    def test_defaultInitializerClobbersExisting(self):
        """
        After using the default initializer for L{KnownHostsFile}, the first use
        of L{KnownHostsFile.save} overwrites any existing contents in the save
        path.
        """
        path = self.pathWithContent(sampleHashedLine)
        hostsFile = KnownHostsFile(path)
        entry = hostsFile.addHostKey(
            "www.example.com", Key.fromString(otherSampleKey))
        hostsFile.save()
        # Check KnownHostsFile to see what it thinks the state is
        self.assertEqual([entry], list(hostsFile.iterentries()))
        # And also directly check the underlying file itself
        self.assertEqual(entry.toString() + "\n", path.getContent())


    def test_saveResetsClobberState(self):
        """
        After L{KnownHostsFile.save} is used once with an instance initialized
        by the default initializer, contents of the save path are respected and
        preserved.
        """
        hostsFile = KnownHostsFile(self.pathWithContent(sampleHashedLine))
        preSave = hostsFile.addHostKey(
            "www.example.com", Key.fromString(otherSampleKey))
        hostsFile.save()
        postSave = hostsFile.addHostKey(
            "another.example.com", Key.fromString(thirdSampleKey))
        hostsFile.save()

        self.assertEqual([preSave, postSave], list(hostsFile.iterentries()))


    def test_loadFromPath(self):
        """
        Loading a L{KnownHostsFile} from a path with six entries in it will
        result in a L{KnownHostsFile} object with six L{IKnownHostEntry}
        providers in it.
        """
        hostsFile = self.loadSampleHostsFile()
        self.assertEqual(6, len(list(hostsFile.iterentries())))


    def test_iterentriesUnsaved(self):
        """
        If the save path for a L{KnownHostsFile} does not exist,
        L{KnownHostsFile.iterentries} still returns added but unsaved entries.
        """
        hostsFile = KnownHostsFile(FilePath(self.mktemp()))
        hostsFile.addHostKey("www.example.com", Key.fromString(sampleKey))
        self.assertEqual(1, len(list(hostsFile.iterentries())))


    def test_verifyHashedEntry(self):
        """
        Loading a L{KnownHostsFile} from a path containing a single valid
        L{HashedEntry} entry will result in a L{KnownHostsFile} object
        with one L{IKnownHostEntry} provider.
        """
        hostsFile = self.loadSampleHostsFile((sampleHashedLine))
        entries = list(hostsFile.iterentries())
        self.assertIsInstance(entries[0], HashedEntry)
        self.assertEqual(True, entries[0].matchesHost("www.twistedmatrix.com"))
        self.assertEqual(1, len(entries))


    def test_verifyPlainEntry(self):
        """
        Loading a L{KnownHostsFile} from a path containing a single valid
        L{PlainEntry} entry will result in a L{KnownHostsFile} object
        with one L{IKnownHostEntry} provider.
        """
        hostsFile = self.loadSampleHostsFile((otherSamplePlaintextLine))
        entries = list(hostsFile.iterentries())
        self.assertIsInstance(entries[0], PlainEntry)
        self.assertEqual(True, entries[0].matchesHost("divmod.com"))
        self.assertEqual(1, len(entries))


    def test_verifyUnparsedEntry(self):
        """
        Loading a L{KnownHostsFile} from a path that only contains '\n' will
        result in a L{KnownHostsFile} object containing a L{UnparsedEntry}
        object.
        """
        hostsFile = self.loadSampleHostsFile(("\n"))
        entries = list(hostsFile.iterentries())
        self.assertIsInstance(entries[0], UnparsedEntry)
        self.assertEqual(entries[0].toString(), "")
        self.assertEqual(1, len(entries))


    def test_verifyUnparsedComment(self):
        """
        Loading a L{KnownHostsFile} from a path that contains a comment will
        result in a L{KnownHostsFile} object containing a L{UnparsedEntry}
        object.
        """
        hostsFile = self.loadSampleHostsFile(("# That was a blank line.\n"))
        entries = list(hostsFile.iterentries())
        self.assertIsInstance(entries[0], UnparsedEntry)
        self.assertEqual(entries[0].toString(), "# That was a blank line.")


    def test_verifyUnparsableLine(self):
        """
        Loading a L{KnownHostsFile} from a path that contains an unparseable
        line will be represented as an L{UnparsedEntry} instance.
        """
        hostsFile = self.loadSampleHostsFile(("This is just unparseable.\n"))
        entries = list(hostsFile.iterentries())
        self.assertIsInstance(entries[0], UnparsedEntry)
        self.assertEqual(entries[0].toString(), "This is just unparseable.")
        self.assertEqual(1, len(entries))


    def test_verifyUnparsableEncryptionMarker(self):
        """
        Loading a L{KnownHostsFile} from a path containing an unparseable line
        that starts with an encryption marker will be represented as an
        L{UnparsedEntry} instance.
        """
        hostsFile = self.loadSampleHostsFile(("|1|This is unparseable.\n"))
        entries = list(hostsFile.iterentries())
        self.assertIsInstance(entries[0], UnparsedEntry)
        self.assertEqual(entries[0].toString(), "|1|This is unparseable.")
        self.assertEqual(1, len(entries))


    def test_loadNonExistent(self):
        """
        Loading a L{KnownHostsFile} from a path that does not exist should
        result in an empty L{KnownHostsFile} that will save back to that path.
        """
        pn = self.mktemp()
        knownHostsFile = KnownHostsFile.fromPath(FilePath(pn))
        entries = list(knownHostsFile.iterentries())
        self.assertEqual([], entries)
        self.assertEqual(False, FilePath(pn).exists())
        knownHostsFile.save()
        self.assertEqual(True, FilePath(pn).exists())


    def test_loadNonExistentParent(self):
        """
        Loading a L{KnownHostsFile} from a path whose parent directory does not
        exist should result in an empty L{KnownHostsFile} that will save back
        to that path, creating its parent directory(ies) in the process.
        """
        thePath = FilePath(self.mktemp())
        knownHostsPath = thePath.child("foo").child("known_hosts")
        knownHostsFile = KnownHostsFile.fromPath(knownHostsPath)
        knownHostsFile.save()
        knownHostsPath.restat(False)
        self.assertEqual(True, knownHostsPath.exists())


    def test_savingAddsEntry(self):
        """
        L{KnownHostsFile.save} will write out a new file with any entries
        that have been added.
        """
        path = self.pathWithContent(sampleHashedLine +
                                    otherSamplePlaintextLine)
        knownHostsFile = KnownHostsFile.fromPath(path)
        newEntry = knownHostsFile.addHostKey("some.example.com",
            Key.fromString(thirdSampleKey))
        expectedContent = (
            sampleHashedLine +
            otherSamplePlaintextLine + HashedEntry.MAGIC +
            b2a_base64(newEntry._hostSalt).strip() + "|" +
            b2a_base64(newEntry._hostHash).strip() + " ssh-rsa " +
            thirdSampleEncodedKey + "\n")

        # Sanity check, let's make sure the base64 API being used for the test
        # isn't inserting spurious newlines.
        self.assertEqual(3, expectedContent.count("\n"))
        knownHostsFile.save()
        self.assertEqual(expectedContent, path.getContent())


    def test_savingAvoidsDuplication(self):
        """
        L{KnownHostsFile.save} only writes new entries to the save path, not
        entries which were added and already written by a previous call to
        C{save}.
        """
        path = FilePath(self.mktemp())
        knownHosts = KnownHostsFile(path)
        entry = knownHosts.addHostKey(
            "some.example.com", Key.fromString(sampleKey))
        knownHosts.save()
        knownHosts.save()

        knownHosts = KnownHostsFile.fromPath(path)
        self.assertEqual([entry], list(knownHosts.iterentries()))


    def test_savingsPreservesExisting(self):
        """
        L{KnownHostsFile.save} will not overwrite existing entries in its save
        path, even if they were only added after the L{KnownHostsFile} instance
        was initialized.
        """
        # Start off with one host/key pair in the file
        path = self.pathWithContent(sampleHashedLine)
        knownHosts = KnownHostsFile.fromPath(path)

        # After initializing the KnownHostsFile instance, add a second host/key
        # pair to the file directly - without the instance's help or knowledge.
        with path.open("a") as hostsFileObj:
            hostsFileObj.write(otherSamplePlaintextLine)

        # Add a third host/key pair using the KnownHostsFile instance
        key = Key.fromString(thirdSampleKey)
        knownHosts.addHostKey("brandnew.example.com", key)
        knownHosts.save()

        # Check that all three host/key pairs are present.
        knownHosts = KnownHostsFile.fromPath(path)
        self.assertEqual([True, True, True], [
                knownHosts.hasHostKey(
                    "www.twistedmatrix.com", Key.fromString(sampleKey)),
                knownHosts.hasHostKey(
                    "divmod.com", Key.fromString(otherSampleKey)),
                knownHosts.hasHostKey("brandnew.example.com", key)])


    def test_hasPresentKey(self):
        """
        L{KnownHostsFile.hasHostKey} returns C{True} when a key for the given
        hostname is present and matches the expected key.
        """
        hostsFile = self.loadSampleHostsFile()
        self.assertEqual(True, hostsFile.hasHostKey(
                "www.twistedmatrix.com", Key.fromString(sampleKey)))


    def test_hasNonPresentKey(self):
        """
        L{KnownHostsFile.hasHostKey} returns C{False} when a key for the given
        hostname is not present.
        """
        hostsFile = self.loadSampleHostsFile()
        self.assertEqual(False, hostsFile.hasHostKey(
                "non-existent.example.com", Key.fromString(sampleKey)))


    def test_hasLaterAddedKey(self):
        """
        L{KnownHostsFile.hasHostKey} returns C{True} when a key for the given
        hostname is present in the file, even if it is only added to the file
        after the L{KnownHostsFile} instance is initialized.
        """
        key = Key.fromString(sampleKey)
        entry = PlainEntry(["brandnew.example.com"], key.sshType(), key, "")
        hostsFile = self.loadSampleHostsFile()
        with hostsFile.savePath.open("a") as hostsFileObj:
            hostsFileObj.write(entry.toString() + "\n")
        self.assertEqual(
            True, hostsFile.hasHostKey("brandnew.example.com", key))


    def test_savedEntryHasKeyMismatch(self):
        """
        L{KnownHostsFile.hasHostKey} raises L{HostKeyChanged} if the host key is
        present in the underlying file, but different from the expected one.
        The resulting exception should have an C{offendingEntry} indicating the
        given entry.
        """
        hostsFile = self.loadSampleHostsFile()
        entries = list(hostsFile.iterentries())
        exception = self.assertRaises(
            HostKeyChanged, hostsFile.hasHostKey,
            "www.twistedmatrix.com", Key.fromString(otherSampleKey))
        self.assertEqual(exception.offendingEntry, entries[0])
        self.assertEqual(exception.lineno, 1)
        self.assertEqual(exception.path, hostsFile.savePath)


    def test_savedEntryAfterAddHasKeyMismatch(self):
        """
        Even after a new entry has been added in memory but not yet saved, the
        L{HostKeyChanged} exception raised by L{KnownHostsFile.hasHostKey} has a
        C{lineno} attribute which indicates the 1-based line number of the
        offending entry in the underlying file when the given host key does not
        match the expected host key.
        """
        hostsFile = self.loadSampleHostsFile()
        hostsFile.addHostKey(
            "www.example.com", Key.fromString(otherSampleKey))
        exception = self.assertRaises(
            HostKeyChanged, hostsFile.hasHostKey,
            "www.twistedmatrix.com", Key.fromString(otherSampleKey))
        self.assertEqual(exception.lineno, 1)
        self.assertEqual(exception.path, hostsFile.savePath)


    def test_unsavedEntryHasKeyMismatch(self):
        """
        L{KnownHostsFile.hasHostKey} raises L{HostKeyChanged} if the host key is
        present in memory (but not yet saved), but different from the expected
        one.  The resulting exception has a C{offendingEntry} indicating the
        given entry, but no filename or line number information (reflecting the
        fact that the entry exists only in memory).
        """
        hostsFile = KnownHostsFile(FilePath(self.mktemp()))
        entry = hostsFile.addHostKey(
            "www.example.com", Key.fromString(otherSampleKey))
        exception = self.assertRaises(
            HostKeyChanged, hostsFile.hasHostKey,
            "www.example.com", Key.fromString(thirdSampleKey))
        self.assertEqual(exception.offendingEntry, entry)
        self.assertEqual(exception.lineno, None)
        self.assertEqual(exception.path, None)


    def test_addHostKey(self):
        """
        L{KnownHostsFile.addHostKey} adds a new L{HashedEntry} to the host
        file, and returns it.
        """
        hostsFile = self.loadSampleHostsFile()
        aKey = Key.fromString(thirdSampleKey)
        self.assertEqual(False,
                         hostsFile.hasHostKey("somewhere.example.com", aKey))
        newEntry = hostsFile.addHostKey("somewhere.example.com", aKey)

        # The code in OpenSSH requires host salts to be 20 characters long.
        # This is the required length of a SHA-1 HMAC hash, so it's just a
        # sanity check.
        self.assertEqual(20, len(newEntry._hostSalt))
        self.assertEqual(True,
                         newEntry.matchesHost("somewhere.example.com"))
        self.assertEqual(newEntry.keyType, "ssh-rsa")
        self.assertEqual(aKey, newEntry.publicKey)
        self.assertEqual(True,
                         hostsFile.hasHostKey("somewhere.example.com", aKey))


    def test_randomSalts(self):
        """
        L{KnownHostsFile.addHostKey} generates a random salt for each new key,
        so subsequent salts will be different.
        """
        hostsFile = self.loadSampleHostsFile()
        aKey = Key.fromString(thirdSampleKey)
        self.assertNotEqual(
            hostsFile.addHostKey("somewhere.example.com", aKey)._hostSalt,
            hostsFile.addHostKey("somewhere-else.example.com", aKey)._hostSalt)


    def test_verifyValidKey(self):
        """
        Verifying a valid key should return a L{Deferred} which fires with
        True.
        """
        hostsFile = self.loadSampleHostsFile()
        hostsFile.addHostKey("1.2.3.4", Key.fromString(sampleKey))
        ui = FakeUI()
        d = hostsFile.verifyHostKey(ui, "www.twistedmatrix.com", "1.2.3.4",
                                    Key.fromString(sampleKey))
        l = []
        d.addCallback(l.append)
        self.assertEqual(l, [True])


    def test_verifyInvalidKey(self):
        """
        Verfying an invalid key should return a L{Deferred} which fires with a
        L{HostKeyChanged} failure.
        """
        hostsFile = self.loadSampleHostsFile()
        wrongKey = Key.fromString(thirdSampleKey)
        ui = FakeUI()
        hostsFile.addHostKey("1.2.3.4", Key.fromString(sampleKey))
        d = hostsFile.verifyHostKey(
            ui, "www.twistedmatrix.com", "1.2.3.4", wrongKey)
        return self.assertFailure(d, HostKeyChanged)


    def verifyNonPresentKey(self):
        """
        Set up a test to verify a key that isn't present.  Return a 3-tuple of
        the UI, a list set up to collect the result of the verifyHostKey call,
        and the sample L{KnownHostsFile} being used.

        This utility method avoids returning a L{Deferred}, and records results
        in the returned list instead, because the events which get generated
        here are pre-recorded in the 'ui' object.  If the L{Deferred} in
        question does not fire, the it will fail quickly with an empty list.
        """
        hostsFile = self.loadSampleHostsFile()
        absentKey = Key.fromString(thirdSampleKey)
        ui = FakeUI()
        l = []
        d = hostsFile.verifyHostKey(
            ui, "sample-host.example.com", "4.3.2.1", absentKey)
        d.addBoth(l.append)
        self.assertEqual([], l)
        self.assertEqual(
            ui.promptText,
            "The authenticity of host 'sample-host.example.com (4.3.2.1)' "
            "can't be established.\n"
            "RSA key fingerprint is "
            "89:4e:cc:8c:57:83:96:48:ef:63:ad:ee:99:00:4c:8f.\n"
            "Are you sure you want to continue connecting (yes/no)? ")
        return ui, l, hostsFile


    def test_verifyNonPresentKey_Yes(self):
        """
        Verifying a key where neither the hostname nor the IP are present
        should result in the UI being prompted with a message explaining as
        much.  If the UI says yes, the Deferred should fire with True.
        """
        ui, l, knownHostsFile = self.verifyNonPresentKey()
        ui.promptDeferred.callback(True)
        self.assertEqual([True], l)
        reloaded = KnownHostsFile.fromPath(knownHostsFile.savePath)
        self.assertEqual(
            True,
            reloaded.hasHostKey("4.3.2.1", Key.fromString(thirdSampleKey)))
        self.assertEqual(
            True,
            reloaded.hasHostKey("sample-host.example.com",
                                Key.fromString(thirdSampleKey)))


    def test_verifyNonPresentKey_No(self):
        """
        Verifying a key where neither the hostname nor the IP are present
        should result in the UI being prompted with a message explaining as
        much.  If the UI says no, the Deferred should fail with
        UserRejectedKey.
        """
        ui, l, knownHostsFile = self.verifyNonPresentKey()
        ui.promptDeferred.callback(False)
        l[0].trap(UserRejectedKey)


    def test_verifyHostIPMismatch(self):
        """
        Verifying a key where the host is present (and correct), but the IP is
        present and different, should result the deferred firing in a
        HostKeyChanged failure.
        """
        hostsFile = self.loadSampleHostsFile()
        wrongKey = Key.fromString(thirdSampleKey)
        ui = FakeUI()
        d = hostsFile.verifyHostKey(
            ui, "www.twistedmatrix.com", "4.3.2.1", wrongKey)
        return self.assertFailure(d, HostKeyChanged)


    def test_verifyKeyForHostAndIP(self):
        """
        Verifying a key where the hostname is present but the IP is not should
        result in the key being added for the IP and the user being warned
        about the change.
        """
        ui = FakeUI()
        hostsFile = self.loadSampleHostsFile()
        expectedKey = Key.fromString(sampleKey)
        hostsFile.verifyHostKey(
            ui, "www.twistedmatrix.com", "5.4.3.2", expectedKey)
        self.assertEqual(
            True, KnownHostsFile.fromPath(hostsFile.savePath).hasHostKey(
                "5.4.3.2", expectedKey))
        self.assertEqual(
            ["Warning: Permanently added the RSA host key for IP address "
             "'5.4.3.2' to the list of known hosts."],
            ui.userWarnings)


class FakeFile(object):
    """
    A fake file-like object that acts enough like a file for
    L{ConsoleUI.prompt}.
    """

    def __init__(self):
        self.inlines = []
        self.outchunks = []
        self.closed = False


    def readline(self):
        """
        Return a line from the 'inlines' list.
        """
        return self.inlines.pop(0)


    def write(self, chunk):
        """
        Append the given item to the 'outchunks' list.
        """
        if self.closed:
            raise IOError("the file was closed")
        self.outchunks.append(chunk)


    def close(self):
        """
        Set the 'closed' flag to True, explicitly marking that it has been
        closed.
        """
        self.closed = True



class ConsoleUITests(TestCase):
    """
    Test cases for L{ConsoleUI}.
    """

    def setUp(self):
        """
        Create a L{ConsoleUI} pointed at a L{FakeFile}.
        """
        self.fakeFile = FakeFile()
        self.ui = ConsoleUI(self.openFile)


    def openFile(self):
        """
        Return the current fake file.
        """
        return self.fakeFile


    def newFile(self, lines):
        """
        Create a new fake file (the next file that self.ui will open) with the
        given list of lines to be returned from readline().
        """
        self.fakeFile = FakeFile()
        self.fakeFile.inlines = lines


    def test_promptYes(self):
        """
        L{ConsoleUI.prompt} writes a message to the console, then reads a line.
        If that line is 'yes', then it returns a L{Deferred} that fires with
        True.
        """
        for okYes in ['yes', 'Yes', 'yes\n']:
            self.newFile([okYes])
            l = []
            self.ui.prompt("Hello, world!").addCallback(l.append)
            self.assertEqual(["Hello, world!"], self.fakeFile.outchunks)
            self.assertEqual([True], l)
            self.assertEqual(True, self.fakeFile.closed)


    def test_promptNo(self):
        """
        L{ConsoleUI.prompt} writes a message to the console, then reads a line.
        If that line is 'no', then it returns a L{Deferred} that fires with
        False.
        """
        for okNo in ['no', 'No', 'no\n']:
            self.newFile([okNo])
            l = []
            self.ui.prompt("Goodbye, world!").addCallback(l.append)
            self.assertEqual(["Goodbye, world!"], self.fakeFile.outchunks)
            self.assertEqual([False], l)
            self.assertEqual(True, self.fakeFile.closed)


    def test_promptRepeatedly(self):
        """
        L{ConsoleUI.prompt} writes a message to the console, then reads a line.
        If that line is neither 'yes' nor 'no', then it says "Please enter
        'yes' or 'no'" until it gets a 'yes' or a 'no', at which point it
        returns a Deferred that answers either True or False.
        """
        self.newFile(['what', 'uh', 'okay', 'yes'])
        l = []
        self.ui.prompt("Please say something useful.").addCallback(l.append)
        self.assertEqual([True], l)
        self.assertEqual(self.fakeFile.outchunks,
                         ["Please say something useful."] +
                         ["Please type 'yes' or 'no': "] * 3)
        self.assertEqual(True, self.fakeFile.closed)
        self.newFile(['blah', 'stuff', 'feh', 'no'])
        l = []
        self.ui.prompt("Please say something negative.").addCallback(l.append)
        self.assertEqual([False], l)
        self.assertEqual(self.fakeFile.outchunks,
                         ["Please say something negative."] +
                         ["Please type 'yes' or 'no': "] * 3)
        self.assertEqual(True, self.fakeFile.closed)


    def test_promptOpenFailed(self):
        """
        If the C{opener} passed to L{ConsoleUI} raises an exception, that
        exception will fail the L{Deferred} returned from L{ConsoleUI.prompt}.
        """
        def raiseIt():
            raise IOError()
        ui = ConsoleUI(raiseIt)
        d = ui.prompt("This is a test.")
        return self.assertFailure(d, IOError)


    def test_warn(self):
        """
        L{ConsoleUI.warn} should output a message to the console object.
        """
        self.ui.warn("Test message.")
        self.assertEqual(["Test message."], self.fakeFile.outchunks)
        self.assertEqual(True, self.fakeFile.closed)


    def test_warnOpenFailed(self):
        """
        L{ConsoleUI.warn} should log a traceback if the output can't be opened.
        """
        def raiseIt():
            1 / 0
        ui = ConsoleUI(raiseIt)
        ui.warn("This message never makes it.")
        self.assertEqual(len(self.flushLoggedErrors(ZeroDivisionError)), 1)



class FakeUI(object):
    """
    A fake UI object, adhering to the interface expected by
    L{KnownHostsFile.verifyHostKey}

    @ivar userWarnings: inputs provided to 'warn'.

    @ivar promptDeferred: last result returned from 'prompt'.

    @ivar promptText: the last input provided to 'prompt'.
    """

    def __init__(self):
        self.userWarnings = []
        self.promptDeferred = None
        self.promptText = None


    def prompt(self, text):
        """
        Issue the user an interactive prompt, which they can accept or deny.
        """
        self.promptText = text
        self.promptDeferred = Deferred()
        return self.promptDeferred


    def warn(self, text):
        """
        Issue a non-interactive warning to the user.
        """
        self.userWarnings.append(text)



class FakeObject(object):
    """
    A fake object that can have some attributes.  Used to fake
    L{SSHClientTransport} and L{SSHClientFactory}.
    """


class DefaultAPITests(TestCase):
    """
    The API in L{twisted.conch.client.default.verifyHostKey} is the integration
    point between the code in the rest of conch and L{KnownHostsFile}.
    """

    def patchedOpen(self, fname, mode):
        """
        The patched version of 'open'; this returns a L{FakeFile} that the
        instantiated L{ConsoleUI} can use.
        """
        self.assertEqual(fname, "/dev/tty")
        self.assertEqual(mode, "r+b")
        return self.fakeFile


    def setUp(self):
        """
        Patch 'open' in verifyHostKey.
        """
        self.fakeFile = FakeFile()
        self.patch(default, "_open", self.patchedOpen)
        self.hostsOption = self.mktemp()
        knownHostsFile = KnownHostsFile(FilePath(self.hostsOption))
        knownHostsFile.addHostKey("exists.example.com",
            Key.fromString(sampleKey))
        knownHostsFile.addHostKey("4.3.2.1", Key.fromString(sampleKey))
        knownHostsFile.save()
        self.fakeTransport = FakeObject()
        self.fakeTransport.factory = FakeObject()
        self.options = self.fakeTransport.factory.options = {
            'host': "exists.example.com",
            'known-hosts': self.hostsOption
            }


    def test_verifyOKKey(self):
        """
        L{default.verifyHostKey} should return a L{Deferred} which fires with
        C{1} when passed a host, IP, and key which already match the
        known_hosts file it is supposed to check.
        """
        l = []
        default.verifyHostKey(self.fakeTransport, "4.3.2.1", sampleKey,
                              "I don't care.").addCallback(l.append)
        self.assertEqual([1], l)


    def replaceHome(self, tempHome):
        """
        Replace the HOME environment variable until the end of the current
        test, with the given new home-directory, so that L{os.path.expanduser}
        will yield controllable, predictable results.

        @param tempHome: the pathname to replace the HOME variable with.

        @type tempHome: L{str}
        """
        oldHome = os.environ.get('HOME')
        def cleanupHome():
            if oldHome is None:
                del os.environ['HOME']
            else:
                os.environ['HOME'] = oldHome
        self.addCleanup(cleanupHome)
        os.environ['HOME'] = tempHome


    def test_noKnownHostsOption(self):
        """
        L{default.verifyHostKey} should find your known_hosts file in
        ~/.ssh/known_hosts if you don't specify one explicitly on the command
        line.
        """
        l = []
        tmpdir = self.mktemp()
        oldHostsOption = self.hostsOption
        hostsNonOption = FilePath(tmpdir).child(".ssh").child("known_hosts")
        hostsNonOption.parent().makedirs()
        FilePath(oldHostsOption).moveTo(hostsNonOption)
        self.replaceHome(tmpdir)
        self.options['known-hosts'] = None
        default.verifyHostKey(self.fakeTransport, "4.3.2.1", sampleKey,
                              "I don't care.").addCallback(l.append)
        self.assertEqual([1], l)


    def test_verifyHostButNotIP(self):
        """
        L{default.verifyHostKey} should return a L{Deferred} which fires with
        C{1} when passed a host which matches with an IP is not present in its
        known_hosts file, and should also warn the user that it has added the
        IP address.
        """
        l = []
        default.verifyHostKey(self.fakeTransport, "8.7.6.5", sampleKey,
                              "Fingerprint not required.").addCallback(l.append)
        self.assertEqual(
            ["Warning: Permanently added the RSA host key for IP address "
            "'8.7.6.5' to the list of known hosts."],
            self.fakeFile.outchunks)
        self.assertEqual([1], l)
        knownHostsFile = KnownHostsFile.fromPath(FilePath(self.hostsOption))
        self.assertEqual(True, knownHostsFile.hasHostKey("8.7.6.5",
                                             Key.fromString(sampleKey)))


    def test_verifyQuestion(self):
        """
        L{default.verifyHostKey} should return a L{Default} which fires with
        C{0} when passed a unknown host that the user refuses to acknowledge.
        """
        self.fakeTransport.factory.options['host'] = 'fake.example.com'
        self.fakeFile.inlines.append("no")
        d = default.verifyHostKey(
            self.fakeTransport, "9.8.7.6", otherSampleKey, "No fingerprint!")
        self.assertEqual(
            ["The authenticity of host 'fake.example.com (9.8.7.6)' "
             "can't be established.\n"
             "RSA key fingerprint is "
             "57:a1:c2:a1:07:a0:2b:f4:ce:b5:e5:b7:ae:cc:e1:99.\n"
              "Are you sure you want to continue connecting (yes/no)? "],
             self.fakeFile.outchunks)
        return self.assertFailure(d, UserRejectedKey)


    def test_verifyBadKey(self):
        """
        L{default.verifyHostKey} should return a L{Deferred} which fails with
        L{HostKeyChanged} if the host key is incorrect.
        """
        d = default.verifyHostKey(
            self.fakeTransport, "4.3.2.1", otherSampleKey,
            "Again, not required.")
        return self.assertFailure(d, HostKeyChanged)