Exemple #1
0
        public override byte[] EvaluateChallenge(byte[] challenge)
        {
            if (challenge == null || challenge.Length == 0)
            {
                throw new ArgumentNullException("challenge");
            }

            NameCallback     nameCB = new NameCallback(AuthorizationId);
            PasswordCallback pwdCB  = new PasswordCallback();

            ISaslCallback[] callbacks = { nameCB, pwdCB };
            Handler.Handle(callbacks);

            string username = nameCB.Text;
            string passwd   = pwdCB.Text.PadRight(MinPwdLen, '\0');

            byte[] secret = Encoding.UTF8.GetBytes(passwd);

            //using ( HMAC hmac = new HMACMD5(secret) )
            using (MD5HMAC hmac = new MD5HMAC(secret))
            {
                byte[] value   = hmac.ComputeHash(challenge);
                string encoded = ToHex(value);
                SetComplete();
                return(Encoding.UTF8.GetBytes(username + " " + encoded));
            }
        }
      public override byte[] EvaluateChallenge(byte[] challenge)
      {
        if ( challenge == null || challenge.Length == 0 )
            throw new ArgumentNullException("challenge");


        NameCallback nameCB = new NameCallback(AuthorizationId);
        PasswordCallback pwdCB = new PasswordCallback();
        ISaslCallback[] callbacks = { nameCB, pwdCB };
        Handler.Handle(callbacks);

        string username = nameCB.Text;
        
        //Encode the Hashed Password as Hex
        byte[] passwd = Encoding.UTF8.GetBytes(ToHex(pwdCB.HashedText));

        string s = System.Text.UTF8Encoding.UTF8.GetString(challenge);
        
        using ( HMAC hmac = new HMACMD5(passwd) )
         {
            byte[] value = hmac.ComputeHash(challenge);
            string encoded = ToHex(value);
            SetComplete();
            return Encoding.UTF8.GetBytes(username + " " + encoded);
         }
      }
Exemple #3
0
        public override byte[] EvaluateChallenge(byte[] challenge)
        {
            if (challenge == null || challenge.Length == 0)
            {
                throw new ArgumentNullException("challenge");
            }


            NameCallback     nameCB = new NameCallback(AuthorizationId);
            PasswordCallback pwdCB  = new PasswordCallback();

            ISaslCallback[] callbacks = { nameCB, pwdCB };
            Handler.Handle(callbacks);

            string username = nameCB.Text;

            //Encode the Hashed Password as Hex
            byte[] passwd = Encoding.UTF8.GetBytes(ToHex(pwdCB.HashedText));

            string s = System.Text.UTF8Encoding.UTF8.GetString(challenge);

            using (HMAC hmac = new HMACMD5(passwd))
            {
                byte[] value   = hmac.ComputeHash(challenge);
                string encoded = ToHex(value);
                SetComplete();
                return(Encoding.UTF8.GetBytes(username + " " + encoded));
            }
        }
      public override byte[] EvaluateChallenge(byte[] challenge)
      {
         if ( challenge == null || challenge.Length == 0 )
            throw new ArgumentNullException("challenge");

         NameCallback nameCB = new NameCallback(AuthorizationId);
         PasswordCallback pwdCB = new PasswordCallback();
         ISaslCallback[] callbacks = { nameCB, pwdCB };
         Handler.Handle(callbacks);

         string username = nameCB.Text;
         string passwd = pwdCB.Text.PadRight(MinPwdLen, '\0');

         byte[] secret = Encoding.UTF8.GetBytes(passwd);

         //using ( HMAC hmac = new HMACMD5(secret) )
         using ( MD5HMAC hmac = new MD5HMAC(secret) )
         {
            byte[] value = hmac.ComputeHash(challenge);
            string encoded = ToHex(value);
            SetComplete();
            return Encoding.UTF8.GetBytes(username + " " + encoded);
         }

      }
Exemple #5
0
 /// <exception cref="Javax.Security.Sasl.SaslException"/>
 public virtual byte[] EvaluateResponse(byte[] response)
 {
     if (completed)
     {
         throw new InvalidOperationException("PLAIN authentication has completed");
     }
     if (response == null)
     {
         throw new ArgumentException("Received null response");
     }
     try
     {
         string payload;
         try
         {
             payload = Runtime.GetStringForBytes(response, "UTF-8");
         }
         catch (Exception e)
         {
             throw new ArgumentException("Received corrupt response", e);
         }
         // [ authz, authn, password ]
         string[] parts = payload.Split("\u0000", 3);
         if (parts.Length != 3)
         {
             throw new ArgumentException("Received corrupt response");
         }
         if (parts[0].IsEmpty())
         {
             // authz = authn
             parts[0] = parts[1];
         }
         NameCallback nc = new NameCallback("SASL PLAIN");
         nc.SetName(parts[1]);
         PasswordCallback pc = new PasswordCallback("SASL PLAIN", false);
         pc.SetPassword(parts[2].ToCharArray());
         AuthorizeCallback ac = new AuthorizeCallback(parts[1], parts[0]);
         cbh.Handle(new Javax.Security.Auth.Callback.Callback[] { nc, pc, ac });
         if (ac.IsAuthorized())
         {
             authz = ac.GetAuthorizedID();
         }
     }
     catch (Exception e)
     {
         throw new SaslException("PLAIN auth failed: " + e.Message);
     }
     finally
     {
         completed = true;
     }
     return(null);
 }
