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
/*
   Copyright 2016 Pierre-Étienne Meunier

   Licensed under the Apache License, Version 2.0 (the "License");
   you may not use this file except in compliance with the License.
   You may obtain a copy of the License at

       http://www.apache.org/licenses/LICENSE-2.0

   Unless required by applicable law or agreed to in writing, software
   distributed under the License is distributed on an "AS IS" BASIS,
   WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
   See the License for the specific language governing permissions and
   limitations under the License.
*/

extern crate libc;
extern crate libsodium_sys;
extern crate rand;

#[macro_use]
extern crate log;
extern crate byteorder;

extern crate rustc_serialize; // config: read base 64.
extern crate time;

pub mod sodium;
mod cryptobuf;
pub use cryptobuf::CryptoBuf;
use std::sync::{Once, ONCE_INIT};
use std::io::{Read, Write, BufRead, BufReader};


use byteorder::{ByteOrder, BigEndian};
use rustc_serialize::base64::{FromBase64};
use std::path::Path;
use std::fs::File;
use std::collections::{HashMap};


static SODIUM_INIT: Once = ONCE_INIT;

#[derive(Debug)]
pub enum Error {
    CouldNotReadKey,
    Base64(rustc_serialize::base64::FromBase64Error),
    KexInit,
    Version,
    Kex,
    DH,
    PacketAuth,
    NewKeys,
    Inconsistent,
    HUP,
    IndexOutOfBounds,
    Utf8(std::str::Utf8Error),
    UnknownKey,
    IO(std::io::Error),
}

impl From<std::io::Error> for Error {
    fn from(e: std::io::Error) -> Error {
        Error::IO(e)
    }
}
impl From<std::str::Utf8Error> for Error {
    fn from(e: std::str::Utf8Error) -> Error {
        Error::Utf8(e)
    }
}
impl From<rustc_serialize::base64::FromBase64Error> for Error {
    fn from(e: rustc_serialize::base64::FromBase64Error) -> Error {
        Error::Base64(e)
    }
}

mod negociation;

mod msg;
mod kex;

mod cipher;
use cipher::CipherT;
pub mod key;

// mod mac;
// use mac::*;
// mod compression;

mod encoding;
use encoding::*;

pub mod auth;
macro_rules! transport {
    ( $x:expr ) => {
        {
            match $x[0] {
                msg::DISCONNECT => return Ok(ReturnCode::Disconnect),
                msg::IGNORE => return Ok(ReturnCode::Ok),
                msg::UNIMPLEMENTED => return Ok(ReturnCode::Ok),
                msg::DEBUG => return Ok(ReturnCode::Ok),
                _ => {}
            }
        }
    };
}
pub enum ReturnCode {
    Ok,
    NotEnoughBytes,
    Disconnect,
    WrongPacket
}

pub mod server;
pub mod client;

const SSH_EXTENDED_DATA_STDERR: u32 = 1;

pub struct SignalName<'a> {
    name:&'a str
}
pub const SIGABRT:SignalName<'static> = SignalName { name:"ABRT" };
pub const SIGALRM:SignalName<'static> = SignalName { name:"ALRM" };
pub const SIGFPE:SignalName<'static> = SignalName { name:"FPE" };
pub const SIGHUP:SignalName<'static> = SignalName { name:"HUP" };
pub const SIGILL:SignalName<'static> = SignalName { name:"ILL" };
pub const SIGINT:SignalName<'static> = SignalName { name:"INT" };
pub const SIGKILL:SignalName<'static> = SignalName { name:"KILL" };
pub const SIGPIPE:SignalName<'static> = SignalName { name:"PIPE" };
pub const SIGQUIT:SignalName<'static> = SignalName { name:"QUIT" };
pub const SIGSEGV:SignalName<'static> = SignalName { name:"SEGV" };
pub const SIGTERM:SignalName<'static> = SignalName { name:"TERM" };
pub const SIGUSR1:SignalName<'static> = SignalName { name:"USR1" };

