private static byte[] GenerateKey(MasterKey key, byte[] masterKeyHashKey, long masterKeyHashRounds)
        {
            const int size = 32;

            byte[] raw = UprotectedAndConcatData(key);
            if (raw == null || raw.Length != size)
                return null;

            byte[] masterKeyData = new byte[size];

            Array.Copy(raw, masterKeyData, size);
            raw.Clear();
            try
            {
                // TODO: make generate key plugable.
                if (!GenerateKey(masterKeyData, masterKeyHashKey, masterKeyHashRounds))
                    return null;

                return masterKeyData.ToSHA256Hash();
            }
            finally
            {
                masterKeyData.Clear();
            }
        }
        public static Stream CreateCryptoStream(Stream stream, bool encrypt, MasterKey key, KeePassFileHeaderInformation headerInfo)
        {
            byte[] encryptionKey = null;
            try {
                using (var ms = new MemoryStream())
                {
                    byte[] masterKeyData = GenerateKey(key, headerInfo.MasterKeyHashKey, headerInfo.MasterKeyHashRounds);
                    if (masterKeyData == null)
                        throw new Exception("Invalid Master Key or Invalid Master Key Generation");

                    ms.Write(headerInfo.DatabaseCipherKeySeed);
                    ms.Write(masterKeyData);
                    masterKeyData.Clear();
                    encryptionKey = ms.ToSHA256Hash();
                }

                if (encryptionKey == null)
                    throw new Exception("Invalid Master Key or Key Generation");

                var encryptionEngine = Find(headerInfo.DatabaseCipherId);
                if (encryptionEngine == null)
                    throw new Exception($"Encryption Engine could not be found for Id {headerInfo.DatabaseCipherId}");


                return encryptionEngine.CreateCryptoStream(stream, encrypt, encryptionKey, headerInfo.DatabaseCipherIV);
            }
            finally
            {
                encryptionKey.Clear();
            }
        }
 public KeePassPackage(MasterKey key)
 {
     this.Binaries = new List<BinaryMapping>();
     this.Strings = new List<StringMapping>();
     this.Format = DocumentFormats.Xml;
     this.MasterKey = key;
     this.HeaderInfo = new KeePassFileHeaderInformation();
     this.Meta = new Meta();
     this.Root = new Root();
 }
            public void WriteToStreamAndVerify()
            {
                var path = Env.ResolvePath("~/Resources/NewDatabase23.kdbx");
                if (System.IO.File.Exists(path))
                    System.IO.File.Delete(path);

                try {
                    var key = new MasterKey();
                    key.Add(new MasterKeyPassword("megatron")); // terrible pw. 
                    var package = new KeePassPackage(key);

                    using (var fs = System.IO.File.OpenWrite(path))
                    {
                        var group = new Group();
                        group.Name = "Sample";

                        package.Root.Groups.Add(group);

                        var entry = new Entry(true);
                        var fields = entry.AsEntryFields();
                        fields.Title = "Test";
                        fields.Password = "******";
                        group.Entries.Add(entry);

                        package.Save(fs);


                        using (var fs2 = System.IO.File.OpenRead(Env.ResolvePath("~/Resources/NewDatabase23.kdbx")))
                        {
                            var package2 = new KeePassPackage(key);
                            package2.Open(fs2);

                            Assert.NotNull(package2);
                            Assert.NotNull(package2.Root);
                            Assert.NotNull(package2.Root.Groups);
                            Assert.Equal(1, package2.Root.Groups.Count);
                            Assert.NotNull(package2.Root.Groups[0].Entries);
                            Assert.Equal(1, package2.Root.Groups[0].Entries.Count);

                            var entry2 = package2.Root.Groups[0].Entries[0];
                            var titleString = entry2.Strings.SingleOrDefault(o => o.Key == "Title");
                            var passwordString = entry2.Strings.SingleOrDefault(o => o.Key == "Password");
                            Assert.Equal("Test", titleString.Value.Unprotect());
                            Assert.Equal("Password", passwordString.Value.Unprotect());
                        }
                    }
                } 
                finally
                {
                    //if (System.IO.File.Exists(path))
                    //    System.IO.File.Delete(path);
                }
            }
            public void OpenStreamAndRead()
            {
                var key = new MasterKey();
                key.Add(new MasterKeyPassword("password")); // terrible pw. 
                var package = new KeePassPackage(key);

                Assert.Null(package.Meta.DatabaseName);

                using (var fs = System.IO.File.OpenRead(Env.ResolvePath("~/Resources/NewDatabase.kdbx")))
                
                {
                    package.Open(fs);
                    var meta = package.Meta;

                    var predicates = new List<Func<IEntryFields, bool>>();
                    var matches = new List<Entry>();

                    if (!string.IsNullOrWhiteSpace(this.Title))
                        predicates.Add(this.CreateSeelctor("Title", this.Title, false));




                    if (package.Root != null && package.Root.Groups != null)
                    {
                        foreach (var group in package.Root.Groups)
                        {
                            if (!Collect(group, predicates, matches))
                            {
                                break;
                            }
                        }
                    }

                    Assert.NotEmpty(matches);
                    Assert.Equal("Password", matches[0].AsEntryFields().Password);
                    foreach(var match in matches)
                    {
                        var t = match.AsEntryFields().Title;
                        var v = match.AsEntryFields().Password;
                        if(v == null)
                            Console.WriteLine("{0} {1} null", t, v);
                        else 
                            Console.WriteLine("{0} {1}", t, v);

                       
                    }
                }
            }