Exemple #6
0
            /// <exception cref="System.IO.IOException"/>
            /// <exception cref="Javax.Security.Auth.Callback.UnsupportedCallbackException"/>
            public void Handle(Javax.Security.Auth.Callback.Callback[] callbacks)
            {
                NameCallback     nc = null;
                PasswordCallback pc = null;
                RealmCallback    rc = null;

                foreach (Javax.Security.Auth.Callback.Callback callback in callbacks)
                {
                    if (callback is RealmChoiceCallback)
                    {
                        continue;
                    }
                    else
                    {
                        if (callback is NameCallback)
                        {
                            nc = (NameCallback)callback;
                        }
                        else
                        {
                            if (callback is PasswordCallback)
                            {
                                pc = (PasswordCallback)callback;
                            }
                            else
                            {
                                if (callback is RealmCallback)
                                {
                                    rc = (RealmCallback)callback;
                                }
                                else
                                {
                                    throw new UnsupportedCallbackException(callback, "Unrecognized SASL client callback"
                                                                           );
                                }
                            }
                        }
                    }
                }
                if (nc != null)
                {
                    nc.SetName(userName);
                }
                if (pc != null)
                {
                    pc.SetPassword(password);
                }
                if (rc != null)
                {
                    rc.SetText(rc.GetDefaultText());
                }
            }
            /// <exception cref="System.IO.IOException"/>
            /// <exception cref="Javax.Security.Auth.Callback.UnsupportedCallbackException"/>
            public void Handle(Javax.Security.Auth.Callback.Callback[] callbacks)
            {
                NameCallback      nc = null;
                PasswordCallback  pc = null;
                AuthorizeCallback ac = null;

                foreach (Javax.Security.Auth.Callback.Callback callback in callbacks)
                {
                    if (callback is AuthorizeCallback)
                    {
                        ac = (AuthorizeCallback)callback;
                    }
                    else
                    {
                        if (callback is PasswordCallback)
                        {
                            pc = (PasswordCallback)callback;
                        }
                        else
                        {
                            if (callback is NameCallback)
                            {
                                nc = (NameCallback)callback;
                            }
                            else
                            {
                                if (callback is RealmCallback)
                                {
                                    continue;
                                }
                                else
                                {
                                    // realm is ignored
                                    throw new UnsupportedCallbackException(callback, "Unrecognized SASL DIGEST-MD5 Callback: "
                                                                           + callback);
                                }
                            }
                        }
                    }
                }
                if (pc != null)
                {
                    pc.SetPassword(passwordFunction.Apply(nc.GetDefaultName()));
                }
                if (ac != null)
                {
                    ac.SetAuthorized(true);
                    ac.SetAuthorizedID(ac.GetAuthorizationID());
                }
            }
Exemple #8
0
        /// <summary>
        /// Loads the keystore using the given
        /// {@code KeyStore.LoadStoreParameter}.
        ///
        /// <para> Note that if this KeyStore has already been loaded, it is
        /// reinitialized and loaded again from the given parameter.
        ///
        /// </para>
        /// </summary>
        /// <param name="param"> the {@code KeyStore.LoadStoreParameter}
        ///          that specifies how to load the keystore,
        ///          which may be {@code null}
        /// </param>
        /// <exception cref="IllegalArgumentException"> if the given
        ///          {@code KeyStore.LoadStoreParameter}
        ///          input is not recognized </exception>
        /// <exception cref="IOException"> if there is an I/O or format problem with the
        ///          keystore data. If the error is due to an incorrect
        ///         {@code ProtectionParameter} (e.g. wrong password)
        ///         the <seealso cref="Throwable#getCause cause"/> of the
        ///         {@code IOException} should be an
        ///         {@code UnrecoverableKeyException} </exception>
        /// <exception cref="NoSuchAlgorithmException"> if the algorithm used to check
        ///          the integrity of the keystore cannot be found </exception>
        /// <exception cref="CertificateException"> if any of the certificates in the
        ///          keystore could not be loaded
        ///
        /// @since 1.5 </exception>