impl<'a> SignalName<'a> {
    pub fn other(name:&'a str) -> SignalName<'a> {
        SignalName { name:name }
    }
}

pub struct ChannelBuf<'a> {
    buffer:&'a mut CryptoBuf,
    channel: &'a mut ChannelParameters,
    write_buffer: &'a mut SSHBuffer,
    cipher: &'a mut cipher::CipherPair,
    wants_reply: bool
}
impl<'a> ChannelBuf<'a> {

    fn output(&mut self, extended:Option<u32>, buf:&[u8]) -> usize {
        debug!("output {:?} {:?}", self.channel, buf);
        let mut buf =
            if buf.len() as u32 > self.channel.recipient_window_size {
                &buf[0..self.channel.recipient_window_size as usize]
            } else {
                buf
            };
        let buf_len = buf.len();

        while buf.len() > 0 && self.channel.recipient_window_size > 0 {

            // Compute the length we're allowed to send.
            let off = std::cmp::min(buf.len(), self.channel.recipient_maximum_packet_size as usize);
            let off = std::cmp::min(off, self.channel.recipient_window_size as usize);

            //
            self.buffer.clear();

            if let Some(ext) = extended {
                self.buffer.push(msg::CHANNEL_EXTENDED_DATA);
                self.buffer.push_u32_be(self.channel.recipient_channel);
                self.buffer.push_u32_be(ext);
            } else {
                self.buffer.push(msg::CHANNEL_DATA);
                self.buffer.push_u32_be(self.channel.recipient_channel);
            }
            self.buffer.extend_ssh_string(&buf [ .. off ]);
            debug!("buffer = {:?}", self.buffer.as_slice());
            self.cipher.write(self.buffer.as_slice(), self.write_buffer);

            self.channel.recipient_window_size -= off as u32;

            buf = &buf[off..]
        }
        buf_len
    }
    pub fn stdout(&mut self, stdout:&[u8]) -> usize {
        self.output(None, stdout)
    }
    pub fn stderr(&mut self, stderr:&[u8]) -> usize {
        self.output(Some(SSH_EXTENDED_DATA_STDERR), stderr)
    }

    fn reply(&mut self, msg:u8) {
        self.buffer.clear();
        self.buffer.push(msg);
        self.buffer.push_u32_be(self.channel.recipient_channel);
        debug!("reply {:?}", self.buffer.as_slice());
        self.cipher.write(self.buffer.as_slice(), self.write_buffer);
    }
    pub fn success(&mut self) {
        if self.wants_reply {
            self.reply(msg::CHANNEL_SUCCESS);
            self.wants_reply = false
        }
    }
    pub fn failure(&mut self) {
        if self.wants_reply {
            self.reply(msg::CHANNEL_FAILURE);
            self.wants_reply = false
        }
    }
    pub fn eof(&mut self) {
        self.reply(msg::CHANNEL_EOF);
    }
    pub fn close(mut self) {
        self.reply(msg::CHANNEL_CLOSE);
    }
    
    pub fn exit_status(&mut self, exit_status: u32) {
        // https://tools.ietf.org/html/rfc4254#section-6.10
        self.buffer.clear();
        self.buffer.push(msg::CHANNEL_REQUEST);
        self.buffer.push_u32_be(self.channel.recipient_channel);
        self.buffer.extend_ssh_string(b"exit-status");
        self.buffer.push(0);
        self.buffer.push_u32_be(exit_status);
        self.cipher.write(self.buffer.as_slice(), self.write_buffer);
    }

    pub fn exit_signal(&mut self, signal_name:SignalName, core_dumped: bool, error_message:&str, language_tag: &str) {
        // https://tools.ietf.org/html/rfc4254#section-6.10
        // Windows compatibility: we can't use Unix signal names here.
        self.buffer.clear();
        self.buffer.push(msg::CHANNEL_REQUEST);
        self.buffer.push_u32_be(self.channel.recipient_channel);
        self.buffer.extend_ssh_string(b"exit-signal");
        self.buffer.push(0);

        self.buffer.extend_ssh_string(signal_name.name.as_bytes());
        self.buffer.push(if core_dumped { 1 } else { 0 });
        self.buffer.extend_ssh_string(error_message.as_bytes());
        self.buffer.extend_ssh_string(language_tag.as_bytes());

        self.cipher.write(self.buffer.as_slice(), self.write_buffer);
    }
}