예제 #6
0
        private async void Button_Click(object sender, RoutedEventArgs e)
        {
            if (!string.IsNullOrEmpty(viewModel.MasterPassword) && !String.IsNullOrEmpty(viewModel.UserName))
            {
                viewModel.EditIsEnabled = false;
                StatusBarProgressIndicator statusBarIndicator = StatusBar.GetForCurrentView().ProgressIndicator;
                StatusBar.GetForCurrentView().ForegroundColor = Windows.UI.Colors.White;
                statusBarIndicator.Text = "Master Key is derived...";

                await statusBarIndicator.ShowAsync();

                await MasterKey.CreateMasterKeyAsync(viewModel.MasterPassword, viewModel.UserName);

                StatusBar.GetForCurrentView().BackgroundColor = Windows.UI.Colors.Green;
                statusBarIndicator.Text = "Derivation complete! Login successful";
                Frame.Navigate(typeof(SitePage), viewModel.UserName);
            }
        }
        public virtual void TestRoundTrip()
        {
            RegisterNodeManagerResponse resp = recordFactory.NewRecordInstance <RegisterNodeManagerResponse
                                                                                >();

            byte[]    b = new byte[] { 0, 1, 2, 3, 4, 5 };
            MasterKey containerTokenMK = recordFactory.NewRecordInstance <MasterKey>();

            containerTokenMK.SetKeyId(54321);
            containerTokenMK.SetBytes(ByteBuffer.Wrap(b));
            resp.SetContainerTokenMasterKey(containerTokenMK);
            MasterKey nmTokenMK = recordFactory.NewRecordInstance <MasterKey>();

            nmTokenMK.SetKeyId(12345);
            nmTokenMK.SetBytes(ByteBuffer.Wrap(b));
            resp.SetNMTokenMasterKey(nmTokenMK);
            resp.SetNodeAction(NodeAction.Normal);
            NUnit.Framework.Assert.AreEqual(NodeAction.Normal, resp.GetNodeAction());
            // Verifying containerTokenMasterKey
            NUnit.Framework.Assert.IsNotNull(resp.GetContainerTokenMasterKey());
            NUnit.Framework.Assert.AreEqual(54321, resp.GetContainerTokenMasterKey().GetKeyId
                                                ());
            Assert.AssertArrayEquals(b, ((byte[])resp.GetContainerTokenMasterKey().GetBytes()
                                         .Array()));
            RegisterNodeManagerResponse respCopy = SerDe(resp);

            NUnit.Framework.Assert.AreEqual(NodeAction.Normal, respCopy.GetNodeAction());
            NUnit.Framework.Assert.IsNotNull(respCopy.GetContainerTokenMasterKey());
            NUnit.Framework.Assert.AreEqual(54321, respCopy.GetContainerTokenMasterKey().GetKeyId
                                                ());
            Assert.AssertArrayEquals(b, ((byte[])respCopy.GetContainerTokenMasterKey().GetBytes
                                             ().Array()));
            // Verifying nmTokenMasterKey
            NUnit.Framework.Assert.IsNotNull(resp.GetNMTokenMasterKey());
            NUnit.Framework.Assert.AreEqual(12345, resp.GetNMTokenMasterKey().GetKeyId());
            Assert.AssertArrayEquals(b, ((byte[])resp.GetNMTokenMasterKey().GetBytes().Array(
                                             )));
            respCopy = SerDe(resp);
            NUnit.Framework.Assert.AreEqual(NodeAction.Normal, respCopy.GetNodeAction());
            NUnit.Framework.Assert.IsNotNull(respCopy.GetNMTokenMasterKey());
            NUnit.Framework.Assert.AreEqual(12345, respCopy.GetNMTokenMasterKey().GetKeyId());
            Assert.AssertArrayEquals(b, ((byte[])respCopy.GetNMTokenMasterKey().GetBytes().Array
                                             ()));
        }
 /// <exception cref="System.IO.IOException"/>
 public virtual void Recover()
 {
     lock (this)
     {
         NMStateStoreService.RecoveredNMTokensState state = stateStore.LoadNMTokensState();
         MasterKey key = state.GetCurrentMasterKey();
         if (key != null)
         {
             base.currentMasterKey = new MasterKeyData(key, CreateSecretKey(((byte[])key.GetBytes
                                                                                 ().Array())));
         }
         key = state.GetPreviousMasterKey();
         if (key != null)
         {
             previousMasterKey = new MasterKeyData(key, CreateSecretKey(((byte[])key.GetBytes(
                                                                             ).Array())));
         }
         // restore the serial number from the current master key
         if (base.currentMasterKey != null)
         {
             base.serialNo = base.currentMasterKey.GetMasterKey().GetKeyId() + 1;
         }
         foreach (KeyValuePair <ApplicationAttemptId, MasterKey> entry in state.GetApplicationMasterKeys
                      ())
         {
             key = entry.Value;
             oldMasterKeys[entry.Key] = new MasterKeyData(key, CreateSecretKey(((byte[])key.GetBytes
                                                                                    ().Array())));
         }
         // reconstruct app to app attempts map
         appToAppAttemptMap.Clear();
         foreach (ApplicationAttemptId attempt in oldMasterKeys.Keys)
         {
             ApplicationId app = attempt.GetApplicationId();
             IList <ApplicationAttemptId> attempts = appToAppAttemptMap[app];
             if (attempts == null)
             {
                 attempts = new AList <ApplicationAttemptId>();
                 appToAppAttemptMap[app] = attempts;
             }
             attempts.AddItem(attempt);
         }
     }
 }
예제 #9
0
 public virtual void SetMasterKey(MasterKey masterKeyRecord)
 {
     lock (this)
     {
         // Update keys only if the key has changed.
         if (base.currentMasterKey == null || base.currentMasterKey.GetMasterKey().GetKeyId
                 () != masterKeyRecord.GetKeyId())
         {
             Log.Info("Rolling master-key for container-tokens, got key with id " + masterKeyRecord
                      .GetKeyId());
             if (base.currentMasterKey != null)
             {
                 UpdatePreviousMasterKey(base.currentMasterKey);
             }
             UpdateCurrentMasterKey(new MasterKeyData(masterKeyRecord, CreateSecretKey(((byte[]
                                                                                         )masterKeyRecord.GetBytes().Array()))));
         }
     }
 }
    public V7CryptomatorHelper(string password, string vaultPath)
    {
        try
        {
            string masterKeyPath = PathJoin(vaultPath, "masterkey.cryptomator");

            var       jsonString = File.ReadAllText(masterKeyPath);
            MasterKey mkey       = JsonConvert.DeserializeObject <MasterKey>(jsonString);

            if (mkey.Version != 7)
            {
                throw new ArgumentException("Only version 7 vaults are supported");
            }

            byte[] abPrimaryMasterKey = Convert.FromBase64String(mkey.PrimaryMasterKey);
            byte[] abHmacMasterKey    = Convert.FromBase64String(mkey.HmacMasterKey);
            byte[] abScryptSalt       = Convert.FromBase64String(mkey.ScryptSalt);

            kek = SCrypt.ComputeDerivedKey(Encoding.ASCII.GetBytes(password), abScryptSalt, mkey.ScryptCostParam, mkey.ScryptBlockSize, 1, 1, 32);

            masterKey = KeyWrapAlgorithm.UnwrapKey(kek, abPrimaryMasterKey);
            macKey    = KeyWrapAlgorithm.UnwrapKey(kek, abHmacMasterKey);
            sivKey    = macKey.Concat(masterKey).ToArray();

            this.vaultPath = vaultPath;
            siv            = Aead.CreateAesCmacSiv(sivKey);

            byte[] ciphertext  = siv.Seal(new byte[0]);
            byte[] hash        = sha1.ComputeHash(ciphertext);
            string fullDirName = Base32Encoding.ToString(hash);
            physicalPathRoot = PathJoin(fullDirName.Substring(0, 2), fullDirName.Substring(2));
        }
        catch (System.IO.FileNotFoundException e)
        {
            throw new FileNotFoundException("Cannot open master key file (masterkey.cryptomator)", e);
        }

        catch (CryptographicException e)
        {
            throw new CryptographicException("Cannot open vault, possible password error", e);
        }
    }
