Beispiel #1
0
 public void SetCipher(Cipher cipher, MAC mac, bool mac_enabled)
 {
     _cipher     = cipher;
     _mac        = mac;
     _macEnabled = mac_enabled;
     _head       = new byte[cipher.BlockSize];
 }
Beispiel #2
0
        public ActionResult AddMac()
        {
            var currentEmail = User.Identity.GetUserName();

            Profile currentProfile = new Profile();

            foreach (Profile profile in context.Profile)
            {
                if (profile.Email.Equals(currentEmail))
                {
                    currentProfile = profile;
                }
            }

            var macAddr = (
                from nic in NetworkInterface.GetAllNetworkInterfaces()
                where nic.OperationalStatus == OperationalStatus.Up
                select nic.GetPhysicalAddress().ToString()
                ).FirstOrDefault();

            MAC mac = new MAC();

            mac.MACAdress = macAddr;

            currentProfile.Macs.Add(mac);

            context.SaveChanges();

            return(RedirectToAction("Index", "Home"));
        }
Beispiel #3
0
            public void Read1()
            {
                MAC    mac      = MAC.Parse("FF:FF:FF:FF:FF:FF");
                string name     = "Adapter 1";
                IP     localip  = IP.Parse("192.168.1.2");
                IP     Subnet   = IP.Parse("255.255.255.0");
                IP     DefaultG = IP.Parse("192.168.1.1");
                IP     DNS      = IP.Parse("1.1.1.1");

                Adapter     a   = new Adapter(mac, 1, name, localip, Subnet, DefaultG, DNS, 1, true);
                Adapter     a2  = null;
                XmlDocument doc = new XmlDocument();

                doc.Load("XMLFile.xml");

                foreach (XmlNode node in doc.DocumentElement)
                {
                    if (node.Name == "AdapterRead1")
                    {
                        foreach (XmlNode n in node.ChildNodes)
                        {
                            if (n.Name == "Adapter")
                            {
                                a2 = Adapter.FromXML(n);
                            }
                        }
                    }
                }

                Assert.True(a.Equals(a2));
            }
Beispiel #4
0
            internal override bool isMatched(string _host)
            {
                if (!hashed)
                {
                    return(base.isMatched(_host));
                }
                MAC macsha1 = mykh.getHMACSHA1();

                try
                {
                    lock (macsha1)
                    {
                        macsha1.init(salt);
                        byte[] foo = _host.getBytes();
                        macsha1.update(foo, 0, foo.Length);
                        byte[] bar = new byte[macsha1.getBlockSize()];
                        macsha1.doFinal(bar, 0);
                        return(Util.array_equals(hash, bar));
                    }
                }
                catch (Exception e)
                {
                    Console.Out.WriteLine(e);
                }
                return(false);
            }
Beispiel #5
0
    protected void L_Autenticate_Authenticate(object sender, EventArgs e)
    {
        DAOUsuario guardarUsuario = new DAOUsuario();
        DataTable  data           = guardarUsuario.loggin(L_Autenticate.UserName.ToString(), L_Autenticate.Password.ToString());

        if (int.Parse(data.Rows[0]["user_id"].ToString()) > 0)
        {
            Session["nombre"]  = data.Rows[0]["nombre"].ToString();
            Session["user_id"] = data.Rows[0]["user_id"].ToString();

            EUsuario datosUsuario  = new EUsuario();
            MAC      datosConexion = new MAC();

            /* ipAddress = HttpContext.Current.Request.UserHostAddress;
             * mac = Utilidades.Mac.GetMAC(ref ipAddress);*/

            datosUsuario.UserId  = int.Parse(Session["user_id"].ToString());
            datosUsuario.Ip      = datosConexion.ip();
            datosUsuario.Mac     = datosConexion.mac();
            datosUsuario.Session = Session.SessionID;
            datosUsuario.RolId   = int.Parse(data.Rows[0]["rol_id"].ToString());
            Session["user"]      = datosUsuario;
            guardarUsuario.guardadoSession(datosUsuario);
            if (datosUsuario.RolId == 1)
            {
                Response.Redirect("MenuAdmin.aspx");
            }
            else
            {
                Response.Redirect("MenuOperador.aspx");
            }
        }
    }
Beispiel #6
0
    protected void Login_Conductor_Authenticate1(object sender, AuthenticateEventArgs e)
    {
        Conductor conductor = new Conductor();

        conductor.Usuario    = Login_Conductor.UserName;
        conductor.Contrasena = Login_Conductor.Password;

        ((Label)Login_Conductor.FindControl("LN_Mensaje")).Text = new LConductor().login(conductor);
        //Session["user"] = null; //Variable vacia (No ha iniciado sesión)

        conductor = new DaoConductor().login(conductor);
        MAC             conexion = new MAC();
        AccesoConductor accesoc  = new AccesoConductor();

        object s = Session["user"] = conductor; //Variable llena (Se inicio sesión)

        if (s != null)
        {
            Session["user"] = conductor;

            accesoc.FechaInicio = DateTime.Now;
            accesoc.Ip          = conexion.ip();
            accesoc.Mac         = conexion.mac();
            accesoc.Session     = Session.SessionID;
            accesoc.IdConductor = conductor.IdConductor;
            new DaoSeguridadConductor().insertarAcceso(accesoc);
        }
    }
Beispiel #7
0
            internal override bool IsMatched(string _host)
            {
                if (!this.hashed)
                {
                    return(base.IsMatched(_host));
                }
                MAC macsha1 = this._enclosing.GetHMACSHA1();

                try
                {
                    lock (macsha1)
                    {
                        macsha1.Init(this.salt);
                        byte[] foo = Util.Str2byte(_host);
                        macsha1.Update(foo, 0, foo.Length);
                        byte[] bar = new byte[macsha1.GetBlockSize()];
                        macsha1.DoFinal(bar, 0);
                        return(Util.Array_equals(this.hash, bar));
                    }
                }
                catch (Exception e)
                {
                    System.Console.Out.WriteLine(e);
                }
                return(false);
            }
        private byte[] GenerateCryptogram(CryptogramType cryptogramType)
        {
            var data = new List <byte>();

            switch (cryptogramType)
            {
            case CryptogramType.Card:
                data.AddRange(this.HostChallenge);
                data.AddRange(this.SequenceCounter);
                data.AddRange(this.CardChallenge);
                break;

            case CryptogramType.Host:
                data.AddRange(this.SequenceCounter);
                data.AddRange(this.CardChallenge);
                data.AddRange(this.HostChallenge);
                break;
            }

            data.Pad();

            byte[] cryptogram = MAC.Algorithm1(data.ToArray(), this.EncryptionKey);

            return(cryptogram);
        }
    protected void BT_Ingresar_Click(object sender, EventArgs e)
    {
        UUser  datos  = new UUser();
        LUser  logic  = new LUser();
        LMUser lmuser = new LMUser();

        datos = lmuser.loggear(TB_UserName.Text, TB_Clave.Text, int.Parse(Session["idioma"].ToString()), NoBotLogin.IsValid());

        Session["userId"]    = datos.SUserId;
        Session["userName"]  = datos.SUserName;
        Session["nombre"]    = datos.SNombre;
        Session["apellido"]  = datos.SApellido;
        Session["clave"]     = datos.SClave;
        Session["correo"]    = datos.SCorreo;
        Session["documento"] = datos.SDocumento;
        Session["foto"]      = datos.SFoto;


        try
        {
            MAC datosConexion = new MAC();

            lmuser.logicaGuardarSesion(int.Parse(Session["userId"].ToString()),
                                       datosConexion.ip(),
                                       datosConexion.mac(),
                                       Session.SessionID);

            Response.Redirect(datos.Url);
        }
        catch
        {
            L_Error.Text = datos.Mensaje;
        }
        this.Page.Response.Write(datos.MensajeIntentoErroneos);
    }