//JAVA TO C# CONVERTER WARNING: Method 'throws' clauses are not available in .NET:
//ORIGINAL LINE: public void engineLoad(KeyStore.LoadStoreParameter param) throws IOException, NoSuchAlgorithmException, java.security.cert.CertificateException
        public virtual void EngineLoad(KeyStore.LoadStoreParameter param)
        {
            if (param == null)
            {
                EngineLoad((InputStream)null, (char[])null);
                return;
            }

            if (param is KeyStore.SimpleLoadStoreParameter)
            {
                ProtectionParameter protection = param.ProtectionParameter;
                char[] password;
                if (protection is PasswordProtection)
                {
                    password = ((PasswordProtection)protection).Password;
                }
                else if (protection is CallbackHandlerProtection)
                {
                    CallbackHandler  handler  = ((CallbackHandlerProtection)protection).CallbackHandler;
                    PasswordCallback callback = new PasswordCallback("Password: "******"Could not obtain password", e);
                    }
                    password = callback.Password;
                    callback.clearPassword();
                    if (password == null)
                    {
                        throw new NoSuchAlgorithmException("No password provided");
                    }
                }
                else
                {
                    throw new NoSuchAlgorithmException("ProtectionParameter must" + " be PasswordProtection or CallbackHandlerProtection");
                }
                EngineLoad(null, password);
                return;
            }

            throw new UnsupportedOperationException();
        }
        //
        // Private Methods
        //

        /// <summary>
        /// Process the first challenge from the server
        /// and calculate a response
        /// </summary>
        /// <param name="challenge">The server issued challenge</param>
        /// <returns>Client response</returns>
        private byte[] OnInitialChallenge(byte[] challenge)
        {
            DigestChallenge dch =
                DigestChallenge.Parse(_encoding.GetString(challenge));

            // validate input challenge
            if (dch.Nonce == null || dch.Nonce.Length == 0)
            {
                throw new SaslException("Nonce value missing in server challenge");
            }
            if (dch.Algorithm != "md5-sess")
            {
                throw new SaslException("Invalid or missing algorithm value in server challenge");
            }


            NameCallback     nameCB  = new NameCallback(AuthorizationId);
            PasswordCallback pwdCB   = new PasswordCallback();
            RealmCallback    realmCB = new RealmCallback(dch.Realm);

            ISaslCallback[] callbacks = { nameCB, pwdCB, realmCB };
            Handler.Handle(callbacks);

            DigestResponse response = new DigestResponse();

            response.Username   = nameCB.Text;
            response.Realm      = realmCB.Text;
            response.Nonce      = dch.Nonce;
            response.Cnonce     = Cnonce;
            response.NonceCount = 1;
            response.Qop        = DigestQop.Auth; // only auth supported for now
            response.DigestUri  = Protocol.ToLower() + "/" + ServerName;
            response.MaxBuffer  = dch.MaxBuffer;
            response.Charset    = dch.Charset;
            response.Cipher     = null; // not supported for now
            response.Authzid    = AuthorizationId;
            response.AuthParam  = dch.AuthParam;

            response.Response = CalculateResponse(
                nameCB.Text, realmCB.Text, pwdCB.Text,
                dch.Nonce, response.NonceCount, response.Qop, response.DigestUri
                );

            return(_encoding.GetBytes(response.ToString()));
        }
      public override byte[] EvaluateChallenge(byte[] challenge)
      {
         // ignore challenge

         NameCallback nameCB = new NameCallback();
         PasswordCallback pwdCB = new PasswordCallback();
         ISaslCallback[] callbacks = { nameCB, pwdCB };
         Handler.Handle(callbacks);

         string username = nameCB.Text;
         string authid = AuthorizationId;
         string passwd = pwdCB.Text;

         string response = 
            string.Format("{0}\0{1}\0{2}", authid, username, passwd);
         SetComplete();
         return Encoding.UTF8.GetBytes(response);
      }
Exemple #11
0
        public override byte[] EvaluateChallenge(byte[] challenge)
        {
            // ignore challenge

            NameCallback     nameCB = new NameCallback();
            PasswordCallback pwdCB  = new PasswordCallback();

            ISaslCallback[] callbacks = { nameCB, pwdCB };
            Handler.Handle(callbacks);

            string username = nameCB.Text;
            string authid   = AuthorizationId;
            string passwd   = pwdCB.Text;

            string response =
                string.Format("{0}\0{1}\0{2}", authid, username, passwd);

            SetComplete();
            return(Encoding.UTF8.GetBytes(response));
        }
 public void handle(Callback [] callbacks)
 {
     for (int i = 0; i < callbacks.Length; i++)
     {
         if (callbacks [i] is NameCallback)
         {
             NameCallback nc = (NameCallback)callbacks [i];
             nc.setName(_username);
         }
         else if (callbacks [i] is PasswordCallback)
         {
             PasswordCallback pc = (PasswordCallback)callbacks [i];
             pc.setPassword(_password.ToCharArray());
         }
         else
         {
             throw new UnsupportedCallbackException(callbacks [i], "Unrecognized Callback");
         }
     }
 }
Exemple #13
0
        /// <summary>
        /// Calls PEM_read_bio_PrivateKey()
        /// </summary>
        /// <param name="bio"></param>
        /// <param name="passwd"></param>
        /// <returns></returns>
        public static CryptoKey FromPrivateKey(BIO bio, string passwd)
        {
            PasswordCallback callback = new PasswordCallback(passwd);

            return(FromPrivateKey(bio, callback.OnPassword, null));
        }
Exemple #14
0
 public override void setPasswordCallback(PasswordCallback callback)
 {
     _engine.setPasswordCallback(callback);
 }
Exemple #15
0
 internal void setPasswordCallback(PasswordCallback callback)
 {
     _passwordCallback = callback;
 }