예제 #11
0
        /// <exception cref="System.Exception"/>
        public virtual NodeHeartbeatResponse NodeHeartbeat(IDictionary <ApplicationId, IList
                                                                        <Org.Apache.Hadoop.Yarn.Api.Records.ContainerStatus> > conts, bool isHealthy, int
                                                           resId)
        {
            NodeHeartbeatRequest req = Org.Apache.Hadoop.Yarn.Util.Records.NewRecord <NodeHeartbeatRequest
                                                                                      >();
            NodeStatus status = Org.Apache.Hadoop.Yarn.Util.Records.NewRecord <NodeStatus>();

            status.SetResponseId(resId);
            status.SetNodeId(nodeId);
            foreach (KeyValuePair <ApplicationId, IList <Org.Apache.Hadoop.Yarn.Api.Records.ContainerStatus
                                                         > > entry in conts)
            {
                Org.Mortbay.Log.Log.Info("entry.getValue() " + entry.Value);
                status.SetContainersStatuses(entry.Value);
            }
            NodeHealthStatus healthStatus = Org.Apache.Hadoop.Yarn.Util.Records.NewRecord <NodeHealthStatus
                                                                                           >();

            healthStatus.SetHealthReport(string.Empty);
            healthStatus.SetIsNodeHealthy(isHealthy);
            healthStatus.SetLastHealthReportTime(1);
            status.SetNodeHealthStatus(healthStatus);
            req.SetNodeStatus(status);
            req.SetLastKnownContainerTokenMasterKey(this.currentContainerTokenMasterKey);
            req.SetLastKnownNMTokenMasterKey(this.currentNMTokenMasterKey);
            NodeHeartbeatResponse heartbeatResponse = resourceTracker.NodeHeartbeat(req);
            MasterKey             masterKeyFromRM   = heartbeatResponse.GetContainerTokenMasterKey();

            if (masterKeyFromRM != null && masterKeyFromRM.GetKeyId() != this.currentContainerTokenMasterKey
                .GetKeyId())
            {
                this.currentContainerTokenMasterKey = masterKeyFromRM;
            }
            masterKeyFromRM = heartbeatResponse.GetNMTokenMasterKey();
            if (masterKeyFromRM != null && masterKeyFromRM.GetKeyId() != this.currentNMTokenMasterKey
                .GetKeyId())
            {
                this.currentNMTokenMasterKey = masterKeyFromRM;
            }
            return(heartbeatResponse);
        }
예제 #12
0
 public virtual void Recover(RMStateStore.RMState state)
 {
     if (state.GetAMRMTokenSecretManagerState() != null)
     {
         // recover the current master key
         MasterKey currentKey = state.GetAMRMTokenSecretManagerState().GetCurrentMasterKey
                                    ();
         this.currentMasterKey = new MasterKeyData(currentKey, CreateSecretKey(((byte[])currentKey
                                                                                .GetBytes().Array())));
         // recover the next master key if not null
         MasterKey nextKey = state.GetAMRMTokenSecretManagerState().GetNextMasterKey();
         if (nextKey != null)
         {
             this.nextMasterKey = new MasterKeyData(nextKey, CreateSecretKey(((byte[])nextKey.
                                                                              GetBytes().Array())));
             this.timer.Schedule(new AMRMTokenSecretManager.NextKeyActivator(this), this.activationDelay
                                 );
         }
     }
 }
예제 #13
0
        private void loginPictureBox_Click(object sender, EventArgs e)
        {
            var login = new MasterKey(this);

            login.ShowDialog();
            if (isLoged)
            {
                loginPictureBox.Enabled = false;
                TabPage admin = new TabPage();
                // administrator
                //
                admin.BackColor = System.Drawing.Color.White;
                admin.Location  = new System.Drawing.Point(4, 38);
                admin.Name      = "administrator";
                admin.Size      = new System.Drawing.Size(792, 527);
                admin.TabIndex  = 7;
                admin.Text      = "Administración";
                //
                metroTabControl2.TabPages.Add(admin);
            }
        }
예제 #14
0
        private void PopulateKeys(NodeHeartbeatRequest request, NodeHeartbeatResponse nodeHeartBeatResponse
                                  )
        {
            // Check if node's masterKey needs to be updated and if the currentKey has
            // roller over, send it across
            // ContainerTokenMasterKey
            MasterKey nextMasterKeyForNode = this.containerTokenSecretManager.GetNextKey();

            if (nextMasterKeyForNode != null && (request.GetLastKnownContainerTokenMasterKey(
                                                     ).GetKeyId() != nextMasterKeyForNode.GetKeyId()))
            {
                nodeHeartBeatResponse.SetContainerTokenMasterKey(nextMasterKeyForNode);
            }
            // NMTokenMasterKey
            nextMasterKeyForNode = this.nmTokenSecretManager.GetNextKey();
            if (nextMasterKeyForNode != null && (request.GetLastKnownNMTokenMasterKey().GetKeyId
                                                     () != nextMasterKeyForNode.GetKeyId()))
            {
                nodeHeartBeatResponse.SetNMTokenMasterKey(nextMasterKeyForNode);
            }
        }
예제 #15
0
 /// <exception cref="System.IO.IOException"/>
 public virtual void Recover()
 {
     lock (this)
     {
         NMStateStoreService.RecoveredContainerTokensState state = stateStore.LoadContainerTokensState
                                                                       ();
         MasterKey key = state.GetCurrentMasterKey();
         if (key != null)
         {
             base.currentMasterKey = new MasterKeyData(key, CreateSecretKey(((byte[])key.GetBytes
                                                                                 ().Array())));
         }
         key = state.GetPreviousMasterKey();
         if (key != null)
         {
             previousMasterKey = new MasterKeyData(key, CreateSecretKey(((byte[])key.GetBytes(
                                                                             ).Array())));
         }
         // restore the serial number from the current master key
         if (base.currentMasterKey != null)
         {
             base.serialNo = base.currentMasterKey.GetMasterKey().GetKeyId() + 1;
         }
         foreach (KeyValuePair <ContainerId, long> entry in state.GetActiveTokens())
         {
             ContainerId         containerId   = entry.Key;
             long                expTime       = entry.Value;
             IList <ContainerId> containerList = recentlyStartedContainerTracker[expTime];
             if (containerList == null)
             {
                 containerList = new AList <ContainerId>();
                 recentlyStartedContainerTracker[expTime] = containerList;
             }
             if (!containerList.Contains(containerId))
             {
                 containerList.AddItem(containerId);
             }
         }
     }
 }
예제 #16
0
        public override bool Equals(object obj)
        {
            if (this == obj)
            {
                return(true);
            }
            if (!(obj is MasterKey))
            {
                return(false);
            }
            MasterKey other = (MasterKey)obj;

            if (this.GetKeyId() != other.GetKeyId())
            {
                return(false);
            }
            if (!this.GetBytes().Equals(other.GetBytes()))
            {
                return(false);
            }
            return(true);
        }
예제 #17
0
        /// <exception cref="System.Exception"/>
        public virtual RegisterNodeManagerResponse RegisterNode(IList <NMContainerStatus>
                                                                containerReports, IList <ApplicationId> runningApplications)
        {
            RegisterNodeManagerRequest req = Org.Apache.Hadoop.Yarn.Util.Records.NewRecord <RegisterNodeManagerRequest
                                                                                            >();

            req.SetNodeId(nodeId);
            req.SetHttpPort(httpPort);
            Resource resource = BuilderUtils.NewResource(memory, vCores);

            req.SetResource(resource);
            req.SetContainerStatuses(containerReports);
            req.SetNMVersion(version);
            req.SetRunningApplications(runningApplications);
            RegisterNodeManagerResponse registrationResponse = resourceTracker.RegisterNodeManager
                                                                   (req);

            this.currentContainerTokenMasterKey = registrationResponse.GetContainerTokenMasterKey
                                                      ();
            this.currentNMTokenMasterKey = registrationResponse.GetNMTokenMasterKey();
            return(registrationResponse);
        }