Beispiel #10
0
        public void CanProveAndVerifyMAC()
        {
            // The coordinator generates a composed private key called CoordinatorSecretKey
            // and derives from that the coordinator's public parameters called CoordinatorParameters.
            var rnd                   = new SecureRandom();
            var coordinatorKey        = new CoordinatorSecretKey(rnd);
            var coordinatorParameters = coordinatorKey.ComputeCoordinatorParameters();

            // A blinded amount is known as an `attribute`. In this case the attribute Ma is the
            // value 10000 blinded with a random `blindingFactor`. This attribute is sent to
            // the coordinator.
            var amount         = new Scalar(10_000);
            var blindingFactor = rnd.GetScalar();
            var Ma             = amount * Generators.G + blindingFactor * Generators.Gh;

            // The coordinator generates a MAC and a proof that the MAC was generated using the
            // coordinator's secret key. The coordinator sends the pair (MAC + proofOfMac) back
            // to the client.
            var t   = rnd.GetScalar();
            var mac = MAC.ComputeMAC(coordinatorKey, Ma, t);

            var coordinatorStatement = ProofSystem.CreateStatement(coordinatorParameters, mac.V, Ma, t);
            var proverBuilder        = ProofSystem.CreateProver(coordinatorStatement, coordinatorKey);
            var macProver            = proverBuilder(rnd);
            var proofOfMac           = macProver();

            // The client receives the MAC and the proofOfMac which let the client know that the MAC
            // was generated with the coordinator's secret key.
            var clientStatement = ProofSystem.CreateStatement(coordinatorParameters, mac.V, Ma, mac.T);
            var verifierBuilder = ProofSystem.CreateVerifier(clientStatement);
            var macVerifier     = verifierBuilder(proofOfMac);
            var isValidProof    = macVerifier();

            Assert.True(isValidProof);
        }
Beispiel #11
0
            internal void Hash()
            {
                if (hashed)
                {
                    return;
                }
                MAC macsha1 = mykh.getHMACSHA1();

                if (salt == null)
                {
                    Random random = Session.random;
                    lock (random)
                    {
                        salt = new byte[macsha1.getBlockSize()];
                        random.fill(salt, 0, salt.Length);
                    }
                }
                try
                {
                    lock (macsha1)
                    {
                        macsha1.init(salt);
                        byte[] foo = host.getBytes();
                        macsha1.update(foo, 0, foo.Length);
                        hash = new byte[macsha1.getBlockSize()];
                        macsha1.doFinal(hash, 0);
                    }
                }
                catch //(Exception e)
                {
                }
                host = HASH_MAGIC + Encoding.UTF8.GetString(Util.toBase64(salt, 0, salt.Length)) +
                       HASH_DELIM + Encoding.UTF8.GetString(Util.toBase64(hash, 0, hash.Length));
                hashed = true;
            }
Beispiel #12
0
 /// <summary>
 /// Overrides Close()
 /// </summary>
 /// <param name="cipher"></param>
 /// <param name="rnd"></param>
 /// <param name="mac"></param>
 /// <param name="sequence"></param>
 /// <returns></returns>
 public override DataFragment Close(Cipher cipher, Random rnd, MAC mac, int sequence) {
     byte[] buf = DataWriter.UnderlyingBuffer;
     int sftpDataLength = DataWriter.Length - OFFSET_SFTP_PACKET_TYPE;
     SSHUtil.WriteIntToByteArray(buf, OFFSET_CHANNEL_DATA_LENGTH, sftpDataLength + 4);
     SSHUtil.WriteIntToByteArray(buf, OFFSET_SFTP_DATA_LENGTH, sftpDataLength);
     return base.Close(cipher, rnd, mac, sequence);
 }
Beispiel #13
0
 public bool isAvailable(IP ip, MAC client)
 {
     lock (Leaseslock)
     {
         if (Leases.ContainsKey(ip))
         {
             if (Leases[ip].chaddr == client)
             {
                 return(true);
             }
             else
             {
                 return(false);
             }
         }
         if (Reserved.ContainsKey(ip))
         {
             if ((bool)Reserved[ip].chaddr?.Equals(client))
             {
                 return(true);
             }
             else
             {
                 return(false);
             }
         }
         else
         {
             return(true);
         }
     }
 }
Beispiel #14
0
        public void Close(Cipher cipher, Random rnd, MAC mac, int sequence, DataFragment result) {
            if(!_is_open) throw new SSHException("internal state error");
            
            int blocksize = cipher==null? 8 : cipher.BlockSize;
            int payload_length = _writer.Length - (SEQUENCE_MARGIN + LENGTH_MARGIN + PADDING_MARGIN);
            int r = 11 - payload_length % blocksize;
            while(r < 4) r += blocksize;
            _paddingLength = r;
            _packetLength = PADDING_MARGIN + payload_length + _paddingLength;
            int image_length = _packetLength + LENGTH_MARGIN;

            //fill padding
            for(int i=0; i<_paddingLength; i+=4)
                _writer.Write(rnd.Next());

            //manipulate stream
            byte[] rawbuf = _writer.UnderlyingBuffer;
            SSHUtil.WriteIntToByteArray(rawbuf, 0, sequence);
            SSHUtil.WriteIntToByteArray(rawbuf, SEQUENCE_MARGIN, _packetLength);
            rawbuf[SEQUENCE_MARGIN + LENGTH_MARGIN] = (byte)_paddingLength;

            //mac
            if(mac!=null) {
                _mac = mac.ComputeHash(rawbuf, 0, _packetLength+LENGTH_MARGIN+SEQUENCE_MARGIN);
                Array.Copy(_mac, 0, rawbuf, _packetLength+LENGTH_MARGIN+SEQUENCE_MARGIN, _mac.Length);
                image_length += _mac.Length;
            }

            //encrypt
            if(cipher!=null)
                cipher.Encrypt(rawbuf, SEQUENCE_MARGIN, _packetLength+LENGTH_MARGIN, rawbuf, SEQUENCE_MARGIN);

            result.Init(rawbuf, SEQUENCE_MARGIN, image_length);
            _is_open = false;
        }
Beispiel #15
0
 public Lease(IP ClientIP, MAC ClientHardwareAddress, uint LeaseStartTick, uint LeaseLength)
 {
     ciaddr = ClientIP;
     chaddr = ClientHardwareAddress;
     this.LeaseStartTick = LeaseStartTick;
     this.LeaseLength    = LeaseLength;
 }