pub trait Server {
    fn new_channel(&mut self, channel: &ChannelParameters);
    fn data(&mut self, _: &[u8], _: ChannelBuf) -> Result<(), Error> {
        Ok(())
    }
    fn exec(&mut self, _:&[u8], _: ChannelBuf) -> Result<(),Error> {
        Ok(())
    }
}
pub trait Client {
    fn auth_banner(&mut self, _:&str) { }
    fn new_channel(&mut self, _: &ChannelParameters) { }
    fn data(&mut self, _:Option<u32>, _: &[u8], _: ChannelBuf) -> Result<(), Error> {
        Ok(())
    }
}

pub trait ValidateKey {
    fn check_server_key(&self, _:&key::PublicKey) -> bool {
        false
    }
}

#[derive(Debug)]
pub struct SSHBuffers {
    read: SSHBuffer,
    write: SSHBuffer,
    last_rekey_s: f64,
}

#[derive(Debug)]
pub struct SSHBuffer {
    buffer: CryptoBuf,
    len: usize, // next packet length.
    bytes: usize,
    seqn: usize,
}
impl SSHBuffer {
    fn new() -> Self {
        SSHBuffer {
            buffer:CryptoBuf::new(),
            len:0,
            bytes:0,
            seqn:0
        }
    }
    pub fn read_ssh_id<'a, R: BufRead>(&'a mut self, stream: &'a mut R) -> Result<Option<&'a [u8]>, Error> {
        let i = {
            let buf = try!(stream.fill_buf());
            let mut i = 0;
            while i < buf.len() - 1 {
                if &buf[i..i + 2] == b"\r\n" {
                    break;
                }
                i += 1
            }
            if buf.len() <= 8 || i >= buf.len() - 1 {
                // Not enough bytes. Don't consume, wait until we have more bytes. The buffer is larger than 255 anyway.
                return Ok(None);
            }
            if &buf[0..8] == b"SSH-2.0-" {
                self.buffer.clear();
                self.bytes += i+2;
                self.buffer.extend(&buf[0..i+2]);
                i

            } else {
                return Err(Error::Version)
            }
        };
        stream.consume(i+2);
        Ok(Some(&self.buffer.as_slice()[0..i]))
    }
    pub fn send_ssh_id(&mut self, id:&[u8]) {
        self.buffer.extend(id);
        self.buffer.push(b'\r');
        self.buffer.push(b'\n');
    }
}
impl SSHBuffers {
    fn new() -> Self {
        SSHBuffers {
            read: SSHBuffer::new(),
            write: SSHBuffer::new(),
            last_rekey_s: time::precise_time_s(),
        }
    }
    // Returns true iff the write buffer has been completely written.
    pub fn write_all<W: std::io::Write>(&mut self, stream: &mut W) -> Result<bool, Error> {
        debug!("write_all, self = {:?}", self.write.buffer.as_slice());
        while self.write.len < self.write.buffer.len() {
            match self.write.buffer.write_all_from(self.write.len, stream) {
                Ok(s) => {
                    debug!("written {:?} bytes", s);
                    self.write.len += s;
                    self.write.bytes += s;
                    try!(stream.flush());
                }
                Err(e) => {
                    if e.kind() == std::io::ErrorKind::WouldBlock {
                        return Ok(false); // need more bytes
                    } else {
                        return Err(Error::IO(e));
                    }
                }
            }
        }
        self.write.buffer.clear();
        self.write.len = 0;
        Ok(true)
    }