예제 #18
0
        public static NodeHeartbeatResponse NewNodeHeartbeatResponse(int responseId, NodeAction
                                                                     action, IList <ContainerId> containersToCleanUp, IList <ApplicationId> applicationsToCleanUp
                                                                     , MasterKey containerTokenMasterKey, MasterKey nmTokenMasterKey, long nextHeartbeatInterval
                                                                     )
        {
            NodeHeartbeatResponse response = recordFactory.NewRecordInstance <NodeHeartbeatResponse
                                                                              >();

            response.SetResponseId(responseId);
            response.SetNodeAction(action);
            response.SetContainerTokenMasterKey(containerTokenMasterKey);
            response.SetNMTokenMasterKey(nmTokenMasterKey);
            response.SetNextHeartBeatInterval(nextHeartbeatInterval);
            if (containersToCleanUp != null)
            {
                response.AddAllContainersToCleanup(containersToCleanUp);
            }
            if (applicationsToCleanUp != null)
            {
                response.AddAllApplicationsToCleanup(applicationsToCleanUp);
            }
            return(response);
        }
예제 #19
0
        /// <inheritdoc/>
        public XmlSerializedDescriptorInfo ExportToXml()
        {
            // <descriptor>
            //   <encryption algorithm="..." />
            //   <validation algorithm="..." /> <!-- only if not GCM -->
            //   <masterKey requiresEncryption="true">...</masterKey>
            // </descriptor>

            var encryptionElement = new XElement("encryption",
                                                 new XAttribute("algorithm", Configuration.EncryptionAlgorithm));

            var validationElement = (AuthenticatedEncryptorFactory.IsGcmAlgorithm(Configuration.EncryptionAlgorithm))
                ? (object)new XComment(" AES-GCM includes a 128-bit authentication tag, no extra validation algorithm required. ")
                : (object)new XElement("validation",
                                       new XAttribute("algorithm", Configuration.ValidationAlgorithm));

            var outerElement = new XElement("descriptor",
                                            encryptionElement,
                                            validationElement,
                                            MasterKey.ToMasterKeyElement());

            return(new XmlSerializedDescriptorInfo(outerElement, typeof(AuthenticatedEncryptorDescriptorDeserializer)));
        }
예제 #20
0
    /// <inheritdoc />
    public XmlSerializedDescriptorInfo ExportToXml()
    {
        // <descriptor>
        //   <!-- Windows CNG-GCM -->
        //   <encryption algorithm="..." keyLength="..." [provider="..."] />
        //   <masterKey>...</masterKey>
        // </descriptor>

        var encryptionElement = new XElement("encryption",
                                             new XAttribute("algorithm", Configuration.EncryptionAlgorithm),
                                             new XAttribute("keyLength", Configuration.EncryptionAlgorithmKeySize));

        if (Configuration.EncryptionAlgorithmProvider != null)
        {
            encryptionElement.SetAttributeValue("provider", Configuration.EncryptionAlgorithmProvider);
        }

        var rootElement = new XElement("descriptor",
                                       new XComment(" Algorithms provided by Windows CNG, using Galois/Counter Mode encryption and validation "),
                                       encryptionElement,
                                       MasterKey.ToMasterKeyElement());

        return(new XmlSerializedDescriptorInfo(rootElement, typeof(CngGcmAuthenticatedEncryptorDescriptorDeserializer)));
    }
예제 #21
0
        public XmlSerializedDescriptorInfo ExportToXml()
        {
            // <descriptor>
            //   <!-- managed implementations -->
            //   <encryption algorithm="..." keyLength="..." />
            //   <validation algorithm="..." />
            //   <masterKey>...</masterKey>
            // </descriptor>

            var encryptionElement = new XElement("encryption",
                                                 new XAttribute("algorithm", TypeToFriendlyName(Configuration.EncryptionAlgorithmType)),
                                                 new XAttribute("keyLength", Configuration.EncryptionAlgorithmKeySize));

            var validationElement = new XElement("validation",
                                                 new XAttribute("algorithm", TypeToFriendlyName(Configuration.ValidationAlgorithmType)));

            var rootElement = new XElement("descriptor",
                                           new XComment(" Algorithms provided by specified SymmetricAlgorithm and KeyedHashAlgorithm "),
                                           encryptionElement,
                                           validationElement,
                                           MasterKey.ToMasterKeyElement());

            return(new XmlSerializedDescriptorInfo(rootElement, typeof(ManagedAuthenticatedEncryptorDescriptorDeserializer)));
        }