Beispiel #16
0
            public void Identicalbytearray()
            {
                Byte[] b1 = new byte[]
                {
                    255,
                    255,
                    255,
                    255,
                    255,
                    255
                };

                Byte[] b2 = new byte[]
                {
                    255,
                    255,
                    255,
                    255,
                    255,
                    255
                };


                MAC m1 = new MAC(b1);
                MAC m2 = new MAC(b2);

                Assert.True(m1.Equals(m2));
            }
Beispiel #17
0
        private void ProcessBuffer()
        {
            // buffer may contains multiple packet data
            while (ConstructPacket())
            {
                if (IsMsgNewKeys(_packet))
                {
                    // next packet must be decrypted with the new key
                    _cipher     = null;
                    _mac        = null;
                    _macEnabled = false;
                    _head       = null;

                    _pending = true;    // retain trailing packets in the buffer
                    _keyErrorDetectionTimeout = DateTime.MaxValue;

                    SSH2MsgNewKeys newKeysPacket =
                        new SSH2MsgNewKeys(_packet, new SSH2MsgNewKeys.Handler(OnMsgNewKeysDequeued));

                    _inner_handler.OnData(newKeysPacket);
                    break;
                }

                _inner_handler.OnData(_packet);
            }
        }
Beispiel #18
0
        private void GetWingParameters()
        {
            N  = Int16.Parse(txt_Segments.Text);
            AR = Double.Parse(txt_AR.Text);

            B = new Double[N, N];

            txt_Sw.Text = S_w.ToString();
            tr_w        = Double.Parse(txt_Taper.Text);

            b_w = Math.Round(Math.Sqrt(AR * S_w), 4);
            txt_WingSpan.Text = b_w.ToString();

            MAC          = Math.Round(S_w / b_w, 4);
            txt_MAC.Text = MAC.ToString();

            cr_w = Math.Round((1.5 * MAC * (1 + tr_w)) / (1 + tr_w + Math.Pow(tr_w, 2)), 4);
            txt_RootChord.Text = cr_w.ToString();

            i_w = Double.Parse(txt_WingSetting.Text);

            alpha0 = Double.Parse(txt_Zerolift.Text);

            a_2d = Double.Parse(txt_LiftCurve.Text);

            alpha_twist = Double.Parse(txt_Twist.Text);
        }
Beispiel #19
0
        /// <summary>
        /// Gets the binary image of this packet.
        /// </summary>
        /// <param name="cipher">cipher algorithm, or null if no encryption.</param>
        /// <param name="mac">MAC algorithm, or null if no MAC.</param>
        /// <param name="sequenceNumber">sequence number</param>
        /// <returns>data</returns>
        public DataFragment GetImage(Cipher cipher, MAC mac, uint sequenceNumber)
        {
            BeforeBuildImage();
            ByteBuffer image = BuildImage(cipher, mac, sequenceNumber);

            _lockFlag.Value = false;
            return(image.AsDataFragment());
        }
Beispiel #20
0
 /// <summary>
 /// Set cipher settings.
 /// </summary>
 /// <param name="cipher">cipher algorithm, or null if not specified.</param>
 /// <param name="mac">MAC algorithm, or null if not specified.</param>
 public void SetCipher(Cipher cipher, MAC mac)
 {
     lock (_cipherSync) {
         _cipher    = cipher;
         _mac       = mac;
         _macLength = (_mac != null) ? _mac.Size : 0;
     }
 }
Beispiel #21
0
        //constracts and appends mac
        public void CalcHash(MAC mac, int sequence)
        {
            byte[] buf = new byte[4 + 4 + _packetLength];
            SSHUtil.WriteIntToByteArray(buf, 0, sequence);
            WriteTo(buf, 4, false);

            _mac = mac.Calc(buf);
        }
Beispiel #22
0
        /// <summary>
        /// Gets the binary image of this packet.
        /// </summary>
        /// <param name="cipher">cipher algorithm, or null if no encryption.</param>
        /// <param name="mac">MAC algorithm, or null if no MAC.</param>
        /// <param name="sequenceNumber">sequence number</param>
        /// <returns>data</returns>
        public DataFragment GetImage(Cipher cipher, MAC mac, uint sequenceNumber)
        {
            BeforeBuildImage();
            ByteBuffer image = BuildImage(cipher, mac, sequenceNumber);

            Recycle();
            return(image.AsDataFragment());
        }
Beispiel #23
0
        private (MAC Mac, Knowledge Knowledge) IssueCredential(GroupElement ma, Scalar t)
        {
            var sk        = CoordinatorSecretKey;
            var mac       = MAC.ComputeMAC(sk, ma, t);
            var knowledge = ProofSystem.IssuerParameters(mac, ma, sk);

            return(mac, knowledge);
        }
        public MAC GetMAC(byte[] bytes)
        {
            var WCHash = new WCHash(bytes.Length * 4, _macLength * 4, _keyBuffer.GetKey((int)Math.Ceiling((_macLength + Math.Log2(Math.Log2((int)bytes.Length * 4)) * Math.Log2((int)bytes.Length * 4)))));

            var mac = new MAC(WCHash.F(bytes).ToByteArray());

            return(mac);
        }
Beispiel #25
0
        public override int GetHashCode()
        {
            int hash = Name.GetHashCode();

            hash = 31 * hash + MAC.GetHashCode();
            hash = 31 * hash + ConnectionQuality.GetHashCode();
            hash = 31 * hash + AuthenticationType.GetHashCode();
            return(hash);
        }
Beispiel #26
0
 public SSH2PacketBuilder(IDataHandler handler) : base(handler)
 {
     _buffer   = new DataFragment(0x1000);
     _packet   = new DataFragment(_buffer.Capacity);
     _sequence = 0;
     _cipher   = null;
     _mac      = null;
     _head     = null;
 }
Beispiel #27
0
        public string VerificaRegistro()
        {
            //Variáveis.
            DA   = null;
            DA   = new SqlCeDataAdapter("Select * from CH_Hardware", SQLConn); //Instância DataAdapter com o cod a executar e a conexão
            TBCH = null;
            TBCH = new DataTable();
            DA.Fill(TBCH); //preenche tabela
            string Processador, HD, MAC;

            if (TBCH.Rows.Count == 0) //Se igual a zero, insere na tabela.
            {
                SQLConn.Close();
                InsereDados();
                retorno = "C";
            }
            else //Senão, faz a comparação com o arquivo local.
            {
                InformacaoHD("IDHD");
                InformacaoHD("Capacidade");
                InformacaoHD("EspacoLivre");
                InformacaoProcessador("IDProcessador");
                InformacaoProcessador("Nome");
                InformacaoProcessador("Arquitetura");
                InformacaoMemoria("Capacidade");
                InformacaoRede();

                Processador = TBCH.Rows[0]["SERIALPROCESSADOR"].ToString();
                HD          = TBCH.Rows[0]["SERIALHD"].ToString();
                MAC         = TBCH.Rows[0]["EnderecoMAC"].ToString();

                if ((Processador.Length <= 1) || (HD.Length <= 1) || (MAC.Length <= 1))
                {
                    ExcluirTabela();
                    CriaTabelaChaveHardware();
                    //InsereDados();
                    return("C");
                }

                //Faz a comparação.
                if ((IDProcessador.Trim() == Processador.Trim()) &&
                    (SerialHD.Trim() == HD.Trim()) &&
                    (MACRede.Trim() == MAC.Trim()))
                {
                    retorno = "C";
                }
                else if (MACRede == "")
                {
                    retorno = "C";
                }
                else
                {
                    retorno = "N";
                }
            }
            return(retorno);
        }