Exemple #16
0
        internal void initialize()
        {
            if(_initialized)
            {
                return;
            }

            const string prefix = "IceSSL.";
            Ice.Properties properties = communicator().getProperties();

            //
            // Check for a default directory. We look in this directory for
            // files mentioned in the configuration.
            //
            _defaultDir = properties.getProperty(prefix + "DefaultDir");

            string certStoreLocation = properties.getPropertyWithDefault(prefix + "CertStoreLocation", "CurrentUser");
            StoreLocation storeLocation;
            if(certStoreLocation == "CurrentUser")
            {
                storeLocation = StoreLocation.CurrentUser;
            }
            else if(certStoreLocation == "LocalMachine")
            {
                storeLocation = StoreLocation.LocalMachine;
            }
            else
            {
                _logger.warning("Invalid IceSSL.CertStoreLocation value `" + certStoreLocation +
                                "' adjusted to `CurrentUser'");
                storeLocation = StoreLocation.CurrentUser;
            }
            _useMachineContext = certStoreLocation == "LocalMachine";

            #if !UNITY
            X509KeyStorageFlags keyStorageFlags;
            if(_useMachineContext)
            {
                keyStorageFlags = X509KeyStorageFlags.MachineKeySet;
            }
            else
            {
                keyStorageFlags = X509KeyStorageFlags.UserKeySet;
            }

            string keySet = properties.getProperty(prefix + "KeySet"); // Deprecated property
            if(keySet.Length > 0)
            {
                if(keySet.Equals("DefaultKeySet"))
                {
                    keyStorageFlags = X509KeyStorageFlags.DefaultKeySet;
                }
                else if(keySet.Equals("UserKeySet"))
                {
                    keyStorageFlags = X509KeyStorageFlags.UserKeySet;
                }
                else if(keySet.Equals("MachineKeySet"))
                {
                    keyStorageFlags = X509KeyStorageFlags.MachineKeySet;
                }
                else
                {
                    _logger.warning("Invalid IceSSL.KeySet value `" + keySet + "' adjusted to `DefaultKeySet'");
                    keyStorageFlags = X509KeyStorageFlags.DefaultKeySet;
                }
            }

            if(properties.getPropertyAsIntWithDefault(prefix + "PersistKeySet", 0) > 0) // Deprecated property
            {
                keyStorageFlags |= X509KeyStorageFlags.PersistKeySet;
            }

            //
            // Process IceSSL.ImportCert.* properties.
            //
            Dictionary<string, string> certs = properties.getPropertiesForPrefix(prefix + "ImportCert.");
            foreach(KeyValuePair<string, string> entry in certs)
            {
                string name = entry.Key;
                string val = entry.Value;
                if(val.Length > 0)
                {
                    importCertificate(name, val, keyStorageFlags);
                }
            }
            #endif

            //
            // Protocols selects which protocols to enable, by default we only enable TLS1.0
            // TLS1.1 and TLS1.2 to avoid security issues with SSLv3
            //
            _protocols = parseProtocols(
                properties.getPropertyAsListWithDefault(prefix + "Protocols",
            #if UNITY
                                                        new string[]{"TLS1_0"}));
            #else
                                                        _tls12Support ? new string[]{"TLS1_0", "TLS1_1", "TLS1_2"} :
                                                                        new string[]{"TLS1_0", "TLS1_1"}));
            #endif
            //
            // CheckCertName determines whether we compare the name in a peer's
            // certificate against its hostname.
            //
            _checkCertName = properties.getPropertyAsIntWithDefault(prefix + "CheckCertName", 0) > 0;

            //
            // VerifyDepthMax establishes the maximum length of a peer's certificate
            // chain, including the peer's certificate. A value of 0 means there is
            // no maximum.
            //
            _verifyDepthMax = properties.getPropertyAsIntWithDefault(prefix + "VerifyDepthMax", 3);

            //
            // CheckCRL determines whether the certificate revocation list is checked, and how strictly.
            //
            _checkCRL = properties.getPropertyAsIntWithDefault(prefix + "CheckCRL", 0);

            #if !UNITY
            //
            // Check for a certificate verifier.
            //
            string certVerifierClass = properties.getProperty(prefix + "CertVerifier");
            if(certVerifierClass.Length > 0)
            {
                if(_verifier != null)
                {
                    Ice.PluginInitializationException e = new Ice.PluginInitializationException();
                    e.reason = "IceSSL: certificate verifier already installed";
                    throw e;
                }

                Type cls = _facade.findType(certVerifierClass);
                if(cls == null)
                {
                    Ice.PluginInitializationException e = new Ice.PluginInitializationException();
                    e.reason = "IceSSL: unable to load certificate verifier class " + certVerifierClass;
                    throw e;
                }

                try
                {
                    _verifier = (CertificateVerifier)IceInternal.AssemblyUtil.createInstance(cls);
                }
                catch(Exception ex)
                {
                    Ice.PluginInitializationException e = new Ice.PluginInitializationException(ex);
                    e.reason = "IceSSL: unable to instantiate certificate verifier class " + certVerifierClass;
                    throw e;
                }

                if(_verifier == null)
                {
                    Ice.PluginInitializationException e = new Ice.PluginInitializationException();
                    e.reason = "IceSSL: unable to instantiate certificate verifier class " + certVerifierClass;
                    throw e;
                }
            }

            //
            // Check for a password callback.
            //
            string passwordCallbackClass = properties.getProperty(prefix + "PasswordCallback");
            if(passwordCallbackClass.Length > 0)
            {
                if(_passwordCallback != null)
                {
                    Ice.PluginInitializationException e = new Ice.PluginInitializationException();
                    e.reason = "IceSSL: password callback already installed";
                    throw e;
                }

                Type cls = _facade.findType(passwordCallbackClass);
                if(cls == null)
                {
                    Ice.PluginInitializationException e = new Ice.PluginInitializationException();
                    e.reason = "IceSSL: unable to load password callback class " + passwordCallbackClass;
                    throw e;
                }

                try
                {
                    _passwordCallback = (PasswordCallback)IceInternal.AssemblyUtil.createInstance(cls);
                }
                catch(Exception ex)
                {
                    Ice.PluginInitializationException e = new Ice.PluginInitializationException(ex);
                    e.reason = "IceSSL: unable to load password callback class " + passwordCallbackClass;
                    throw e;
                }

                if(_passwordCallback == null)
                {
                    Ice.PluginInitializationException e = new Ice.PluginInitializationException();
                    e.reason = "IceSSL: unable to load password callback class " + passwordCallbackClass;
                    throw e;
                }
            }

            //
            // If the user hasn't supplied a certificate collection, we need to examine
            // the property settings.
            //
            if(_certs == null)
            {
                //
                // If IceSSL.CertFile is defined, load a certificate from a file and
                // add it to the collection.
                //
                // TODO: tracing?
                _certs = new X509Certificate2Collection();
                string certFile = properties.getProperty(prefix + "CertFile");
                string passwordStr = properties.getProperty(prefix + "Password");
                string findCert = properties.getProperty(prefix + "FindCert");
                const string findPrefix = prefix + "FindCert.";
                Dictionary<string, string> findCertProps = properties.getPropertiesForPrefix(findPrefix);

                if(certFile.Length > 0)
                {
                    if(!checkPath(ref certFile))
                    {
                        Ice.PluginInitializationException e = new Ice.PluginInitializationException();
                        e.reason = "IceSSL: certificate file not found: " + certFile;
                        throw e;
                    }

                    SecureString password = null;
                    if(passwordStr.Length > 0)
                    {
                        password = createSecureString(passwordStr);
                    }
                    else if(_passwordCallback != null)
                    {
                        password = _passwordCallback.getPassword(certFile);
                    }

                    try
                    {
                        X509Certificate2 cert;
                        X509KeyStorageFlags importFlags;
                        if(_useMachineContext)
                        {
                            importFlags = X509KeyStorageFlags.MachineKeySet;
                        }
                        else
                        {
                            importFlags = X509KeyStorageFlags.UserKeySet;
                        }

                        if(password != null)
                        {
                            cert = new X509Certificate2(certFile, password, importFlags);
                        }
                        else
                        {
                            cert = new X509Certificate2(certFile, "", importFlags);
                        }
                        _certs.Add(cert);
                    }
                    catch(CryptographicException ex)
                    {
                        Ice.PluginInitializationException e = new Ice.PluginInitializationException(ex);
                        e.reason = "IceSSL: error while attempting to load certificate from " + certFile;
                        throw e;
                    }
                }
                else if(findCert.Length > 0)
                {
                    string certStore = properties.getPropertyWithDefault("IceSSL.CertStore", "My");
                    _certs.AddRange(findCertificates("IceSSL.FindCert", storeLocation, certStore, findCert));
                    if(_certs.Count == 0)
                    {
                        throw new Ice.PluginInitializationException("IceSSL: no certificates found");
                    }
                }
                else if(findCertProps.Count > 0)
                {
                    //
                    // If IceSSL.FindCert.* properties are defined, add the selected certificates
                    // to the collection.
                    //
                    foreach(KeyValuePair<string, string> entry in findCertProps)
                    {
                        string name = entry.Key;
                        string val = entry.Value;
                        if(val.Length > 0)
                        {
                            string storeSpec = name.Substring(findPrefix.Length);
                            StoreLocation storeLoc = 0;
                            StoreName storeName = 0;
                            string sname = null;
                            parseStore(name, storeSpec, ref storeLoc, ref storeName, ref sname);
                            if(sname == null)
                            {
                                sname = storeName.ToString();
                            }
                            X509Certificate2Collection coll = findCertificates(name, storeLoc, sname, val);
                            _certs.AddRange(coll);
                        }
                    }
                    if(_certs.Count == 0)
                    {
                        Ice.PluginInitializationException e = new Ice.PluginInitializationException();
                        e.reason = "IceSSL: no certificates found";
                        throw e;
                    }
                }
            }

            if(_caCerts == null)
            {
                string certAuthFile = properties.getProperty(prefix + "CAs");
                if(certAuthFile.Length == 0)
                {
                    certAuthFile = properties.getProperty(prefix + "CertAuthFile");
                }
                if(certAuthFile.Length > 0 || properties.getPropertyAsInt(prefix + "UsePlatformCAs") <= 0)
                {
                    _caCerts = new X509Certificate2Collection();
                }
                if(certAuthFile.Length > 0)
                {
                    if(!checkPath(ref certAuthFile))
                    {
                        Ice.PluginInitializationException e = new Ice.PluginInitializationException();
                        e.reason = "IceSSL: CA certificate file not found: " + certAuthFile;
                        throw e;
                    }

                    try
                    {
                        using(System.IO.FileStream fs = System.IO.File.OpenRead(certAuthFile))
                        {
                            byte[] data = new byte[fs.Length];
                            fs.Read(data, 0, data.Length);

                            string strbuf = "";
                            try
                            {
                                strbuf = System.Text.Encoding.UTF8.GetString(data);
                            }
                            catch(Exception)
                            {
                                // Ignore
                            }

                            if(strbuf.Length == data.Length)
                            {
                                int size, startpos, endpos = 0;
                                bool first = true;
                                while(true)
                                {
                                    startpos = strbuf.IndexOf("-----BEGIN CERTIFICATE-----", endpos);
                                    if(startpos != -1)
                                    {
                                        endpos = strbuf.IndexOf("-----END CERTIFICATE-----", startpos);
                                        size = endpos - startpos + "-----END CERTIFICATE-----".Length;
                                    }
                                    else if(first)
                                    {
                                        startpos = 0;
                                        endpos = strbuf.Length;
                                        size = strbuf.Length;
                                    }
                                    else
                                    {
                                        break;
                                    }

                                    byte[] cert = new byte[size];
                                    System.Buffer.BlockCopy(data, startpos, cert, 0, size);
                                    _caCerts.Import(cert);
                                    first = false;
                                }
                            }
                            else
                            {
                                _caCerts.Import(data);
                            }
                        }
                    }
                    catch(Exception ex)
                    {
                        Ice.PluginInitializationException e = new Ice.PluginInitializationException(ex);
                        e.reason = "IceSSL: error while attempting to load CA certificate from " + certAuthFile;
                        throw e;
                    }
                }
            }
            #endif

            _initialized = true;
        }