    pub fn cleartext_write_kex_init(
        &mut self,
        preferred: &negociation::Preferred,
        is_server: bool,
        mut kexinit: KexInit) -> ServerState {

        if !kexinit.sent {
            let pos = self.write.buffer.len();
            self.write.buffer.extend(b"\0\0\0\0\0");
            negociation::write_kex(&preferred, &mut self.write.buffer);

            {
                let buf = self.write.buffer.as_slice();
                if is_server {
                    kexinit.exchange.server_kex_init.extend(&buf[5..]);
                } else {
                    kexinit.exchange.client_kex_init.extend(&buf[5..]);
                }
            }

            complete_packet(&mut self.write.buffer, pos);
            self.write.seqn += 1;
            kexinit.sent = true;
        }
        if let Some(names) = kexinit.algo {
            ServerState::Kex(Kex::KexDh(KexDh {
                exchange: kexinit.exchange,
                names:names,
                session_id: kexinit.session_id,
            }))
        } else {
            ServerState::Kex(Kex::KexInit(kexinit))
        }

    }
    fn set_clear_len<R: BufRead>(&mut self, stream: &mut R) -> Result<(), Error> {
        if self.read.len == 0 {
            // Packet lengths are always multiples of 8, so is a StreamBuf.
            // Therefore, this can never block.
            self.read.buffer.clear();
            try!(self.read.buffer.read(4, stream));

            self.read.len = self.read.buffer.read_u32_be(0) as usize;
        }
        Ok(())
    }

    fn get_current_payload<'b>(&'b mut self) -> &'b [u8] {
        let packet_length = self.read.buffer.read_u32_be(0) as usize;
        let padding_length = self.read.buffer[4] as usize;

        let buf = self.read.buffer.as_slice();
        let payload = {
            &buf[5..(4 + packet_length - padding_length)]
        };
        payload
    }

    /// Fills the read buffer, and returns whether a complete message has been read.
    ///
    /// It would be tempting to return either a slice of `stream`, or a
    /// slice of `read_buffer`, but except for a very small number of
    /// messages, we need double buffering anyway to decrypt in place on
    /// `read_buffer`.
    fn read<R: BufRead>(&mut self, stream: &mut R) -> Result<bool, Error> {
        // This loop consumes something or returns, it cannot loop forever.
        loop {
            let consumed_len = match stream.fill_buf() {
                Ok(buf) => {
                    if self.read.buffer.len() + buf.len() < self.read.len + 4 {

                        self.read.buffer.extend(buf);
                        buf.len()

                    } else {
                        let consumed_len = self.read.len + 4 - self.read.buffer.len();
                        self.read.buffer.extend(&buf[0..consumed_len]);
                        consumed_len
                    }
                }
                Err(e) => {
                    if e.kind() == std::io::ErrorKind::WouldBlock {
                        return Ok(false);
                    } else {
                        return Err(Error::IO(e));
                    }
                }
            };
            stream.consume(consumed_len);
            self.read.bytes += consumed_len;
            if self.read.buffer.len() >= 4 + self.read.len {
                self.read.len = 0;
                self.read.seqn += 1;
                return Ok(true);
            }
        }
    }

}

fn complete_packet(buf: &mut CryptoBuf, off: usize) {

    let block_size = 8; // no MAC yet.
    let padding_len = {
        (block_size - ((buf.len() - off) % block_size))
    };
    let padding_len = if padding_len < 4 {
        padding_len + block_size
    } else {
        padding_len
    };
    let mac_len = 0;

    let packet_len = buf.len() - off - 4 + padding_len + mac_len;
    {
        let buf = buf.as_mut_slice();
        BigEndian::write_u32(&mut buf[off..], packet_len as u32);
        buf[off + 4] = padding_len as u8;
    }


    let mut padding = [0; 256];
    sodium::randombytes::into(&mut padding[0..padding_len]);

    buf.extend(&padding[0..padding_len]);

}

#[derive(Debug)]
pub enum ServerState {
    VersionOk(Exchange),
    Kex(Kex),
    Encrypted(Encrypted), // Session is now encrypted.
}