Beispiel #28
0
        /// <summary>
        /// Overrides Close()
        /// </summary>
        /// <param name="cipher"></param>
        /// <param name="mac"></param>
        /// <param name="sequence"></param>
        /// <returns></returns>
        public override DataFragment Close(Cipher cipher, MAC mac, int sequence)
        {
            byte[] buf            = DataWriter.UnderlyingBuffer;
            int    sftpDataLength = DataWriter.Length - OFFSET_SFTP_PACKET_TYPE;

            SSHUtil.WriteIntToByteArray(buf, OFFSET_CHANNEL_DATA_LENGTH, sftpDataLength + 4);
            SSHUtil.WriteIntToByteArray(buf, OFFSET_SFTP_DATA_LENGTH, sftpDataLength);
            return(base.Close(cipher, mac, sequence));
        }
Beispiel #29
0
 public static Statement IssuerParametersStmt(CoordinatorParameters iparams, MAC mac, GroupElement ma)
 => new Statement(new GroupElement[, ]
 {
     // public                                             Witness terms:
     // point                     w,             wp,             x0,             x1,             ya
     { mac.V, Generators.Gw, O, mac.U, mac.T * mac.U, ma },
     { Generators.GV - iparams.I, O, O, Generators.Gx0, Generators.Gx1, Generators.Ga },
     { iparams.Cw, Generators.Gw, Generators.Gwp, O, O, O },
 });
Beispiel #30
0
            public Header(Command cmd, MAC destMAC)
            {
                this.Cmd = cmd;
                this.Mac = destMAC;

                this.PackNo            = 1;
                this.TotalNumOfPackets = 1;
                this.SeqNo             = 1;
            }
Beispiel #31
0
 /// <summary>
 /// Set cipher settings.
 /// </summary>
 /// <param name="cipher">cipher algorithm, or null if not specified.</param>
 /// <param name="mac">MAC algorithm, or null if not specified.</param>
 /// <param name="checkMAC">specifies whether MAC check is performed.</param>
 public void SetCipher(Cipher cipher, MAC mac, bool checkMAC)
 {
     lock (_cipherSync) {
         _cipher    = cipher;
         _mac       = mac;
         _macLength = (mac != null) ? mac.Size : 0;
         _checkMAC  = (mac != null) ? checkMAC : false;
     }
 }
Beispiel #32
0
 /// <summary>
 /// Constructor
 /// </summary>
 /// <param name="handler">a handler that SSH packets are passed to</param>
 public SSH2Packetizer(IDataHandler handler)
 {
     _nextHandler  = handler;
     _sequence     = 0;
     _cipher       = null;
     _mac          = null;
     _macLength    = 0;
     _packetLength = -1;
 }
Beispiel #33
0
        // Derived class can override this method to modify the buffer.
        public virtual DataFragment Close(Cipher cipher, MAC mac, int sequence) {
            if (!_isOpen)
                throw new SSHException("internal state error");

            int blocksize = cipher == null ? 8 : cipher.BlockSize;
            int payloadLength = _writer.Length - (SEQUENCE_MARGIN + LENGTH_MARGIN + PADDING_MARGIN);
            int paddingLength = 11 - payloadLength % blocksize;
            while (paddingLength < 4)
                paddingLength += blocksize;
            int packetLength = PADDING_MARGIN + payloadLength + paddingLength;
            int imageLength = packetLength + LENGTH_MARGIN;

            //fill padding
	        byte[] tmp = new byte[4];
            Rng rng = RngManager.GetSecureRng();
            for (int i = 0; i < paddingLength; i += 4) {
                rng.GetBytes(tmp);
                _writer.Write(tmp);
            }

            //manipulate stream
            byte[] rawbuf = _writer.UnderlyingBuffer;
            SSHUtil.WriteIntToByteArray(rawbuf, 0, sequence);
            SSHUtil.WriteIntToByteArray(rawbuf, SEQUENCE_MARGIN, packetLength);
            rawbuf[SEQUENCE_MARGIN + LENGTH_MARGIN] = (byte)paddingLength;

            //mac
            if (mac != null) {
                byte[] macCode = mac.ComputeHash(rawbuf, 0, packetLength + LENGTH_MARGIN + SEQUENCE_MARGIN);
                Array.Copy(macCode, 0, rawbuf, packetLength + LENGTH_MARGIN + SEQUENCE_MARGIN, macCode.Length);
                imageLength += macCode.Length;
            }

            //encrypt
            if (cipher != null)
                cipher.Encrypt(rawbuf, SEQUENCE_MARGIN, packetLength + LENGTH_MARGIN, rawbuf, SEQUENCE_MARGIN);

            _dataFragment.Init(rawbuf, SEQUENCE_MARGIN, imageLength);
            _isOpen = false;
            return _dataFragment;
        }
Beispiel #34
0
        private void ProcessBuffer()
        {
            // buffer may contains multiple packet data
            while (ConstructPacket()) {
                if (IsMsgNewKeys(_packet)) {
                    // next packet must be decrypted with the new key
                    _cipher = null;
                    _mac = null;
                    _macEnabled = false;
                    _head = null;

                    _pending = true;    // retain trailing packets in the buffer
                    _keyErrorDetectionTimeout = DateTime.MaxValue;

                    SSH2MsgNewKeys newKeysPacket =
                        new SSH2MsgNewKeys(_packet, new SSH2MsgNewKeys.Handler(OnMsgNewKeysDequeued));

                    _inner_handler.OnData(newKeysPacket);
                    break;
                }

                _inner_handler.OnData(_packet);
            }
        }
Beispiel #35
0
        public void SetCipher(Cipher cipher, MAC mac, bool mac_enabled)
        {
            lock (_cipherSync) {
                try {
                    _cipher = cipher;
                    _mac = mac;
                    _macEnabled = mac_enabled;
                    _head = new byte[cipher.BlockSize];

                    _pending = false;
                    _keyErrorDetectionTimeout = DateTime.MaxValue;

                    ProcessBuffer();
                } catch (Exception ex) {
                    OnError(ex);
                }
            }
        }
Beispiel #36
0
 public SSH2PacketBuilder(IDataHandler handler)
     : base(handler)
 {
     _buffer = new DataFragment(0x1000);
     _packet = new DataFragment(_buffer.Capacity);
     _sequence = 0;
     _cipher = null;
     _mac = null;
     _head = null;
 }