Exemple #17
0
 /// <summary>
 /// Establish the password callback object. This must be
 /// done before the plug-in is initialized.
 /// </summary>
 /// <param name="callback">The password callback.</param>
 public abstract void setPasswordCallback(PasswordCallback callback);
Exemple #18
0
 public override void setPasswordCallback(PasswordCallback callback)
 {
     instance_.setPasswordCallback(callback);
 }
Exemple #19
0
            /// <exception cref="Javax.Security.Auth.Callback.UnsupportedCallbackException"/>
            public virtual void Handle(Javax.Security.Auth.Callback.Callback[] callbacks)
            {
                NameCallback     nc = null;
                PasswordCallback pc = null;
                RealmCallback    rc = null;

                foreach (Javax.Security.Auth.Callback.Callback callback in callbacks)
                {
                    if (callback is RealmChoiceCallback)
                    {
                        continue;
                    }
                    else
                    {
                        if (callback is NameCallback)
                        {
                            nc = (NameCallback)callback;
                        }
                        else
                        {
                            if (callback is PasswordCallback)
                            {
                                pc = (PasswordCallback)callback;
                            }
                            else
                            {
                                if (callback is RealmCallback)
                                {
                                    rc = (RealmCallback)callback;
                                }
                                else
                                {
                                    throw new UnsupportedCallbackException(callback, "Unrecognized SASL client callback"
                                                                           );
                                }
                            }
                        }
                    }
                }
                if (nc != null)
                {
                    if (Log.IsDebugEnabled())
                    {
                        Log.Debug("SASL client callback: setting username: "******"SASL client callback: setting userPassword");
                    }
                    pc.SetPassword(userPassword);
                }
                if (rc != null)
                {
                    if (Log.IsDebugEnabled())
                    {
                        Log.Debug("SASL client callback: setting realm: " + rc.GetDefaultText());
                    }
                    rc.SetText(rc.GetDefaultText());
                }
            }