#[derive(Debug)]
pub enum EncryptedState {
    WaitingServiceRequest,
    ServiceRequest,
    WaitingAuthRequest(auth::AuthRequest),
    RejectAuthRequest(auth::AuthRequest),
    WaitingSignature(auth::AuthRequest),
    AuthRequestSuccess(auth::AuthRequest),
    WaitingChannelOpen,
    ChannelOpenConfirmation(ChannelParameters),
    ChannelOpened(Option<u32>) // (HashSet<u32>),
}


#[derive(Debug)]
pub struct Exchange {
    client_id: Vec<u8>,
    server_id: Vec<u8>,
    client_kex_init: Vec<u8>,
    server_kex_init: Vec<u8>,
    client_ephemeral: Vec<u8>,
    server_ephemeral: Vec<u8>,
}

impl Exchange {
    fn new() -> Self {
        Exchange {
            client_id: Vec::new(),
            server_id: Vec::new(),
            client_kex_init: Vec::new(),
            server_kex_init: Vec::new(),
            client_ephemeral: Vec::new(),
            server_ephemeral: Vec::new(),
        }
    }
}

#[derive(Debug)]
pub enum Kex {
    KexInit(KexInit), /* Version number sent. `algo` and `sent` tell wether kexinit has been received, and sent, respectively. */
    KexDh(KexDh), // Algorithms have been determined, the DH algorithm should run.
    KexDhDone(KexDhDone), // The kex has run.
    NewKeys(NewKeys), /* The DH is over, we've sent the NEWKEYS packet, and are waiting the NEWKEYS from the other side. */
}



#[derive(Debug)]
pub struct KexInit {
    pub algo: Option<negociation::Names>,
    pub exchange: Exchange,
    pub session_id: Option<kex::Digest>,
    pub sent: bool
}

impl KexInit {
    pub fn kexinit(self) -> Result<Kex, Error> {
        if !self.sent {
            Ok(Kex::KexInit(self))
        } else {
            if let Some(names) = self.algo {

                Ok(Kex::KexDh(KexDh {
                    exchange:self.exchange,
                    names:names,
                    session_id: self.session_id
                }))
            } else {
                Err(Error::Kex)
            }
        }
    }

    pub fn rekey(ex:Exchange, algo:negociation::Names, session_id:&kex::Digest) -> Self {
        let mut kexinit = KexInit {
            exchange: ex,
            algo: Some(algo),
            sent: false,
            session_id: Some(session_id.clone()),
        };
        kexinit.exchange.client_kex_init.clear();
        kexinit.exchange.server_kex_init.clear();
        kexinit.exchange.client_ephemeral.clear();
        kexinit.exchange.server_ephemeral.clear();
        kexinit
    }
}

#[derive(Debug)]
pub struct KexDh {
    exchange: Exchange,
    names:negociation::Names,
    session_id: Option<kex::Digest>,
}

#[derive(Debug)]
pub struct KexDhDone {
    exchange: Exchange,
    kex: kex::Algorithm,
    session_id: Option<kex::Digest>,
    names: negociation::Names
}

impl KexDhDone {
    fn compute_keys(mut self,
                    hash: kex::Digest,
                    buffer: &mut CryptoBuf,
                    buffer2: &mut CryptoBuf,
                    is_server:bool)
                    -> Result<NewKeys, Error> {
        let session_id = if let Some(session_id) = self.session_id {
            session_id
        } else {
            hash.clone()
        };
        // Now computing keys.
        let c = try!(self.kex.compute_keys(&session_id, &hash, buffer, buffer2, &mut self.names.cipher, is_server));
        Ok(NewKeys {
            exchange: self.exchange,
            names: self.names,
            kex: self.kex,
            cipher: c,
            session_id: session_id,
            received: false,
            sent: false
        })
    }