예제 #22
0
파일: Form2.cs 프로젝트: nberglund/ssbadmin
        int UpDateSsb()
        {
            updatedobj = null;
              //if (!isDirty)
            //return 0;
              if (!ValidateData()) {
            Cursor crs = Cursor.Current;
            Cursor.Current = Cursors.WaitCursor;

            try {
              Database db = null;

              ServiceBroker sb = null;
              if (ssbType != SsbEnum.Database && ssbType != SsbEnum.Login && ssbType != SsbEnum.EndPoint) {
             sb = dBase.ServiceBroker;
              }
              switch (ssbType) {
            case SsbEnum.Database:
              MasterKey mk = null;
              SSBIDatabase sbd = null;
              if (isEdit) {
                sbd = (SSBIDatabase)objToUpdate;
                db = sbd.DataBase;
              }
              else {
                db = new Database();
                db.Name = txtName.Text;
                db.Parent = dbServ.SMOServer;
              }

              if (isEdit) {
               if(db.MasterKey != null && db_chkMasterKey.Checked == false) {
                 mk = db.MasterKey;
                 mk.Drop();

               }
               else if (db.MasterKey == null && db_chkMasterKey.Checked) {
                 mk = new MasterKey();
                 mk.Parent = db;
                 mk.Create(db_txtMkPwd.Text);
               }

               db.Alter();
               if (sbd.IsTrustworthy != db_chkTrustWorthy.Checked)
                 sbd.IsTrustworthy = db_chkTrustWorthy.Checked;

              }
              else {
                db.Create();
                sbd = new SSBIDatabase(db);

                if (db_chkMasterKey.Checked) {
                  mk = new MasterKey();
                  mk.Parent = db;
                  mk.Create(db_txtMkPwd.Text);

                }

                if (db_chkTrustWorthy.Checked) {
                  sbd.IsTrustworthy = true;
                }

              }
              if (dBase == null)
                dBase = db;

              //Server serv = db.Parent;

              updatedobj = db;
              break;
            case SsbEnum.MessageType:
              MessageType mt = null;
              if (isEdit)
                mt = (MessageType)objToUpdate;
              else {
                mt = new MessageType();
                mt.Parent = sb;
                mt.Name = txtName.Text;
              }
              if (cboUser.Text != string.Empty)
                mt.Owner = cboUser.Text;
              mt.MessageTypeValidation = (MessageTypeValidation)Enum.Parse(typeof(MessageTypeValidation), cboVal.Text);
              if (cboValSchema.Enabled)
                mt.ValidationXmlSchemaCollection = cboValSchema.Text;

              if (isEdit)
                mt.Alter();
              else
                mt.Create();
              updatedobj = mt;
              break;

            case SsbEnum.Contract:
              ServiceContract sc = new ServiceContract();
              sc.Parent = sb;
              sc.Name = txtName.Text;
              if (cboUser.Text != string.Empty)
                sc.Owner = cboUser.Text;
              //get the message types
              foreach (DataGridViewRow row in dvMsgTypes.Rows) {
                sc.MessageTypeMappings.Add(new MessageTypeMapping(sc, row.Cells[0].Value.ToString(), (MessageSource)Enum.Parse(typeof(MessageSource), row.Cells[1].Value.ToString())));
              }

              if (isEdit)
                sc.Alter();
              else
                sc.Create();

              updatedobj = sc;
              break;

            case SsbEnum.Queu:
              ServiceQueue q = null;
              if (isEdit)
                q = (ServiceQueue)objToUpdate;
              else {
                q = new ServiceQueue();
                q.Parent = sb;
                q.Name = txtName.Text;
              }
              q.IsEnqueueEnabled = chkStatus.Checked;
              if (chkRetention.Checked)
                q.IsRetentionEnabled = true;

              //if (chkActivation.Checked) {
              //if(isEdit)
              //  q.IsActivationEnabled = chkActivation.Checked;
              //
              if (chkActivation.Checked) {
                q.IsActivationEnabled = chkActivation.Checked;
                if (dBase.Name != cboQDb.Text)
                  q.ProcedureDatabase = cboQDb.Text;
                StoredProcedure sp = (StoredProcedure)cboProc.SelectedItem;
                q.ProcedureSchema = sp.Schema;
                q.ProcedureName = cboProc.Text;
                q.MaxReaders = short.Parse(txtReaders.Text);
                if (rdOwner.Checked)
                  q.ActivationExecutionContext = ActivationExecutionContext.Owner;
                else if (rdSelf.Checked)
                  q.ActivationExecutionContext = ActivationExecutionContext.Self;
                else if (rdUser.Checked) {
                  q.ActivationExecutionContext = ActivationExecutionContext.ExecuteAsUser;
                  q.ExecutionContextPrincipal = txtExecuteAs.Text;
                }

              }

              if (isEdit)
                q.Alter();
              else
                q.Create();

              updatedobj = q;

              break;

            case SsbEnum.Service:
              BrokerService bserv = null;
              if (isEdit)
                bserv = (BrokerService)objToUpdate;
              else {
                bserv = new BrokerService();
                bserv.Parent = sb;
                bserv.Name = txtName.Text;
              }
              if (cboUser.Text != string.Empty)
                bserv.Owner = cboUser.Text;

              ServiceQueue servq = (ServiceQueue)cboQueue.SelectedItem;
              bserv.QueueName = servq.Name;
              bserv.QueueSchema = servq.Schema;

              if (lbChosenCtr.Items.Count > 0) {
                foreach (object o in lbChosenCtr.Items) {
                  ServiceContract servctr = o as ServiceContract;
                  ServiceContractMapping scm = new ServiceContractMapping(bserv, servctr.Name);
                  bserv.ServiceContractMappings.Add(scm);
                }
              }

              if (isEdit)
                bserv.Alter();
              else
                bserv.Create();

              updatedobj = bserv;

              break;

            case SsbEnum.Route:
              ServiceRoute srt = null;
              if (isEdit)
                srt = (ServiceRoute)objToUpdate;
              else {
                srt = new ServiceRoute();
                srt.Name = txtName.Text;
                srt.Parent = sb;
              }

              if (cboUser.Text != string.Empty)
                srt.Owner = cboUser.Text;

              if (textBroker.Text != string.Empty)
                srt.BrokerInstance = textBroker.Text;

              if (textRemote.Text != string.Empty)
                srt.RemoteService = textRemote.Text;

              if (textLifeTime.Text != string.Empty)
                srt.ExpirationDate = DateTime.Parse(textLifeTime.Text);

              if (rdLocal.Checked)
                srt.Address = "LOCAL";

              if (rdTransport.Checked)
                srt.Address = "TRANSPORT";

              if (rdTCP.Checked)
                srt.Address = "TCP://" + txtAddress.Text;

              if (txtMirror.Text != string.Empty)
                srt.MirrorAddress = "TCP://" + txtMirror.Text;

              //StringCollection sColl = srt.Script();
              //foreach (string s in sColl)
              //  MessageBox.Show(s);

              if (isEdit)
                srt.Alter();
              else
                srt.Create();

              updatedobj = srt;

              break;

            case SsbEnum.RemoteBinding:
              RemoteServiceBinding remBind = null;
              if (isEdit)
                remBind = (RemoteServiceBinding)objToUpdate;
              else {
                remBind = new RemoteServiceBinding();
                remBind.Name = txtName.Text;
                remBind.Parent = sb;
              }

              if (cboUser.Text != string.Empty)
                remBind.Owner = cboUser.Text;

              remBind.RemoteService = textRemServ.Text;

              remBind.CertificateUser = cboRemUser.Text;
              remBind.IsAnonymous = chkAnon.Checked;

              StringCollection sColl = remBind.Script();
              foreach (string s in sColl)
                MessageBox.Show(s);

              if (isEdit)
                remBind.Alter();
              else
                remBind.Create();

              updatedobj = remBind;

              break;

            case SsbEnum.Conversation:
              TimeSpan ts = TimeSpan.Zero;
              Guid grpHandle = Guid.Empty;
              string convContract = "DEFAULT";
              BrokerService bServ = (BrokerService)cnv_cboFrmServ.SelectedItem;

              string toService = cnv_txtToSrv.Text;

              if (cnv_txtLifetime.Text != string.Empty && cnv_txtLifetime.Text != "0")
                ts = TimeSpan.FromSeconds(double.Parse(cnv_txtLifetime.Text));

              if (cnv_cboContract.Text != string.Empty)
                convContract = cnv_cboContract.Text;

              if (cnv_txtRelGrpHndl.Text != string.Empty)
                grpHandle = new Guid(cnv_txtRelGrpHndl.Text);

              //get a service object
              Service smoserv = smo.GetSSBIService(bServ.Parent.Parent, bServ.Name);
              if (smoserv.Connection.State == ConnectionState.Closed)
                smoserv.Connection.Open();

              smoserv.Connection.ChangeDatabase(bServ.Parent.Parent.Name);
              updatedobj = smoserv.BeginDialog(toService, convContract, ts, cnv_chkEncryption.Checked, grpHandle);
              break;

            case SsbEnum.Message:
              SSBIConversation msgConv = (SSBIConversation)msg_cboConv.SelectedItem;
              string servName = msg_txtFrom.Text;
              //we need a service object
              Service msgSsbiServ = smo.GetSSBIService(dBase, msgConv.FromService);
              if (msgSsbiServ.Connection.State== ConnectionState.Closed)
                 msgSsbiServ.Connection.Open();

               msgSsbiServ.Connection.ChangeDatabase(dBase.Name);
              Conversation msgCnv = new Conversation(msgSsbiServ, msgConv.Handle);
              string msgType = msg_cboMsgType.SelectedText;
              string msgString = msg_rchMsg.Text;
              msgType = msg_cboMsgType.Text;
              MemoryStream msgBody = new MemoryStream(Encoding.ASCII.GetBytes(msgString));

              Microsoft.Samples.SqlServer.Message msg = new Microsoft.Samples.SqlServer.Message(msgType, msgBody);
              msgCnv.Send(msg);

              break;

            case SsbEnum.Login :
              string pwd = "";
              Login lg = new Login();
              lg.Parent = dbServ.SMOServer;
              lg.Name = lgn_txtLoginName.Text;
              if (lgn_rdSql.Checked) {
                pwd = lgn_txtPwd.Text;
                lg.PasswordPolicyEnforced = lgn_chkEnforcePolicy.Checked;
                lg.LoginType = LoginType.SqlLogin;
                lg.Create(pwd);
              }
              else {
                lg.Create();
              }

              updatedobj = lg;
              break;

            case SsbEnum.Certificate:
              string certOwner  = "dbo";
              int certSource = cert_cboSource.SelectedIndex;
              Certificate cert = new Certificate();
              if(!isEdit) {
                cert.Name = txtName.Text;
                if(cboUser.Text != "")
                  certOwner = cboUser.Text;
                cert.Parent = dBase;
                cert.Owner = certOwner;

              }

              cert.ActiveForServiceBrokerDialog = cert_chkBeginDlg.Checked;

              if (certSource == 0) {
                if (!isEdit) {
                  if (cert_chkMasterKey.Checked)
                    cert.Create(cert_txtCertPath.Text, CertificateSourceType.File, cert_txtPrivPath.Text, cert_txtDecrypt.Text);
                  else
                    cert.Create(cert_txtCertPath.Text, CertificateSourceType.File, cert_txtPrivPath.Text, cert_txtDecrypt.Text, cert_txtEncrypt.Text);

                }
              }
              else if (certSource == 1) {
                if (!isEdit) {
                  cert.StartDate = cert_dtValidFrom.Value;
                  cert.ExpirationDate = cert_dtExpiry.Value;
                  cert.Subject = cert_txtCertPath.Text;

                  if (cert_chkMasterKey.Checked) {
                    cert.Create();
                  }
                  else {
                    cert.Create(cert_txtEncrypt.Text);
                  }
                }

              }
              else if (certSource == 2) {
                if (!isEdit) {
                  cert.Create(cert_txtCertPath.Text, CertificateSourceType.File);
                }

              }

              if (isEdit)
                cert.Alter();

              updatedobj = cert;
              break;

            case SsbEnum.User :
              User usr;
              if (!isEdit) {
                usr = new User();
                usr.Name = txtName.Text;
                usr.Parent = dBase;
                if(usr_chkLogin.Checked)
                  usr.Login = usr_cboLogin.Text;

              }
              else
                usr = (User)objToUpdate;

              if (usr_cboCerts.SelectedIndex != -1)
                usr.Certificate = usr_cboCerts.Text;

              if (!isEdit)
                if (usr_chkLogin.Checked)
                  usr.Create();
                else
                  smo.CreateUserWithNoLogin(usr);

              else
                usr.Alter();
              updatedobj = usr;
              break;

            case SsbEnum.EndPoint :
              Endpoint ep = null;
              if (!isEdit) {
                ep = new Endpoint();
                ep.Name = txtName.Text;
                ep.Parent = dbServ.SMOServer;
                ep.ProtocolType = ProtocolType.Tcp;
                ep.EndpointType = EndpointType.ServiceBroker;
              }
              else
                ep = ((SSBIEndpoint)objToUpdate).EndPoint;

              ep.Protocol.Tcp.ListenerPort = int.Parse(ep_txtPort.Text);
              if (ep_txtIp.Text == "ALL")
                ep.Protocol.Tcp.ListenerIPAddress = System.Net.IPAddress.Any;
              else {
                ep.Protocol.Tcp.ListenerIPAddress = System.Net.IPAddress.Parse(ep_txtIp.Text);
              }
              ep.Payload.ServiceBroker.EndpointAuthenticationOrder = (EndpointAuthenticationOrder)ep_cboAuth.SelectedItem;
              if (ep_cboCert.SelectedIndex != -1)
                ep.Payload.ServiceBroker.Certificate = ep_cboCert.Text;

              ep.Payload.ServiceBroker.EndpointEncryption = (EndpointEncryption)ep_cboEncrypt.SelectedItem;
              if (ep_cboAlgorithm.SelectedIndex != -1)
                ep.Payload.ServiceBroker.EndpointEncryptionAlgorithm = (EndpointEncryptionAlgorithm)ep_cboAlgorithm.SelectedItem;

              ep.Payload.ServiceBroker.IsMessageForwardingEnabled = ep_chkFwd.Checked;

              if (ep_txtSize.Text != string.Empty)
                ep.Payload.ServiceBroker.MessageForwardingSize = int.Parse(ep_txtSize.Text);

              if(!isEdit)
                ep.Create();

              switch ((EndpointState)ep_cboState.SelectedIndex) {
                case EndpointState.Disabled :
                  ep.Disable();
                  break;

                case EndpointState.Started :
                  ep.Start();
                  break;
                case EndpointState.Stopped :
                  if (isEdit)
                    ep.Stop();
                  break;
              }

              if (isEdit)
                ep.Alter();

              break;

            case SsbEnum.CreateListing :
              CreateListing(true);

              break;

              }

              if (isEdit)
            _state = SsbState.Edited;
              else
            _state = SsbState.New;

              Cursor.Current = crs;

              this.DialogResult = DialogResult.OK;

              ExitAndClose();

            }
            catch (FailedOperationException e) {
              smo.ShowException(e);
            }
            catch (Exception ex) {
              smo.ShowException(ex);
            }

            finally {
              if(dbServ !=null)
            dbServ.SMOServer.ConnectionContext.Disconnect();

            }

              }

              return 0;
        }