Exemple #20
0
        internal void initialize()
        {
            if(_initialized)
            {
                return;
            }

            const string prefix = "IceSSL.";
            Ice.Properties properties = communicator().getProperties();

            //
            // Check for a default directory. We look in this directory for
            // files mentioned in the configuration.
            //
            _defaultDir = properties.getProperty(prefix + "DefaultDir");

            //
            // Process IceSSL.ImportCert.* properties.
            //
            Dictionary<string, string> certs = properties.getPropertiesForPrefix(prefix + "ImportCert.");
            foreach(KeyValuePair<string, string> entry in certs)
            {
                string name = entry.Key;
                string val = entry.Value;
                if(val.Length > 0)
                {
                    importCertificate(name, val);
                }
            }

            //
            // Select protocols.
            //
            _protocols = parseProtocols(prefix + "Protocols");

            //
            // CheckCertName determines whether we compare the name in a peer's
            // certificate against its hostname.
            //
            _checkCertName = properties.getPropertyAsIntWithDefault(prefix + "CheckCertName", 0) > 0;

            //
            // VerifyDepthMax establishes the maximum length of a peer's certificate
            // chain, including the peer's certificate. A value of 0 means there is
            // no maximum.
            //
            _verifyDepthMax = properties.getPropertyAsIntWithDefault(prefix + "VerifyDepthMax", 2);

            //
            // CheckCRL determines whether the certificate revocation list is checked, and how strictly.
            //
            _checkCRL = properties.getPropertyAsIntWithDefault(prefix + "CheckCRL", 0);

            //
            // Check for a certificate verifier.
            //
            string certVerifierClass = properties.getProperty(prefix + "CertVerifier");
            if(certVerifierClass.Length > 0)
            {
                if(_verifier != null)
                {
                    Ice.PluginInitializationException e = new Ice.PluginInitializationException();
                    e.reason = "IceSSL: certificate verifier already installed";
                    throw e;
                }

                Type cls = _facade.findType(certVerifierClass);
                if(cls == null)
                {
                    Ice.PluginInitializationException e = new Ice.PluginInitializationException();
                    e.reason = "IceSSL: unable to load certificate verifier class " + certVerifierClass;
                    throw e;
                }

                try
                {
                    _verifier = (CertificateVerifier)IceInternal.AssemblyUtil.createInstance(cls);
                }
                catch(Exception ex)
                {
                    Ice.PluginInitializationException e = new Ice.PluginInitializationException(ex);
                    e.reason = "IceSSL: unable to instantiate certificate verifier class " + certVerifierClass;
                    throw e;
                }

                if(_verifier == null)
                {
                    Ice.PluginInitializationException e = new Ice.PluginInitializationException();
                    e.reason = "IceSSL: unable to instantiate certificate verifier class " + certVerifierClass;
                    throw e;
                }
            }

            //
            // Check for a password callback.
            //
            string passwordCallbackClass = properties.getProperty(prefix + "PasswordCallback");
            if(passwordCallbackClass.Length > 0)
            {
                if(_passwordCallback != null)
                {
                    Ice.PluginInitializationException e = new Ice.PluginInitializationException();
                    e.reason = "IceSSL: password callback already installed";
                    throw e;
                }

                Type cls = _facade.findType(passwordCallbackClass);
                if(cls == null)
                {
                    Ice.PluginInitializationException e = new Ice.PluginInitializationException();
                    e.reason = "IceSSL: unable to load password callback class " + passwordCallbackClass;
                    throw e;
                }

                try
                {
                    _passwordCallback = (PasswordCallback)IceInternal.AssemblyUtil.createInstance(cls);
                }
                catch(Exception ex)
                {
                    Ice.PluginInitializationException e = new Ice.PluginInitializationException(ex);
                    e.reason = "IceSSL: unable to load password callback class " + passwordCallbackClass;
                    throw e;
                }

                if(_passwordCallback == null)
                {
                    Ice.PluginInitializationException e = new Ice.PluginInitializationException();
                    e.reason = "IceSSL: unable to load password callback class " + passwordCallbackClass;
                    throw e;
                }
            }

            //
            // If the user hasn't supplied a certificate collection, we need to examine
            // the property settings.
            //
            if(_certs == null)
            {
                //
                // If IceSSL.CertFile is defined, load a certificate from a file and
                // add it to the collection.
                //
                // TODO: tracing?
                _certs = new X509Certificate2Collection();
                string certFile = properties.getProperty(prefix + "CertFile");
                string passwordStr = properties.getProperty(prefix + "Password");
                if(certFile.Length > 0)
                {
                    if(!checkPath(ref certFile))
                    {
                        Ice.PluginInitializationException e = new Ice.PluginInitializationException();
                        e.reason = "IceSSL: certificate file not found: " + certFile;
                        throw e;
                    }

                    SecureString password = null;
                    if(passwordStr.Length > 0)
                    {
                        password = createSecureString(passwordStr);
                    }
                    else if(_passwordCallback != null)
                    {
                        password = _passwordCallback.getPassword(certFile);
                    }

                    try
                    {
                        X509Certificate2 cert;
                        if(password != null)
                        {
                            cert = new X509Certificate2(certFile, password);
                        }
                        else
                        {
                            cert = new X509Certificate2(certFile);
                        }
                        _certs.Add(cert);
                    }
                    catch(CryptographicException ex)
                    {
                        Ice.PluginInitializationException e = new Ice.PluginInitializationException(ex);
                        e.reason = "IceSSL: error while attempting to load certificate from " + certFile;
                        throw e;
                    }
                }

                //
                // If IceSSL.FindCert.* properties are defined, add the selected certificates
                // to the collection.
                //
                // TODO: tracing?
                const string findPrefix = prefix + "FindCert.";
                Dictionary<string, string> certProps = properties.getPropertiesForPrefix(findPrefix);
                if(certProps.Count > 0)
                {
                    foreach(KeyValuePair<string, string> entry in certProps)
                    {
                        string name = entry.Key;
                        string val = entry.Value;
                        if(val.Length > 0)
                        {
                            string storeSpec = name.Substring(findPrefix.Length);
                            X509Certificate2Collection coll = findCertificates(name, storeSpec, val);
                            _certs.AddRange(coll);
                        }
                    }
                    if(_certs.Count == 0)
                    {
                        Ice.PluginInitializationException e = new Ice.PluginInitializationException();
                        e.reason = "IceSSL: no certificates found";
                        throw e;
                    }
                }
            }

            _initialized = true;
        }