    fn client_compute_exchange_hash<C:ValidateKey>(&mut self, client:&C, payload:&[u8], buffer:&mut CryptoBuf) -> Result<kex::Digest, Error> {
        assert!(payload[0] == msg::KEX_ECDH_REPLY);
        let mut reader = payload.reader(1);

        let pubkey = try!(reader.read_string()); // server public key.
        let pubkey = try!(read_public_key(pubkey));
        if ! client.check_server_key(&pubkey) {
            return Err(Error::UnknownKey)
        }
        let server_ephemeral = try!(reader.read_string());
        self.exchange.server_ephemeral.extend(server_ephemeral);
        let signature = try!(reader.read_string());

        try!(self.kex.compute_shared_secret(&self.exchange.server_ephemeral));

        let hash = try!(self.kex.compute_exchange_hash(&pubkey,
                                                       &self.exchange,
                                                       buffer));

        let signature = {
            let mut sig_reader = signature.reader(0);
            let sig_type = try!(sig_reader.read_string());
            assert_eq!(sig_type, b"ssh-ed25519");
            let signature = try!(sig_reader.read_string());
            sodium::ed25519::Signature::copy_from_slice(signature)
        };

        match pubkey {
            key::PublicKey::Ed25519(ref pubkey) => {

                assert!(sodium::ed25519::verify_detached(&signature, hash.as_bytes(), pubkey))

            }
        };
        debug!("signature = {:?}", signature);
        debug!("exchange = {:?}", self.exchange);
        Ok(hash)
    }

}

#[derive(Debug)]
pub struct NewKeys {
    exchange: Exchange,
    names: negociation::Names,
    kex: kex::Algorithm,
    cipher: cipher::CipherPair,
    session_id: kex::Digest,
    received:bool,
    sent:bool
}

impl NewKeys {
    fn encrypted(self, state:EncryptedState) -> Encrypted {
        Encrypted {
            exchange: Some(self.exchange),
            kex: self.kex,
            key: self.names.key,
            cipher: self.cipher,
            mac: self.names.mac,
            session_id: self.session_id,
            state: Some(state),
            rekey: None,
            channels: HashMap::new(),
        }
    }
}

#[derive(Debug)]
pub struct Encrypted {
    exchange: Option<Exchange>, // It's always Some, except when we std::mem::replace it temporarily.
    kex: kex::Algorithm,
    key: key::Algorithm,
    cipher: cipher::CipherPair,
    mac: &'static str,
    session_id: kex::Digest,
    state: Option<EncryptedState>,
    rekey: Option<Kex>,
    channels: HashMap<u32, ChannelParameters>,
}

#[derive(Debug)]
pub struct ChannelParameters {
    pub recipient_channel: u32,
    pub sender_channel: u32,
    pub recipient_window_size: u32,
    pub sender_window_size: u32,
    pub recipient_maximum_packet_size: u32,
    pub sender_maximum_packet_size: u32,
}
fn adjust_window_size(write_buffer:&mut SSHBuffer, cipher:&mut cipher::CipherPair, target:u32, buffer:&mut CryptoBuf, channel:&mut ChannelParameters) {
    buffer.clear();
    buffer.push(msg::CHANNEL_WINDOW_ADJUST);
    buffer.push_u32_be(channel.recipient_channel);
    buffer.push_u32_be(target - channel.sender_window_size);
    cipher.write(buffer.as_slice(), write_buffer);
    channel.sender_window_size = target;
}


/// Fills the read buffer, and returns whether a complete message has been read.
///
/// It would be tempting to return either a slice of `stream`, or a
/// slice of `read_buffer`, but except for a very small number of
/// messages, we need double buffering anyway to decrypt in place on
/// `read_buffer`.
fn read<R: BufRead>(stream: &mut R,
                    read_buffer: &mut CryptoBuf,
                    read_len: usize,
                    bytes_read: &mut usize)
                    -> Result<bool, Error> {
    // This loop consumes something or returns, it cannot loop forever.
    loop {
        let consumed_len = match stream.fill_buf() {
            Ok(buf) => {
                if read_buffer.len() + buf.len() < read_len + 4 {

                    read_buffer.extend(buf);
                    buf.len()

                } else {
                    let consumed_len = read_len + 4 - read_buffer.len();
                    read_buffer.extend(&buf[0..consumed_len]);
                    consumed_len
                }
            }
            Err(e) => {
                if e.kind() == std::io::ErrorKind::WouldBlock {
                    return Ok(false);
                } else {
                    return Err(Error::IO(e));
                }
            }
        };
        stream.consume(consumed_len);
        *bytes_read += consumed_len;
        if read_buffer.len() >= 4 + read_len {
            return Ok(true);
        }
    }
}