예제 #23
0
 /// <exception cref="System.IO.IOException"/>
 public override void StoreNMTokenPreviousMasterKey(MasterKey key)
 {
 }
예제 #24
0
 /// <exception cref="System.IO.IOException"/>
 public override void StoreNMTokenApplicationMasterKey(ApplicationAttemptId attempt
                                                       , MasterKey key)
 {
 }
예제 #25
0
 /// <exception cref="System.IO.IOException"/>
 public override void StoreContainerTokenCurrentMasterKey(MasterKey key)
 {
 }
        public virtual void TestRecovery()
        {
            YarnConfiguration conf = new YarnConfiguration();

            conf.SetBoolean(YarnConfiguration.NmRecoveryEnabled, true);
            NodeId      nodeId = NodeId.NewInstance("somehost", 1234);
            ContainerId cid1   = BuilderUtils.NewContainerId(1, 1, 1, 1);
            ContainerId cid2   = BuilderUtils.NewContainerId(2, 2, 2, 2);

            TestNMContainerTokenSecretManager.ContainerTokenKeyGeneratorForTest keygen = new
                                                                                         TestNMContainerTokenSecretManager.ContainerTokenKeyGeneratorForTest(conf);
            NMMemoryStateStoreService stateStore = new NMMemoryStateStoreService();

            stateStore.Init(conf);
            stateStore.Start();
            NMContainerTokenSecretManager secretMgr = new NMContainerTokenSecretManager(conf,
                                                                                        stateStore);

            secretMgr.SetNodeId(nodeId);
            MasterKey currentKey = keygen.GenerateKey();

            secretMgr.SetMasterKey(currentKey);
            ContainerTokenIdentifier tokenId1 = CreateContainerTokenId(cid1, nodeId, "user1",
                                                                       secretMgr);
            ContainerTokenIdentifier tokenId2 = CreateContainerTokenId(cid2, nodeId, "user2",
                                                                       secretMgr);

            NUnit.Framework.Assert.IsNotNull(secretMgr.RetrievePassword(tokenId1));
            NUnit.Framework.Assert.IsNotNull(secretMgr.RetrievePassword(tokenId2));
            // restart and verify tokens still valid
            secretMgr = new NMContainerTokenSecretManager(conf, stateStore);
            secretMgr.SetNodeId(nodeId);
            secretMgr.Recover();
            NUnit.Framework.Assert.AreEqual(currentKey, secretMgr.GetCurrentKey());
            NUnit.Framework.Assert.IsTrue(secretMgr.IsValidStartContainerRequest(tokenId1));
            NUnit.Framework.Assert.IsTrue(secretMgr.IsValidStartContainerRequest(tokenId2));
            NUnit.Framework.Assert.IsNotNull(secretMgr.RetrievePassword(tokenId1));
            NUnit.Framework.Assert.IsNotNull(secretMgr.RetrievePassword(tokenId2));
            // roll master key and start a container
            secretMgr.StartContainerSuccessful(tokenId2);
            currentKey = keygen.GenerateKey();
            secretMgr.SetMasterKey(currentKey);
            // restart and verify tokens still valid due to prev key persist
            secretMgr = new NMContainerTokenSecretManager(conf, stateStore);
            secretMgr.SetNodeId(nodeId);
            secretMgr.Recover();
            NUnit.Framework.Assert.AreEqual(currentKey, secretMgr.GetCurrentKey());
            NUnit.Framework.Assert.IsTrue(secretMgr.IsValidStartContainerRequest(tokenId1));
            NUnit.Framework.Assert.IsFalse(secretMgr.IsValidStartContainerRequest(tokenId2));
            NUnit.Framework.Assert.IsNotNull(secretMgr.RetrievePassword(tokenId1));
            NUnit.Framework.Assert.IsNotNull(secretMgr.RetrievePassword(tokenId2));
            // roll master key again, restart, and verify keys no longer valid
            currentKey = keygen.GenerateKey();
            secretMgr.SetMasterKey(currentKey);
            secretMgr = new NMContainerTokenSecretManager(conf, stateStore);
            secretMgr.SetNodeId(nodeId);
            secretMgr.Recover();
            NUnit.Framework.Assert.AreEqual(currentKey, secretMgr.GetCurrentKey());
            NUnit.Framework.Assert.IsTrue(secretMgr.IsValidStartContainerRequest(tokenId1));
            NUnit.Framework.Assert.IsFalse(secretMgr.IsValidStartContainerRequest(tokenId2));
            try
            {
                secretMgr.RetrievePassword(tokenId1);
                NUnit.Framework.Assert.Fail("token should not be valid");
            }
            catch (SecretManager.InvalidToken)
            {
            }
            // expected
            try
            {
                secretMgr.RetrievePassword(tokenId2);
                NUnit.Framework.Assert.Fail("token should not be valid");
            }
            catch (SecretManager.InvalidToken)
            {
            }
            // expected
            stateStore.Close();
        }