Beispiel #37
0
        public static SSH2Packet FromDecryptedHead(byte[] head, byte[] buffer, int offset, Cipher cipher, int sequence, MAC mac)
        {
            SSH2Packet p = new SSH2Packet();
            p._packetLength = SSHUtil.ReadInt32(head, 0);
            if(p._packetLength<=0 || p._packetLength>=MAX_PACKET_LENGTH) throw new Exception(String.Format("packet size {0} is invalid", p._packetLength));
            SSH2DataWriter buf = new SSH2DataWriter();
            buf.Write(sequence);
            buf.Write(head);
            if(p._packetLength > (cipher.BlockSize - 4)) {
                byte[] tmp = new byte[p._packetLength-(cipher.BlockSize - 4)];
                cipher.Decrypt(buffer, offset, tmp.Length, tmp, 0);
                offset += tmp.Length;
                buf.Write(tmp);
            }
            byte[] result = buf.ToByteArray();
            int padding_len = (int)result[8];
            if(padding_len<4) throw new Exception("padding length is invalid");

            byte[] payload = new byte[result.Length-9-padding_len];
            Array.Copy(result, 9, payload, 0, payload.Length);
            p._payload = payload;

            if(mac!=null) {
                p._mac = mac.Calc(result);
                if(SSHUtil.memcmp(p._mac, 0, buffer, offset, mac.Size)!=0)
                    throw new Exception("MAC Error");
            }
            return p;
        }
Beispiel #38
0
 public SSH2PacketBuilder(ISSH2PacketHandler handler)
 {
     _handler = handler;
     _buffer = new byte[0x1000];
     _readOffset = 0;
     _writeOffset = 0;
     _sequence = 0;
     _cipher = null;
     _mac = null;
     _head = null;
 }
Beispiel #39
0
 public void SetCipher(Cipher c, MAC m)
 {
     _cipher = c;
     _mac = m;
 }
Beispiel #40
0
 private MAC getHMACSHA1()
 {
     if (hmacsha1 == null)
     {
         try
         {
             Type c = Type.GetType(JSch.getConfig("hmac-sha1"));
             hmacsha1 = (MAC)(c.newInstance());
         }
         catch (Exception e)
         {
             Console.Error.WriteLine("hmacsha1: " + e);
         }
     }
     return hmacsha1;
 }
Beispiel #41
0
        private void updateKeys(KeyExchange kex)
        {
            byte[] K = kex.getK();
            byte[] H = kex.getH();
            HASH hash = kex.getHash();

            //    string[] guess=kex.guess;

            if (session_id == null)
            {
                session_id = new byte[H.Length];
                Array.Copy(H, 0, session_id, 0, H.Length);
            }

            /*
              Initial IV client to server:     HASH (K || H || "A" || session_id)
              Initial IV server to client:     HASH (K || H || "B" || session_id)
              Encryption key client to server: HASH (K || H || "C" || session_id)
              Encryption key server to client: HASH (K || H || "D" || session_id)
              Integrity key client to server:  HASH (K || H || "E" || session_id)
              Integrity key server to client:  HASH (K || H || "F" || session_id)
            */

            buf.reset();
            buf.putMPInt(K);
            buf.putByte(H);
            buf.putByte((byte)0x41);
            buf.putByte(session_id);
            hash.update(buf.buffer, 0, buf.index);
            IVc2s = hash.digest();

            int j = buf.index - session_id.Length - 1;

            buf.buffer[j]++;
            hash.update(buf.buffer, 0, buf.index);
            IVs2c = hash.digest();

            buf.buffer[j]++;
            hash.update(buf.buffer, 0, buf.index);
            Ec2s = hash.digest();

            buf.buffer[j]++;
            hash.update(buf.buffer, 0, buf.index);
            Es2c = hash.digest();

            buf.buffer[j]++;
            hash.update(buf.buffer, 0, buf.index);
            MACc2s = hash.digest();

            buf.buffer[j]++;
            hash.update(buf.buffer, 0, buf.index);
            MACs2c = hash.digest();

            try
            {
                Type c;
                string method;

                method = guess[KeyExchange.PROPOSAL_ENC_ALGS_STOC];
                c = Type.GetType(getConfig(method));
                s2ccipher = (Cipher)(c.newInstance());
                while (s2ccipher.getBlockSize() > Es2c.Length)
                {
                    buf.reset();
                    buf.putMPInt(K);
                    buf.putByte(H);
                    buf.putByte(Es2c);
                    hash.update(buf.buffer, 0, buf.index);
                    byte[] foo = hash.digest();
                    byte[] bar = new byte[Es2c.Length + foo.Length];
                    Array.Copy(Es2c, 0, bar, 0, Es2c.Length);
                    Array.Copy(foo, 0, bar, Es2c.Length, foo.Length);
                    Es2c = bar;
                }
                s2ccipher.init(Cipher.DECRYPT_MODE, Es2c, IVs2c);
                s2ccipher_size = s2ccipher.getIVSize();

                method = guess[KeyExchange.PROPOSAL_MAC_ALGS_STOC];
                c = Type.GetType(getConfig(method));
                s2cmac = (MAC)(c.newInstance());
                s2cmac.init(MACs2c);
                //mac_buf=new byte[s2cmac.getBlockSize()];
                s2cmac_result1 = new byte[s2cmac.getBlockSize()];
                s2cmac_result2 = new byte[s2cmac.getBlockSize()];

                method = guess[KeyExchange.PROPOSAL_ENC_ALGS_CTOS];
                c = Type.GetType(getConfig(method));
                c2scipher = (Cipher)(c.newInstance());
                while (c2scipher.getBlockSize() > Ec2s.Length)
                {
                    buf.reset();
                    buf.putMPInt(K);
                    buf.putByte(H);
                    buf.putByte(Ec2s);
                    hash.update(buf.buffer, 0, buf.index);
                    byte[] foo = hash.digest();
                    byte[] bar = new byte[Ec2s.Length + foo.Length];
                    Array.Copy(Ec2s, 0, bar, 0, Ec2s.Length);
                    Array.Copy(foo, 0, bar, Ec2s.Length, foo.Length);
                    Ec2s = bar;
                }
                c2scipher.init(Cipher.ENCRYPT_MODE, Ec2s, IVc2s);
                c2scipher_size = c2scipher.getIVSize();

                method = guess[KeyExchange.PROPOSAL_MAC_ALGS_CTOS];
                c = Type.GetType(getConfig(method));
                c2smac = (MAC)(c.newInstance());
                c2smac.init(MACc2s);

                method = guess[KeyExchange.PROPOSAL_COMP_ALGS_CTOS];
                initDeflater(method);

                method = guess[KeyExchange.PROPOSAL_COMP_ALGS_STOC];
                initInflater(method);
            }
            catch (Exception e)
            {
                if (e is JSchException)
                    throw e;
                throw new JSchException(e.ToString(), e);
                //Console.Error.WriteLine("updatekeys: "+e);
            }
        }
Beispiel #42
0
 internal void RefreshKeys(byte[] sessionID, Cipher tc, Cipher rc, MAC tm, MAC rm) {
     lock(this) { //these must change synchronously
         _sessionID = sessionID;
         _tCipher = tc;
         _tMAC = tm;
         _packetBuilder.SetCipher(rc, rm, _param.CheckMACError);
         _asyncKeyExchanger = null;
     }
 }