const KEYTYPE_ED25519:&'static [u8] = b"ssh-ed25519";

pub fn load_public_key<P:AsRef<Path>>(p:P) -> Result<key::PublicKey, Error> {

    let mut pubkey = String::new();
    let mut file = try!(File::open(p.as_ref()));
    try!(file.read_to_string(&mut pubkey));

    let mut split = pubkey.split_whitespace();

    match (split.next(), split.next()) {
        (Some(ssh_), Some(key)) if ssh_.starts_with("ssh-") => {
            let base = try!(key.from_base64());
            read_public_key(&base)
        },
        _ => Err(Error::CouldNotReadKey)
    }
}

pub fn read_public_key(p: &[u8]) -> Result<key::PublicKey, Error> {
    let mut pos = p.reader(0);
    if try!(pos.read_string()) == b"ssh-ed25519" {
        if let Ok(pubkey) = pos.read_string() {
            return Ok(key::PublicKey::Ed25519(sodium::ed25519::PublicKey::copy_from_slice(pubkey)))
        }
    }
    Err(Error::CouldNotReadKey)
}

pub fn load_secret_key<P:AsRef<Path>>(p:P) -> Result<key::SecretKey, Error> {

    let file = try!(File::open(p.as_ref()));
    let file = BufReader::new(file);

    let mut secret = String::new();
    let mut started = false;

    for l in file.lines() {
        let l = try!(l);
        if l == "-----BEGIN OPENSSH PRIVATE KEY-----" {
            started = true
        } else if l == "-----END OPENSSH PRIVATE KEY-----" {
            break
        } else if started {
            secret.push_str(&l)
        }
    }
    let secret = try!(secret.from_base64());

    if &secret[0..15] == b"openssh-key-v1\0" {
        let mut position = secret.reader(15);

        let ciphername = try!(position.read_string());
        let kdfname = try!(position.read_string());
        let kdfoptions = try!(position.read_string());
        info!("ciphername: {:?}", std::str::from_utf8(ciphername));
        debug!("kdf: {:?} {:?}",
                 std::str::from_utf8(kdfname),
                 std::str::from_utf8(kdfoptions));

        let nkeys = try!(position.read_u32());
        
        for _ in 0..nkeys {
            let public_string = try!(position.read_string());
            let mut pos = public_string.reader(0);
            if try!(pos.read_string()) == KEYTYPE_ED25519 {
                if let Ok(pubkey) = pos.read_string() {
                    let public = sodium::ed25519::PublicKey::copy_from_slice(pubkey);
                    info!("public: {:?}", public);
                } else {
                    info!("warning: no public key");
                }
            }
        }
        info!("there are {} keys in this file", nkeys);
        let secret = try!(position.read_string());
        if kdfname == b"none" {
            let mut position = secret.reader(0);
            let check0 = try!(position.read_u32());
            let check1 = try!(position.read_u32());
            debug!("check0: {:?}", check0);
            debug!("check1: {:?}", check1);
            for _ in 0..nkeys {

                let key_type = try!(position.read_string());
                if key_type == KEYTYPE_ED25519 {
                    let pubkey = try!(position.read_string());
                    debug!("pubkey = {:?}", pubkey);
                    let seckey = try!(position.read_string());
                    let comment = try!(position.read_string());
                    debug!("comment = {:?}", comment);
                    let secret = sodium::ed25519::SecretKey::copy_from_slice(seckey);
                    return Ok(key::SecretKey::Ed25519(secret))
                } else {
                    info!("unsupported key type {:?}", std::str::from_utf8(key_type));
                }
            }
            Err(Error::CouldNotReadKey)
        } else {
            info!("unsupported secret key cipher: {:?}", std::str::from_utf8(kdfname));
            Err(Error::CouldNotReadKey)
        }
    } else {
        Err(Error::CouldNotReadKey)
    }
}