Exemple #21
0
 public override void setPasswordCallback(PasswordCallback callback)
 {
     instance_.setPasswordCallback(callback);
 }
Exemple #22
0
            /// <exception cref="Org.Apache.Hadoop.Security.Token.SecretManager.InvalidToken"/>
            /// <exception cref="Javax.Security.Auth.Callback.UnsupportedCallbackException"/>
            /// <exception cref="Org.Apache.Hadoop.Ipc.StandbyException"/>
            /// <exception cref="Org.Apache.Hadoop.Ipc.RetriableException"/>
            /// <exception cref="System.IO.IOException"/>
            public virtual void Handle(Javax.Security.Auth.Callback.Callback[] callbacks)
            {
                NameCallback      nc = null;
                PasswordCallback  pc = null;
                AuthorizeCallback ac = null;

                foreach (Javax.Security.Auth.Callback.Callback callback in callbacks)
                {
                    if (callback is AuthorizeCallback)
                    {
                        ac = (AuthorizeCallback)callback;
                    }
                    else
                    {
                        if (callback is NameCallback)
                        {
                            nc = (NameCallback)callback;
                        }
                        else
                        {
                            if (callback is PasswordCallback)
                            {
                                pc = (PasswordCallback)callback;
                            }
                            else
                            {
                                if (callback is RealmCallback)
                                {
                                    continue;
                                }
                                else
                                {
                                    // realm is ignored
                                    throw new UnsupportedCallbackException(callback, "Unrecognized SASL DIGEST-MD5 Callback"
                                                                           );
                                }
                            }
                        }
                    }
                }
                if (pc != null)
                {
                    TokenIdentifier tokenIdentifier = GetIdentifier(nc.GetDefaultName(), secretManager
                                                                    );
                    char[] password           = GetPassword(tokenIdentifier);
                    UserGroupInformation user = null;
                    user = tokenIdentifier.GetUser();
                    // may throw exception
                    connection.attemptingUser = user;
                    if (Log.IsDebugEnabled())
                    {
                        Log.Debug("SASL server DIGEST-MD5 callback: setting password " + "for client: " +
                                  tokenIdentifier.GetUser());
                    }
                    pc.SetPassword(password);
                }
                if (ac != null)
                {
                    string authid  = ac.GetAuthenticationID();
                    string authzid = ac.GetAuthorizationID();
                    if (authid.Equals(authzid))
                    {
                        ac.SetAuthorized(true);
                    }
                    else
                    {
                        ac.SetAuthorized(false);
                    }
                    if (ac.IsAuthorized())
                    {
                        if (Log.IsDebugEnabled())
                        {
                            string username = GetIdentifier(authzid, secretManager).GetUser().GetUserName();
                            Log.Debug("SASL server DIGEST-MD5 callback: setting " + "canonicalized client ID: "
                                      + username);
                        }
                        ac.SetAuthorizedID(authzid);
                    }
                }
            }