Beispiel #43
0
        private DataFragment SendNEWKEYS(Mode mode) {
            _status = Status.WAIT_NEWKEYS;
            Monitor.Enter(_connection); //lock the connection during we exchange sSH_MSG_NEWKEYS
            TransmitRawPayload(new byte[1] {(byte)PacketType.SSH_MSG_NEWKEYS});

            //establish Ciphers
            _tc = CipherFactory.CreateCipher(SSHProtocol.SSH2, _cInfo._algorithmForTransmittion,
                DeriveKey(_k, _hash, 'C', CipherFactory.GetKeySize(_cInfo._algorithmForTransmittion)), DeriveKey(_k, _hash, 'A', CipherFactory.GetBlockSize(_cInfo._algorithmForTransmittion)));
            _rc = CipherFactory.CreateCipher(SSHProtocol.SSH2, _cInfo._algorithmForReception,
                DeriveKey(_k, _hash, 'D', CipherFactory.GetKeySize(_cInfo._algorithmForReception)), DeriveKey(_k, _hash, 'B', CipherFactory.GetBlockSize(_cInfo._algorithmForReception)));

            //establish MACs
            MACAlgorithm ma = MACAlgorithm.HMACSHA1;
            _tm = MACFactory.CreateMAC(MACAlgorithm.HMACSHA1, DeriveKey(_k, _hash, 'E', MACFactory.GetSize(ma)));
            _rm = MACFactory.CreateMAC(MACAlgorithm.HMACSHA1, DeriveKey(_k, _hash, 'F', MACFactory.GetSize(ma)));
            
            if(mode==Mode.Synchronized)
                return _connection.ReceivePacket();
            else
                return null;
        }
Beispiel #44
0
        private void SendNEWKEYS()
        {
            _status = Status.WAIT_NEWKEYS;
            _newKeyEvent = new ManualResetEvent(false);
            TransmitPacket(new byte[1] {(byte)PacketType.SSH_MSG_NEWKEYS});

            //establish Ciphers
            _tc = CipherFactory.CreateCipher(SSHProtocol.SSH2, _cInfo._algorithmForTransmittion,
                DeriveKey(_k, _hash, 'C', CipherFactory.GetKeySize(_cInfo._algorithmForTransmittion)), DeriveKey(_k, _hash, 'A', CipherFactory.GetBlockSize(_cInfo._algorithmForTransmittion)));
            _rc = CipherFactory.CreateCipher(SSHProtocol.SSH2, _cInfo._algorithmForReception,
                DeriveKey(_k, _hash, 'D', CipherFactory.GetKeySize(_cInfo._algorithmForReception)), DeriveKey(_k, _hash, 'B', CipherFactory.GetBlockSize(_cInfo._algorithmForReception)));

            //establish MACs
            MACAlgorithm ma = MACAlgorithm.HMACSHA1;
            _tm = MACFactory.CreateMAC(MACAlgorithm.HMACSHA1, DeriveKey(_k, _hash, 'E', MACFactory.GetSize(ma)));
            _rm = MACFactory.CreateMAC(MACAlgorithm.HMACSHA1, DeriveKey(_k, _hash, 'F', MACFactory.GetSize(ma)));
            _newKeyEvent.Set();
        }
Beispiel #45
0
 internal void RefreshKeys(byte[] sessionID, Cipher tc, Cipher rc, MAC tm, MAC rm)
 {
     _sessionID = sessionID;
     _tCipher = tc;
     _tMAC = tm;
     _packetBuilder.SetCipher(rc, _param.CheckMACError? rm : null);
     _asyncKeyExchanger = null;
 }
Beispiel #46
0
        //constracts and appends mac
        public void CalcHash(MAC mac, int sequence)
        {
            byte[] buf = new byte[4+4+_packetLength];
            SSHUtil.WriteIntToByteArray(buf, 0, sequence);
            WriteTo(buf, 4, false);

            _mac = mac.Calc(buf);
        }
 public void SetCipher(Cipher cipher, MAC mac, bool mac_enabled)
 {
     _cipher = cipher;
     _mac = mac;
     _macEnabled = mac_enabled;
     _head = new byte[cipher.BlockSize];
 }
Beispiel #48
0
        private void updateKeys(KeyExchange kex)
        {
            byte[] K = kex.getK();
            byte[] H = kex.getH();
            HASH hash = kex.getHash();

            string[] guess = kex.m_guess;

            if (m_session_id == null)
            {
                m_session_id = new byte[H.Length];
                Array.Copy(H, 0, m_session_id, 0, H.Length);
            }

            /*
              Initial IV client to server:     HASH (K || H || "A" || session_id)
              Initial IV server to client:     HASH (K || H || "B" || session_id)
              Encryption key client to server: HASH (K || H || "C" || session_id)
              Encryption key server to client: HASH (K || H || "D" || session_id)
              Integrity key client to server:  HASH (K || H || "E" || session_id)
              Integrity key server to client:  HASH (K || H || "F" || session_id)
            */

            m_buf.reset();
            m_buf.putMPInt(K);
            m_buf.putByte(H);
            m_buf.putByte((byte)0x41);
            m_buf.putByte(m_session_id);
            hash.update(m_buf.m_buffer, 0, m_buf.m_index);
            m_IVc2s = hash.digest();

            int j = m_buf.m_index - m_session_id.Length - 1;

            m_buf.m_buffer[j]++;
            hash.update(m_buf.m_buffer, 0, m_buf.m_index);
            m_IVs2c = hash.digest();

            m_buf.m_buffer[j]++;
            hash.update(m_buf.m_buffer, 0, m_buf.m_index);
            m_Ec2s = hash.digest();

            m_buf.m_buffer[j]++;
            hash.update(m_buf.m_buffer, 0, m_buf.m_index);
            m_Es2c = hash.digest();

            m_buf.m_buffer[j]++;
            hash.update(m_buf.m_buffer, 0, m_buf.m_index);
            m_MACc2s = hash.digest();

            m_buf.m_buffer[j]++;
            hash.update(m_buf.m_buffer, 0, m_buf.m_index);
            m_MACs2c = hash.digest();

            try
            {
                Class c;

                c = Class.ForName(getConfig(guess[KeyExchange.PROPOSAL_ENC_ALGS_STOC]));
                m_s2ccipher = (Cipher)(c.Instance());
                while (m_s2ccipher.BlockSize > m_Es2c.Length)
                {
                    m_buf.reset();
                    m_buf.putMPInt(K);
                    m_buf.putByte(H);
                    m_buf.putByte(m_Es2c);
                    hash.update(m_buf.m_buffer, 0, m_buf.m_index);
                    byte[] foo = hash.digest();
                    byte[] bar = new byte[m_Es2c.Length + foo.Length];
                    Array.Copy(m_Es2c, 0, bar, 0, m_Es2c.Length);
                    Array.Copy(foo, 0, bar, m_Es2c.Length, foo.Length);
                    m_Es2c = bar;
                }
                m_s2ccipher.init(jsch.Cipher.DECRYPT_MODE, m_Es2c, m_IVs2c);
                m_cipher_size = m_s2ccipher.IVSize;
                c = Class.ForName(getConfig(guess[KeyExchange.PROPOSAL_MAC_ALGS_STOC]));
                m_s2cmac = (MAC)(c.Instance());
                m_s2cmac.init(m_MACs2c);
                m_mac_buf = new byte[m_s2cmac.BlockSize];

                c = Class.ForName(getConfig(guess[KeyExchange.PROPOSAL_ENC_ALGS_CTOS]));
                m_c2scipher = (Cipher)(c.Instance());
                while (m_c2scipher.BlockSize > m_Ec2s.Length)
                {
                    m_buf.reset();
                    m_buf.putMPInt(K);
                    m_buf.putByte(H);
                    m_buf.putByte(m_Ec2s);
                    hash.update(m_buf.m_buffer, 0, m_buf.m_index);
                    byte[] foo = hash.digest();
                    byte[] bar = new byte[m_Ec2s.Length + foo.Length];
                    Array.Copy(m_Ec2s, 0, bar, 0, m_Ec2s.Length);
                    Array.Copy(foo, 0, bar, m_Ec2s.Length, foo.Length);
                    m_Ec2s = bar;
                }
                m_c2scipher.init(jsch.Cipher.ENCRYPT_MODE, m_Ec2s, m_IVc2s);

                c = Class.ForName(getConfig(guess[KeyExchange.PROPOSAL_MAC_ALGS_CTOS]));
                m_c2smac = (MAC)(c.Instance());
                m_c2smac.init(m_MACc2s);

                if (!guess[KeyExchange.PROPOSAL_COMP_ALGS_CTOS].Equals("none"))
                {
                    string foo = getConfig(guess[KeyExchange.PROPOSAL_COMP_ALGS_CTOS]);
                    if (foo != null)
                    {
                        try
                        {
                            c = Class.ForName(foo);
                            m_deflater = (Compression)(c.Instance());
                            int level = 6;
                            try
                            {
                                level = int.Parse(getConfig("compression_level"));
                            }
                            catch (Exception)
                            { }
                            m_deflater.init(Compression.DEFLATER, level);
                        }
                        catch (Exception)
                        {
                            Console.Error.WriteLine(foo + " isn't accessible.");
                        }
                    }
                }
                else
                {
                    if (m_deflater != null)
                        m_deflater = null;
                }
                if (!guess[KeyExchange.PROPOSAL_COMP_ALGS_STOC].Equals("none"))
                {
                    string foo = getConfig(guess[KeyExchange.PROPOSAL_COMP_ALGS_STOC]);
                    if (foo != null)
                    {
                        try
                        {
                            c = Class.ForName(foo);
                            m_inflater = (Compression)(c.Instance());
                            m_inflater.init(Compression.INFLATER, 0);
                        }
                        catch (Exception)
                        {
                            Console.Error.WriteLine(foo + " isn't accessible.");
                        }
                    }
                }
                else
                {
                    if (m_inflater != null)
                        m_inflater = null;
                }
            }
            catch (Exception e) { Console.Error.WriteLine("updatekeys: " + e); }
        }