예제 #27
0
        private async void LoginButton_OnClick(object sender, RoutedEventArgs e)
        {
            if (!string.IsNullOrEmpty(PasswordBox.Password))
            {
                Views.Busy.SetBusy(true, ResourceLoader.GetForCurrentView().GetString("BusyMessage_GeneratingMasterKey"));
                // generate master password stuff
                var userName = UserNameBox.Text;
                var password = PasswordBox.Password.ToCharArray();
                await Task.Run(() => App.Container.Resolve <SettingsService>().MasterKey = MasterKey.Create(userName, password));

                Views.Busy.SetBusy(false);

                Shell.Instance.SetMenuState(HamburgerMenuState.LoggedIn);
                Shell.Instance.NavigationService.Navigate(typeof(Views.SitesPage), new SitesPageViewModelParameter {
                    ParameterType = SitesPageViewModelParameterType.RefreshView
                });
                return;
            }
            Shell.Instance.SetMenuState(HamburgerMenuState.Default);
            PasswordBox.Focus(FocusState.Keyboard);
        }
 public PublicParameters Setup()
 {
     MasterKey = new MasterKey();
     return(new PublicParameters());
 }
        private static byte[] UprotectedAndConcatData(MasterKey key)
        {
            // TODO: research if using a memory stream is the right thing to do.
            using (var ms = new MemoryStream())
            {
                foreach(var fragment in key)
                {
                    ms.Write(fragment.UnprotectAndCopyData());
                }

                return ms.ToSHA256Hash();
            }
        }
예제 #30
0
 public abstract void SetNextMasterKey(MasterKey nextMasterKey);
예제 #31
0
 public abstract void SetCurrentMasterKey(MasterKey currentMasterKey);
 private YarnServerCommonProtos.MasterKeyProto ConvertToProtoFormat(MasterKey t)
 {
     return(((MasterKeyPBImpl)t).GetProto());
 }
예제 #33
0
 public MasterKeyData(MasterKey masterKeyRecord, SecretKey secretKey)
 {
     this.masterKeyRecord    = masterKeyRecord;
     this.generatedSecretKey = secretKey;
 }
예제 #34
0
 public ConfirmPartyGump(MasterKey key)
     : base()
 {
     this.m_Key = key;
 }