Exemple #23
0
        /// <summary>
        /// Calls PEM_read_bio_PUBKEY()
        /// </summary>
        /// <param name="bio"></param>
        /// <param name="password"></param>
        /// <returns></returns>
        public static CryptoKey FromPublicKey(BIO bio, string password)
        {
            var callback = new PasswordCallback(password);

            return(FromPublicKey(bio, callback.OnPassword, null));
        }
Exemple #24
0
        /// <summary>
        /// Calls PEM_write_bio_PKCS8PrivateKey
        /// </summary>
        /// <param name="bp"></param>
        /// <param name="cipher"></param>
        /// <param name="password"></param>
        public void WritePrivateKey(BIO bp, Cipher cipher, string password)
        {
            PasswordCallback callback = new PasswordCallback(password);

            WritePrivateKey(bp, cipher, callback.OnPassword, null);
        }
Exemple #25
0
 /// <summary>
 /// Establish the password callback object. This must be
 /// done before the plug-in is initialized.
 /// </summary>
 /// <param name="callback">The password callback.</param>
 abstract public void setPasswordCallback(PasswordCallback callback);
      //
      // Private Methods
      //

      /// <summary>
      /// Process the first challenge from the server
      /// and calculate a response
      /// </summary>
      /// <param name="challenge">The server issued challenge</param>
      /// <returns>Client response</returns>
      private byte[] OnInitialChallenge(byte[] challenge)
      {
         DigestChallenge dch = 
            DigestChallenge.Parse(_encoding.GetString(challenge));
         // validate input challenge
         if ( dch.Nonce == null || dch.Nonce.Length == 0 )
            throw new SaslException("Nonce value missing in server challenge");
         if ( dch.Algorithm != "md5-sess" )
            throw new SaslException("Invalid or missing algorithm value in server challenge");


         NameCallback nameCB = new NameCallback(AuthorizationId);
         PasswordCallback pwdCB = new PasswordCallback();
         RealmCallback realmCB = new RealmCallback(dch.Realm);
         ISaslCallback[] callbacks = { nameCB, pwdCB, realmCB };
         Handler.Handle(callbacks);

         DigestResponse response = new DigestResponse();
         response.Username = nameCB.Text;
         response.Realm = realmCB.Text;
         response.Nonce = dch.Nonce;
         response.Cnonce = Cnonce;
         response.NonceCount = 1;
         response.Qop = DigestQop.Auth; // only auth supported for now
         response.DigestUri = Protocol.ToLower() + "/" + ServerName;
         response.MaxBuffer = dch.MaxBuffer;
         response.Charset = dch.Charset;
         response.Cipher = null; // not supported for now
         response.Authzid = AuthorizationId;
         response.AuthParam = dch.AuthParam;

         response.Response = CalculateResponse(
            nameCB.Text, realmCB.Text, pwdCB.Text, 
            dch.Nonce, response.NonceCount, response.Qop, response.DigestUri
            );

         return _encoding.GetBytes(response.ToString());
      }
Exemple #27
0
 internal void setPasswordCallback(PasswordCallback callback)
 {
     _passwordCallback = callback;
 }
Exemple #28
0
 public override void setPasswordCallback(PasswordCallback callback)
 {
     _engine.setPasswordCallback(callback);
 }