Beispiel #49
0
		/// <exception cref="NSch.JSchException"></exception>
		/// <exception cref="System.IO.IOException"></exception>
		private void Start_discard(Buffer buf, NSch.Cipher cipher, MAC mac, int packet_length
			, int discard)
		{
			MAC discard_mac = null;
			if (!cipher.IsCBC())
			{
				throw new JSchException("Packet corrupt");
			}
			if (packet_length != PACKET_MAX_SIZE && mac != null)
			{
				discard_mac = mac;
			}
			discard -= buf.index;
			while (discard > 0)
			{
				buf.Reset();
				int len = discard > buf.buffer.Length ? buf.buffer.Length : discard;
				io.GetByte(buf.buffer, 0, len);
				if (discard_mac != null)
				{
					discard_mac.Update(buf.buffer, 0, len);
				}
				discard -= len;
			}
			if (discard_mac != null)
			{
				discard_mac.DoFinal(buf.buffer, 0);
			}
			throw new JSchException("Packet corrupt");
		}
Beispiel #50
0
		/// <exception cref="System.Exception"></exception>
		private void UpdateKeys(KeyExchange kex)
		{
			byte[] K = kex.GetK();
			byte[] H = kex.GetH();
			HASH hash = kex.GetHash();
			//    String[] guess=kex.guess;
			if (session_id == null)
			{
				session_id = new byte[H.Length];
				System.Array.Copy(H, 0, session_id, 0, H.Length);
			}
			buf.Reset();
			buf.PutMPInt(K);
			buf.PutByte(H);
			buf.PutByte(unchecked((byte)unchecked((int)(0x41))));
			buf.PutByte(session_id);
			hash.Update(buf.buffer, 0, buf.index);
			IVc2s = hash.Digest();
			int j = buf.index - session_id.Length - 1;
			buf.buffer[j]++;
			hash.Update(buf.buffer, 0, buf.index);
			IVs2c = hash.Digest();
			buf.buffer[j]++;
			hash.Update(buf.buffer, 0, buf.index);
			Ec2s = hash.Digest();
			buf.buffer[j]++;
			hash.Update(buf.buffer, 0, buf.index);
			Es2c = hash.Digest();
			buf.buffer[j]++;
			hash.Update(buf.buffer, 0, buf.index);
			MACc2s = hash.Digest();
			buf.buffer[j]++;
			hash.Update(buf.buffer, 0, buf.index);
			MACs2c = hash.Digest();
			try
			{
				Type c;
				string method;
				method = guess[KeyExchange.PROPOSAL_ENC_ALGS_STOC];
				c = Sharpen.Runtime.GetType(GetConfig(method));
				s2ccipher = (NSch.Cipher)(System.Activator.CreateInstance(c));
				while (s2ccipher.GetBlockSize() > Es2c.Length)
				{
					buf.Reset();
					buf.PutMPInt(K);
					buf.PutByte(H);
					buf.PutByte(Es2c);
					hash.Update(buf.buffer, 0, buf.index);
					byte[] foo = hash.Digest();
					byte[] bar = new byte[Es2c.Length + foo.Length];
					System.Array.Copy(Es2c, 0, bar, 0, Es2c.Length);
					System.Array.Copy(foo, 0, bar, Es2c.Length, foo.Length);
					Es2c = bar;
				}
				s2ccipher.Init(NSch.Cipher.DECRYPT_MODE, Es2c, IVs2c);
				s2ccipher_size = s2ccipher.GetIVSize();
				method = guess[KeyExchange.PROPOSAL_MAC_ALGS_STOC];
				c = Sharpen.Runtime.GetType(GetConfig(method));
				s2cmac = (MAC)(System.Activator.CreateInstance(c));
				s2cmac.Init(MACs2c);
				//mac_buf=new byte[s2cmac.getBlockSize()];
				s2cmac_result1 = new byte[s2cmac.GetBlockSize()];
				s2cmac_result2 = new byte[s2cmac.GetBlockSize()];
				method = guess[KeyExchange.PROPOSAL_ENC_ALGS_CTOS];
				c = Sharpen.Runtime.GetType(GetConfig(method));
				c2scipher = (NSch.Cipher)(System.Activator.CreateInstance(c));
				while (c2scipher.GetBlockSize() > Ec2s.Length)
				{
					buf.Reset();
					buf.PutMPInt(K);
					buf.PutByte(H);
					buf.PutByte(Ec2s);
					hash.Update(buf.buffer, 0, buf.index);
					byte[] foo = hash.Digest();
					byte[] bar = new byte[Ec2s.Length + foo.Length];
					System.Array.Copy(Ec2s, 0, bar, 0, Ec2s.Length);
					System.Array.Copy(foo, 0, bar, Ec2s.Length, foo.Length);
					Ec2s = bar;
				}
				c2scipher.Init(NSch.Cipher.ENCRYPT_MODE, Ec2s, IVc2s);
				c2scipher_size = c2scipher.GetIVSize();
				method = guess[KeyExchange.PROPOSAL_MAC_ALGS_CTOS];
				c = Sharpen.Runtime.GetType(GetConfig(method));
				c2smac = (MAC)(System.Activator.CreateInstance(c));
				c2smac.Init(MACc2s);
				method = guess[KeyExchange.PROPOSAL_COMP_ALGS_CTOS];
				InitDeflater(method);
				method = guess[KeyExchange.PROPOSAL_COMP_ALGS_STOC];
				InitInflater(method);
			}
			catch (Exception e)
			{
				if (e is JSchException)
				{
					throw;
				}
				throw new JSchException(e.ToString(), e);
			}
		}
		private void updateKeys(KeyExchange kex) 
		{
			byte[] K=kex.getK();
			byte[] H=kex.getH();
			HASH hash=kex.getHash();

			String[] guess=kex._guess;

			if(session_id==null)
			{
				session_id=new byte[H.Length];
				Tamir.SharpSsh.java.System.arraycopy(H, 0, session_id, 0, H.Length);
			}

			/*
			  Initial IV client to server:     HASH (K || H || "A" || session_id)
			  Initial IV server to client:     HASH (K || H || "B" || session_id)
			  Encryption key client to server: HASH (K || H || "C" || session_id)
			  Encryption key server to client: HASH (K || H || "D" || session_id)
			  Integrity key client to server:  HASH (K || H || "E" || session_id)
			  Integrity key server to client:  HASH (K || H || "F" || session_id)
			*/

			buf.reset();
			buf.putMPInt(K);
			buf.putByte(H);
			buf.putByte((byte)0x41);
			buf.putByte(session_id);
			hash.update(buf.buffer, 0, buf.index);
			IVc2s=hash.digest();

			int j=buf.index-session_id.Length-1;

			buf.buffer[j]++;
			hash.update(buf.buffer, 0, buf.index);
			IVs2c=hash.digest();

			buf.buffer[j]++;
			hash.update(buf.buffer, 0, buf.index);
			Ec2s=hash.digest();

			buf.buffer[j]++;
			hash.update(buf.buffer, 0, buf.index);
			Es2c=hash.digest();

			buf.buffer[j]++;
			hash.update(buf.buffer, 0, buf.index);
			MACc2s=hash.digest();

			buf.buffer[j]++;
			hash.update(buf.buffer, 0, buf.index);
			MACs2c=hash.digest();

			try
			{
				Class c;

				c=Class.forName(getConfig(guess[KeyExchange.PROPOSAL_ENC_ALGS_STOC]));
				s2ccipher=(Cipher)(c.newInstance());
				while(s2ccipher.getBlockSize()>Es2c.Length)
				{
					buf.reset();
					buf.putMPInt(K);
					buf.putByte(H);
					buf.putByte(Es2c);
					hash.update(buf.buffer, 0, buf.index);
					byte[] foo=hash.digest();
					byte[] bar=new byte[Es2c.Length+foo.Length];
					Tamir.SharpSsh.java.System.arraycopy(Es2c, 0, bar, 0, Es2c.Length);
					Tamir.SharpSsh.java.System.arraycopy(foo, 0, bar, Es2c.Length, foo.Length);
					Es2c=bar;
				}
				s2ccipher.init(Cipher.DECRYPT_MODE, Es2c, IVs2c);
				cipher_size=s2ccipher.getIVSize();
				c=Class.forName(getConfig(guess[KeyExchange.PROPOSAL_MAC_ALGS_STOC]));
				s2cmac=(MAC)(c.newInstance());
				s2cmac.init(MACs2c);
				mac_buf=new byte[s2cmac.getBlockSize()];

				c=Class.forName(getConfig(guess[KeyExchange.PROPOSAL_ENC_ALGS_CTOS]));
				c2scipher=(Cipher)(c.newInstance());
				while(c2scipher.getBlockSize()>Ec2s.Length)
				{
					buf.reset();
					buf.putMPInt(K);
					buf.putByte(H);
					buf.putByte(Ec2s);
					hash.update(buf.buffer, 0, buf.index);
					byte[] foo=hash.digest();
					byte[] bar=new byte[Ec2s.Length+foo.Length];
					Tamir.SharpSsh.java.System.arraycopy(Ec2s, 0, bar, 0, Ec2s.Length);
					Tamir.SharpSsh.java.System.arraycopy(foo, 0, bar, Ec2s.Length, foo.Length);
					Ec2s=bar;
				}
				c2scipher.init(Cipher.ENCRYPT_MODE, Ec2s, IVc2s);

				c=Class.forName(getConfig(guess[KeyExchange.PROPOSAL_MAC_ALGS_CTOS]));
				c2smac=(MAC)(c.newInstance());
				c2smac.init(MACc2s);

				if(!guess[KeyExchange.PROPOSAL_COMP_ALGS_CTOS].equals("none"))
				{
					String foo=getConfig(guess[KeyExchange.PROPOSAL_COMP_ALGS_CTOS]);
					if(foo!=null)
					{
						try
						{
							c=Class.forName(foo);
							deflater=(Compression)(c.newInstance());
							int level=6;
							try{ level=Integer.parseInt(getConfig("compression_level"));}
							catch(Exception ee){ }
							deflater.init(Compression.DEFLATER, level);
						}
						catch(Exception ee)
						{
							System.Console.Error.WriteLine(foo+" isn't accessible.");
						}
					}
				}
				else
				{
					if(deflater!=null)
					{
						deflater=null;
					}
				}
				if(!guess[KeyExchange.PROPOSAL_COMP_ALGS_STOC].equals("none"))
				{
					String foo=getConfig(guess[KeyExchange.PROPOSAL_COMP_ALGS_STOC]);
					if(foo!=null)
					{
						try
						{
							c=Class.forName(foo);
							inflater=(Compression)(c.newInstance());
							inflater.init(Compression.INFLATER, 0);
						}
						catch(Exception ee)
						{
							System.Console.Error.WriteLine(foo+" isn't accessible.");
						}
					}
				}
				else
				{
					if(inflater!=null)
					{
						inflater=null;
					}
				}
			}
			catch(Exception e){ System.Console.Error.WriteLine("updatekeys: "+e); }
		}
Beispiel #52
0
		private MAC GetHMACSHA1()
		{
			lock (this)
			{
				if (hmacsha1 == null)
				{
					try
					{
						Type c = Sharpen.Runtime.GetType(JSch.GetConfig("hmac-sha1"));
						hmacsha1 = (MAC)(System.Activator.CreateInstance(c));
					}
					catch (Exception e)
					{
						System.Console.Error.WriteLine("hmacsha1: " + e);
					}
				}
				return hmacsha1;
			}
		}