예제 #35
0
 /// <exception cref="System.IO.IOException"/>
 public override void StoreContainerTokenPreviousMasterKey(MasterKey key)
 {
 }
        public virtual void TestRecovery()
        {
            YarnConfiguration conf = new YarnConfiguration();

            conf.SetBoolean(YarnConfiguration.NmRecoveryEnabled, true);
            NodeId nodeId = NodeId.NewInstance("somehost", 1234);
            ApplicationAttemptId attempt1 = ApplicationAttemptId.NewInstance(ApplicationId.NewInstance
                                                                                 (1, 1), 1);
            ApplicationAttemptId attempt2 = ApplicationAttemptId.NewInstance(ApplicationId.NewInstance
                                                                                 (2, 2), 2);

            TestNMTokenSecretManagerInNM.NMTokenKeyGeneratorForTest keygen = new TestNMTokenSecretManagerInNM.NMTokenKeyGeneratorForTest
                                                                                 ();
            NMMemoryStateStoreService stateStore = new NMMemoryStateStoreService();

            stateStore.Init(conf);
            stateStore.Start();
            NMTokenSecretManagerInNM secretMgr = new NMTokenSecretManagerInNM(stateStore);

            secretMgr.SetNodeId(nodeId);
            MasterKey currentKey = keygen.GenerateKey();

            secretMgr.SetMasterKey(currentKey);
            NMTokenIdentifier attemptToken1 = GetNMTokenId(secretMgr.CreateNMToken(attempt1,
                                                                                   nodeId, "user1"));
            NMTokenIdentifier attemptToken2 = GetNMTokenId(secretMgr.CreateNMToken(attempt2,
                                                                                   nodeId, "user2"));

            secretMgr.AppAttemptStartContainer(attemptToken1);
            secretMgr.AppAttemptStartContainer(attemptToken2);
            NUnit.Framework.Assert.IsTrue(secretMgr.IsAppAttemptNMTokenKeyPresent(attempt1));
            NUnit.Framework.Assert.IsTrue(secretMgr.IsAppAttemptNMTokenKeyPresent(attempt2));
            NUnit.Framework.Assert.IsNotNull(secretMgr.RetrievePassword(attemptToken1));
            NUnit.Framework.Assert.IsNotNull(secretMgr.RetrievePassword(attemptToken2));
            // restart and verify key is still there and token still valid
            secretMgr = new NMTokenSecretManagerInNM(stateStore);
            secretMgr.Recover();
            secretMgr.SetNodeId(nodeId);
            NUnit.Framework.Assert.AreEqual(currentKey, secretMgr.GetCurrentKey());
            NUnit.Framework.Assert.IsTrue(secretMgr.IsAppAttemptNMTokenKeyPresent(attempt1));
            NUnit.Framework.Assert.IsTrue(secretMgr.IsAppAttemptNMTokenKeyPresent(attempt2));
            NUnit.Framework.Assert.IsNotNull(secretMgr.RetrievePassword(attemptToken1));
            NUnit.Framework.Assert.IsNotNull(secretMgr.RetrievePassword(attemptToken2));
            // roll master key and remove an app
            currentKey = keygen.GenerateKey();
            secretMgr.SetMasterKey(currentKey);
            secretMgr.AppFinished(attempt1.GetApplicationId());
            // restart and verify attempt1 key is still valid due to prev key persist
            secretMgr = new NMTokenSecretManagerInNM(stateStore);
            secretMgr.Recover();
            secretMgr.SetNodeId(nodeId);
            NUnit.Framework.Assert.AreEqual(currentKey, secretMgr.GetCurrentKey());
            NUnit.Framework.Assert.IsFalse(secretMgr.IsAppAttemptNMTokenKeyPresent(attempt1));
            NUnit.Framework.Assert.IsTrue(secretMgr.IsAppAttemptNMTokenKeyPresent(attempt2));
            NUnit.Framework.Assert.IsNotNull(secretMgr.RetrievePassword(attemptToken1));
            NUnit.Framework.Assert.IsNotNull(secretMgr.RetrievePassword(attemptToken2));
            // roll master key again, restart, and verify attempt1 key is bad but
            // attempt2 is still good due to app key persist
            currentKey = keygen.GenerateKey();
            secretMgr.SetMasterKey(currentKey);
            secretMgr = new NMTokenSecretManagerInNM(stateStore);
            secretMgr.Recover();
            secretMgr.SetNodeId(nodeId);
            NUnit.Framework.Assert.AreEqual(currentKey, secretMgr.GetCurrentKey());
            NUnit.Framework.Assert.IsFalse(secretMgr.IsAppAttemptNMTokenKeyPresent(attempt1));
            NUnit.Framework.Assert.IsTrue(secretMgr.IsAppAttemptNMTokenKeyPresent(attempt2));
            try
            {
                secretMgr.RetrievePassword(attemptToken1);
                NUnit.Framework.Assert.Fail("attempt token should not still be valid");
            }
            catch (SecretManager.InvalidToken)
            {
            }
            // expected
            NUnit.Framework.Assert.IsNotNull(secretMgr.RetrievePassword(attemptToken2));
            // remove last attempt, restart, verify both tokens are now bad
            secretMgr.AppFinished(attempt2.GetApplicationId());
            secretMgr = new NMTokenSecretManagerInNM(stateStore);
            secretMgr.Recover();
            secretMgr.SetNodeId(nodeId);
            NUnit.Framework.Assert.AreEqual(currentKey, secretMgr.GetCurrentKey());
            NUnit.Framework.Assert.IsFalse(secretMgr.IsAppAttemptNMTokenKeyPresent(attempt1));
            NUnit.Framework.Assert.IsFalse(secretMgr.IsAppAttemptNMTokenKeyPresent(attempt2));
            try
            {
                secretMgr.RetrievePassword(attemptToken1);
                NUnit.Framework.Assert.Fail("attempt token should not still be valid");
            }
            catch (SecretManager.InvalidToken)
            {
            }
            // expected
            try
            {
                secretMgr.RetrievePassword(attemptToken2);
                NUnit.Framework.Assert.Fail("attempt token should not still be valid");
            }
            catch (SecretManager.InvalidToken)
            {
            }
            // expected
            stateStore.Close();
        }
예제 #37
0
        protected internal virtual void RegisterWithRM()
        {
            IList <NMContainerStatus>  containerReports = GetNMContainerStatuses();
            RegisterNodeManagerRequest request          = RegisterNodeManagerRequest.NewInstance(nodeId
                                                                                                 , httpPort, totalResource, nodeManagerVersionId, containerReports, GetRunningApplications
                                                                                                     ());

            if (containerReports != null)
            {
                Log.Info("Registering with RM using containers :" + containerReports);
            }
            RegisterNodeManagerResponse regNMResponse = resourceTracker.RegisterNodeManager(request
                                                                                            );

            this.rmIdentifier = regNMResponse.GetRMIdentifier();
            // if the Resourcemanager instructs NM to shutdown.
            if (NodeAction.Shutdown.Equals(regNMResponse.GetNodeAction()))
            {
                string message = "Message from ResourceManager: " + regNMResponse.GetDiagnosticsMessage
                                     ();
                throw new YarnRuntimeException("Recieved SHUTDOWN signal from Resourcemanager ,Registration of NodeManager failed, "
                                               + message);
            }
            // if ResourceManager version is too old then shutdown
            if (!minimumResourceManagerVersion.Equals("NONE"))
            {
                if (minimumResourceManagerVersion.Equals("EqualToNM"))
                {
                    minimumResourceManagerVersion = nodeManagerVersionId;
                }
                string rmVersion = regNMResponse.GetRMVersion();
                if (rmVersion == null)
                {
                    string message = "The Resource Manager's did not return a version. " + "Valid version cannot be checked.";
                    throw new YarnRuntimeException("Shutting down the Node Manager. " + message);
                }
                if (VersionUtil.CompareVersions(rmVersion, minimumResourceManagerVersion) < 0)
                {
                    string message = "The Resource Manager's version (" + rmVersion + ") is less than the minimum "
                                     + "allowed version " + minimumResourceManagerVersion;
                    throw new YarnRuntimeException("Shutting down the Node Manager on RM " + "version error, "
                                                   + message);
                }
            }
            MasterKey masterKey = regNMResponse.GetContainerTokenMasterKey();

            // do this now so that its set before we start heartbeating to RM
            // It is expected that status updater is started by this point and
            // RM gives the shared secret in registration during
            // StatusUpdater#start().
            if (masterKey != null)
            {
                this.context.GetContainerTokenSecretManager().SetMasterKey(masterKey);
            }
            masterKey = regNMResponse.GetNMTokenMasterKey();
            if (masterKey != null)
            {
                this.context.GetNMTokenSecretManager().SetMasterKey(masterKey);
            }
            Log.Info("Registered with ResourceManager as " + this.nodeId + " with total resource of "
                     + this.totalResource);
            Log.Info("Notifying ContainerManager to unblock new container-requests");
            ((ContainerManagerImpl)this.context.GetContainerManager()).SetBlockNewContainerRequests
                (false);
        }