public static void CreateKey()
        {
            Global glob = new Global();

            glob.UnlockBundle("Anything for 30-day trial");

            SshKey key    = new SshKey();
            Rsa    rsaKey = new Rsa();

            rsaKey.GenerateKey(1024);
            _privateKey = rsaKey.ExportPrivateKeyObj();
            Console.WriteLine("Private Key: " + rsaKey.ExportPrivateKey());
            _publicKey = rsaKey.ExportPublicKey();
            Console.WriteLine("Public Key: " + _publicKey);
            using (ConsulClient consulClient = new ConsulClient())
            {
                String url = Constants.BASE_URL + ":" + Constants.CONSUL_PORT;
                Console.WriteLine("Consul URL: " + url);
                consulClient.Config.Address = new Uri(url);
                var putPair = new KVPair("publickey")
                {
                    Value = Encoding.UTF8.GetBytes(_publicKey)
                };
                var putAttempt = consulClient.KV.Put(putPair).Result;
                Console.WriteLine("Put Result: " + JsonConvert.SerializeObject(putAttempt));
            }
            _isCreated = true;
        }
            public void ReturnsFalseWhenTwoKeysHaveDifferentData(string firstKey, string secondKey)
            {
                var key        = new SshKey(firstKey, "somekey");
                var anotherKey = new SshKey(secondKey, "whatever");

                Assert.False(key.HasSameDataAs(anotherKey));
            }
Esempio n. 3
0
        public String AddSshKey(String name, String sshkey)
        {
            var seg  = sshkey.Split();
            var type = seg[0];

            sshkey = seg[1];
            var fingerprint = KeyUtils.GetFingerprint(sshkey);

            var user = User.FindByName(name);

            if (user == null)
            {
                return(null);
            }

            var key = new SshKey
            {
                UserID      = user.ID,
                KeyType     = type,
                Fingerprint = fingerprint,
                PublicKey   = sshkey,
                ImportData  = DateTime.UtcNow,
                LastUse     = DateTime.UtcNow,
            };

            key.Save();

            return(fingerprint);
        }
Esempio n. 4
0
        protected override void ProcessRecord()
        {
            base.ProcessRecord();

            try
            {
                if (sshKeyID != null)
                {
                    SshKey rsSSHKey = RightScale.netClient.SshKey.show(cloudID, sshKeyID, view);
                    WriteObject(rsSSHKey);
                }
                else
                {
                    List <Filter> lstFilter = new List <Filter>();

                    if (filter != null)
                    {
                        Filter fltFilter = Filter.parseFilter(filter);
                        lstFilter.Add(fltFilter);
                    }

                    List <SshKey> rsSSHKeys = RightScale.netClient.SshKey.index(cloudID, lstFilter, view);

                    WriteObject(rsSSHKeys);
                }
            }
            catch (RightScaleAPIException rex)
            {
                WriteObject(rex);
                WriteObject(rex.ErrorData);
            }
        }
            public void ReturnsFalseWhenTwoKeysHaveDifferentData(string firstKey, string secondKey)
            {
                var key = new SshKey(firstKey, "somekey");
                var anotherKey = new SshKey(secondKey, "whatever");

                Assert.False(key.HasSameDataAs(anotherKey));
            }
            public void ReturnsTrueWhenTwoKeysHaveTheSameData()
            {
                var key = new SshKey("ssh-dsa AAAAB3NzaC1yc2EAAAABIwAA", "somekey");
                var anotherKey = new SshKey("ssh-rsa AAAAB3NzaC1yc2EAAAABIwAA", "whatever");

                Assert.True(key.HasSameDataAs(anotherKey));
            }
Esempio n. 7
0
        public string AddSshKey(string name, string sshkey)
        {
            var seg  = sshkey.Split();
            var type = seg[0];

            sshkey = seg[1];
            var fingerprint = KeyUtils.GetFingerprint(sshkey);

            using (var ctx = new GitCandyContext())
            {
                var user = ctx.Users.FirstOrDefault(s => s.Name == name);
                if (user == null)
                {
                    return(null);
                }

                var key = new SshKey
                {
                    UserID      = user.ID,
                    KeyType     = type,
                    Fingerprint = fingerprint,
                    PublicKey   = sshkey,
                    ImportData  = DateTime.UtcNow,
                    LastUse     = DateTime.UtcNow,
                };

                ctx.SshKeys.Add(key);
                ctx.SaveChanges();
            }
            return(fingerprint);
        }
        /// <summary>
        /// Converts an SSH key between .pem and opensshv2 formats
        /// </summary>
        /// <returns>conversion succeeded</returns>
        public bool Convert()
        {
            // get the file contents
            string fileContent = string.Empty;
            using (var reader = new StreamReader(_privateKeyFile))
            {
                fileContent = reader.ReadToEnd();
            }
            // check to see whether this has worked
            var key = new SshKey {Password = _password};
            // get the ssh key
            bool converted = key.FromOpenSshPrivateKey(fileContent);
            // if this hasn't worked then just drop out of this method
            if (!converted)
                return false;
            // update the ssh key
            string content = key.ToOpenSshPrivateKey(false);
            // get the filename without the key extension
            string openSsh2Filename = Path.GetFileNameWithoutExtension(_privateKeyFile) + ".pvk";
            // get the path
            string openSsh2Directory = Path.GetDirectoryName(_privateKeyFile);

            // get the full path
            KeyFilePath = Path.Combine(openSsh2Directory, openSsh2Filename);
            // create the file
            using(var writer = new StreamWriter(File.Create(KeyFilePath)))
            {
                writer.Write(content);
            }
            // if that worked return out of this
            return true;
        }
        /// <summary>
        /// Starts the SFTP server.
        /// </summary>
        protected static void StartSftpServer()
        {
            Dev2Logger.Log.Debug("ServerStartup");
            lock (ServerLock)
            {
                if (Server == null)
                {
                    SshKey rsaKey = SshKey.Generate(SshKeyAlgorithm.RSA, 1024);
                    SshKey dssKey = SshKey.Generate(SshKeyAlgorithm.DSS, 1024);

                    // add keys, bindings and users
                    Server = new SftpServer {
                        Log = Console.Out
                    };
                    Server.Keys.Add(rsaKey);
                    Server.Keys.Add(dssKey);
                    Server.Bindings.Add(IPAddress.Any, 22);
                    if (Directory.Exists(@"C:\Temp\SFTP"))
                    {
                        Directory.Delete(@"C:\Temp\SFTP", true);
                    }
                    Directory.CreateDirectory(@"C:\Temp\SFTP");
                    Server.Users.Add(new SshUser("dev2", "Q/ulw&]", @"C:\Temp\SFTP"));
                    // start the server
                    Server.Start();
                }
            }
        }
            public void ReturnsTrueWhenTwoKeysHaveTheSameData()
            {
                var key        = new SshKey("ssh-dsa AAAAB3NzaC1yc2EAAAABIwAA", "somekey");
                var anotherKey = new SshKey("ssh-rsa AAAAB3NzaC1yc2EAAAABIwAA", "whatever");

                Assert.True(key.HasSameDataAs(anotherKey));
            }
Esempio n. 11
0
        public Boolean CanWriteRepository(String owner, String reponame, String fingerprint, String publickey)
        {
            var repo = Repository.FindByOwnerAndName(owner, reponame);

            if (repo == null)
            {
                return(false);
            }
            if (repo.AllowAnonymousRead && repo.AllowAnonymousWrite)
            {
                return(true);
            }

            var ssh = SshKey.FindByFingerprint(fingerprint);

            if (ssh == null || ssh.PublicKey != publickey)
            {
                return(false);
            }

            var user = ssh.User;

            if (user == null)
            {
                return(false);
            }
            if (user.IsAdmin)
            {
                return(true);
            }

            return(CheckReadWrite(repo, user, true));
        }
            public void ReturnsFalseWhenCompareKeyIsNull()
            {
                var key = new SshKey {
                    Key = "ssh-dsa AAAAB3NzaC1yc2EAAAABIwAA", Title = "somekey"
                };

                Assert.False(key.HasSameDataAs(null));
            }
            public void CanParseKeyData(string raw, string data, string name)
            {
                var key = new SshKey(raw);

                SshKeyInfo keyInfo = key.GetKeyDataAndName();
                Assert.Equal(data, keyInfo.Data);
                Assert.Equal(name, keyInfo.Name);
            }
        public static Meziantou.GitLab.SshKeyIdRef FromSshKey(SshKey sshKey)
        {
            if ((sshKey == null))
            {
                throw new System.ArgumentNullException(nameof(sshKey));
            }

            return(new Meziantou.GitLab.SshKeyIdRef(sshKey));
        }
Esempio n. 15
0
 private void OnSsh(SshKey sshKey)
 {
     runningProcesses.Clear();
     runningProcesses.AddRange(HostHandler.I.currentHost.GetComponentsInChildren <IProcess>());
     foreach (IProcess process in runningProcesses)
     {
         process.SetPid(GetUniquePid());
     }
 }
        public async Task <SshKey> CreateUserSshKeyAsync(string userName, SshKey sshKey)
        {
            var response = await GetUsersUrl()
                           .AppendPathSegment($"/{userName}/ssh-keys")
                           .PostJsonAsync(sshKey)
                           .ConfigureAwait(false);

            return(await HandleResponseAsync <SshKey>(response).ConfigureAwait(false));
        }
            public void CanParseKeyData(string raw, string data, string name)
            {
                var key = new SshKey(raw);

                SshKeyInfo keyInfo = key.GetKeyDataAndName();

                Assert.Equal(data, keyInfo.Data);
                Assert.Equal(name, keyInfo.Name);
            }
        private SshKeyIdRef(SshKey sshKey)
        {
            if ((sshKey == null))
            {
                throw new System.ArgumentNullException(nameof(sshKey));
            }

            this._value = sshKey.Id;
        }
Esempio n. 19
0
 public void OnSsh(SshKey sshKey)
 {
     exploredHosts.Add(currentHost);
     Player.I.MoveTo(sshKey.GetHost().GetRootDirectory());
     currentHost = sshKey.GetHost();
     currentHost.SetUser(sshKey.GetUser());
     currentHost.Init(exploredHosts.Count + 1);
     onSsh.Invoke(sshKey);
 }
Esempio n. 20
0
        private ClusterMessage GenerateDeleteQueueMessage(Cluster cluster, SshKey selectedSshKey, DatacenterNode selectedNode, int baseIp, int baseId)
        {
            var message = new ClusterMessage()
            {
                Pattern = "delete",
                Data    = new Data()
                {
                    Id     = baseId,
                    Name   = cluster.Name,
                    Config = new Config()
                    {
                        User     = "******",
                        Password = "******",
                        Ssh      = new Ssh()
                        {
                            PrivateKey = selectedSshKey.Pem,
                            PublicKey  = selectedSshKey.Public
                        }
                    },
                    Nodes = new List <Node>()
                }
            };

            var master = new Node()
            {
                Id          = baseId,
                CpuCores    = 2,
                Master      = true,
                Disk        = 30,
                Memory      = 2048,
                Ip          = $"10.0.{selectedNode.Id}.{baseIp}",
                ProxmoxNode = selectedNode.Name,
                Template    = cluster.BaseTemplate
            };

            message.Data.Nodes.Add(master);

            for (var i = 0; i < cluster.Node; i++)
            {
                var node = new Node()
                {
                    Id          = baseId + i + 1,
                    CpuCores    = cluster.Cpu,
                    Master      = false,
                    Disk        = cluster.Storage,
                    Memory      = cluster.Memory,
                    Ip          = $"10.0.{selectedNode.Id}.{baseIp + i + 1}",
                    ProxmoxNode = selectedNode.Name,
                    Template    = cluster.BaseTemplate
                };

                message.Data.Nodes.Add(node);
            }

            return(message);
        }
Esempio n. 21
0
        public void sshIndexSimple()
        {
            netClient.Core.APIClient.Instance.InitWebClient();
            netClient.Core.APIClient.Instance.Authenticate(this.authUserName, this.authPassword, this.accountID);

            List <SshKey> sshKeys = SshKey.index(this.awsUSEastCloudID);

            Assert.IsNotNull(sshKeys);
            Assert.IsTrue(sshKeys.Count > 0);

            netClient.Core.APIClient.Instance.InitWebClient();
        }
Esempio n. 22
0
    public IEnumerator Run()
    {
        sshKey = gameObject.AddComponent <SshKey>();
        yield return(1);

        TrimFolders();
        yield return(1);

        RegisterDirectoryTypes();
        AddChallenges();
        AddPickups();
    }
Esempio n. 23
0
    public override bool Run(out string result, ParsedCommand parsedCommand)
    {
        if (!base.Run(out result, parsedCommand))
        {
            return(false);
        }
        result = $"ssh to {parsedCommand.arguments[0]}, please wait...";
        SshKey sshKey = HostHandler.I.currentHost.GetComponent <SshKey>();

        HostHandler.I.OnSsh(sshKey);
        return(true);
    }
Esempio n. 24
0
        public void Modify(ModifyCallback action)
        {
            Dictionary <string, SshKey> keys = new Dictionary <string, SshKey>();

            File.Copy(this.Filename, this.Filename + ".bak");
            try
            {
                using (StreamReader sr = new StreamReader(this.Filename))
                {
                    while (!sr.EndOfStream)
                    {
                        string line = sr.ReadLine();
                        if (!string.IsNullOrEmpty(line))
                        {
                            if (line.Trim() != string.Empty)
                            {
                                string[] values = line.Split(' ');
                                SshKey   sshKey = new SshKey()
                                {
                                    Type = values[0], Key = values[1], Comment = values[2]
                                };
                                keys[sshKey.Comment] = sshKey;
                            }
                        }
                    }
                }
                Dictionary <string, SshKey> oldKeys = new Dictionary <string, SshKey>(keys);

                action(keys);

                // TODO compare new keys with old keys before overwriting

                using (File.Create(this.Filename)) { }
                using (StreamWriter sw = new StreamWriter(this.Filename))
                {
                    foreach (SshKey value in keys.Values)
                    {
                        sw.WriteLine(string.Format("{0} {1} {2}", value.Type, value.Key, value.Comment));
                    }
                }
            }
            catch (Exception ex)
            {
                File.Copy(this.Filename + ".bak", this.Filename, true);
                throw ex;
            }
            finally
            {
                File.Delete(this.Filename + ".bak");
            }
        }
Esempio n. 25
0
        /// <summary>
        /// TfeClient
        /// </summary>
        /// <param name="config"></param>
        public TfeClient(TfeConfig config)
        {
            this.client = config.HttpClient;

            Apply              = new Apply(client);
            Organization       = new Organization(client);
            SshKey             = new SshKey(client);
            Run                = new Run(client);
            Workspace          = new Workspace(client);
            WorkspaceVariable  = new WorkspaceVariable(client);
            OAuthClient        = new OAuthClient(client);
            StateVersion       = new StateVersion(client);
            StateVersionOutput = new StateVersionOutput(client);
        }
        public static SshKeyPair Generate(int bits)
        {
            SshKey key        = new SshKey();
            int    numBits    = bits;
            int    exponent   = 65537;
            bool   success    = key.GenerateRsaKey(numBits, exponent);
            var    sshKeyPair = new SshKeyPair(key.ToOpenSshPublicKey(), key.ToOpenSshPrivateKey(false));

            if (!success)
            {
                Generate(bits);
            }
            return(sshKeyPair);
        }
Esempio n. 27
0
        public void instaneSSHKey()
        {
            List <Instance> instanceList = Instance.index(cloudID);

            Assert.IsNotNull(instanceList);
            Assert.IsTrue(instanceList.Count > 0);
            string   instanceID   = instanceList[0].ID;
            Instance testInstance = Instance.show(cloudID, instanceID, "full");

            Assert.IsNotNull(testInstance);
            SshKey ssh = testInstance.sshKey;

            Assert.IsTrue(true);//no exception
        }
Esempio n. 28
0
 public void ReplaceKeys(List <SshKey> newKeys)
 {
     Modify(delegate(Dictionary <string, SshKey> keys)
     {
         keys.Clear();
         foreach (SshKey key in newKeys)
         {
             string id = KeyId(key.Comment);
             keys[id]  = new SshKey()
             {
                 Comment = key.Comment, Key = key.Key, Type = key.Type
             };
         }
     });
 }
Esempio n. 29
0
        static AgentClientTest()
        {
            rsa1Key = KeyGenerator.CreateKey(SshVersion.SSH1,
                                             PublicKeyAlgorithm.SSH_RSA, "SSH1 RSA test key");
            rsaKey = KeyGenerator.CreateKey(SshVersion.SSH2,
                                            PublicKeyAlgorithm.SSH_RSA, "SSH2 RSA test key");
            rsaCert = KeyGenerator.CreateKey(SshVersion.SSH2,
                                             PublicKeyAlgorithm.SSH_RSA_CERT_V1, "SSH2 RSA test key + cert");
            dsaKey = KeyGenerator.CreateKey(SshVersion.SSH2,
                                            PublicKeyAlgorithm.SSH_DSS, "SSH2 DSA test key");
            dsaCert = KeyGenerator.CreateKey(SshVersion.SSH2,
                                             PublicKeyAlgorithm.SSH_DSS_CERT_V1, "SSH2 DSA test key + cert");
            ecdsa256Key = KeyGenerator.CreateKey(SshVersion.SSH2,
                                                 PublicKeyAlgorithm.ECDSA_SHA2_NISTP256, "SSH2 ECDSA 256 test key");
            ecdsa256Cert = KeyGenerator.CreateKey(SshVersion.SSH2,
                                                  PublicKeyAlgorithm.ECDSA_SHA2_NISTP256_CERT_V1, "SSH2 ECDSA 256 test key + cert");
            ecdsa384Key = KeyGenerator.CreateKey(SshVersion.SSH2,
                                                 PublicKeyAlgorithm.ECDSA_SHA2_NISTP384, "SSH2 ECDSA 384 test key");
            ecdsa384Cert = KeyGenerator.CreateKey(SshVersion.SSH2,
                                                  PublicKeyAlgorithm.ECDSA_SHA2_NISTP384_CERT_V1, "SSH2 ECDSA 384 test key + cert");
            ecdsa521Key = KeyGenerator.CreateKey(SshVersion.SSH2,
                                                 PublicKeyAlgorithm.ECDSA_SHA2_NISTP521, "SSH2 ECDSA 521 test key");
            ecdsa521Cert = KeyGenerator.CreateKey(SshVersion.SSH2,
                                                  PublicKeyAlgorithm.ECDSA_SHA2_NISTP521_CERT_V1, "SSH2 ECDSA 521 test key + cert");
            ed25519Key = KeyGenerator.CreateKey(SshVersion.SSH2,
                                                PublicKeyAlgorithm.ED25519, "SSH2 Ed25519 test key");
            ed25519Cert = KeyGenerator.CreateKey(SshVersion.SSH2,
                                                 PublicKeyAlgorithm.ED25519_CERT_V1, "SSH2 Ed25519 test key + cert");

            List <SshKey> keyList = new List <SshKey>();

            keyList.Add(rsa1Key);
            keyList.Add(rsaKey);
            keyList.Add(rsaCert);
            keyList.Add(dsaKey);
            keyList.Add(dsaCert);
            keyList.Add(ecdsa256Key);
            keyList.Add(ecdsa256Cert);
            keyList.Add(ecdsa384Key);
            keyList.Add(ecdsa384Cert);
            keyList.Add(ecdsa521Key);
            keyList.Add(ecdsa521Cert);
            keyList.Add(ed25519Key);
            keyList.Add(ed25519Cert);
            allKeys = keyList.AsReadOnly();
        }
Esempio n. 30
0
        private async Task <bool> ImportRsaPublicKey(SshKeyCreateRequest request)
        {
            var importedKey = sshKey.FromOpenSshPublicKey(request.Public);
            var keyToInsert = new SshKey()
            {
                Fingerprint = sshKey.GenFingerprint(),
                Name        = request.Name,
                Public      = request.Public
            };

            if ((await sshKeyRepository.InsertAsync(keyToInsert)) > 0)
            {
                logger.LogInformation("Key insert.");

                return(true);
            }

            return(false);
        }
Esempio n. 31
0
        public void TestFormatSignature()
        {
            var random  = new Random();
            var dsa_key = new SshKey(SshVersion.SSH2, new DsaPublicKeyParameters(
                                         new BigInteger("1"),
                                         new DsaParameters(new BigInteger("2"), new BigInteger("3"),
                                                           new BigInteger("4"))));

            // test that dsa signature works when values are not full 20 bytes.
            byte[] r_bytes = new byte[19];
            byte[] s_bytes = new byte[19];
            random.NextBytes(r_bytes);
            random.NextBytes(s_bytes);
            var r         = new DerInteger(r_bytes);
            var s         = new DerInteger(s_bytes);
            var sequence  = new DerSequence(r, s);
            var signature = dsa_key.FormatSignature(sequence.GetEncoded());

            Assert.That(signature.Count(), Is.EqualTo(40));
        }
Esempio n. 32
0
        private async Task <bool> GenerateNewRsaKey(SshKeyCreateRequest request)
        {
            var    numBits = 2048;
            var    exponent = 65537;
            var    success = sshKey.GenerateRsaKey(numBits, exponent);
            string exportedPrivateKey, exportedPublicKey, exportedPpkKey;
            bool   exportEncrypted;

            if (success != true)
            {
                logger.LogDebug("Bad params passed to RSA key generation method.");
                return(false);
            }

            //  Export the RSA private key to OpenSSH, PuTTY, and XML and save.
            exportEncrypted = false;

            var fingerprint = sshKey.GenFingerprint();

            exportedPrivateKey = sshKey.ToOpenSshPrivateKey(exportEncrypted);
            exportedPpkKey     = sshKey.ToPuttyPrivateKey(exportEncrypted);
            exportedPublicKey  = sshKey.ToOpenSshPublicKey();

            var keyToInsert = new SshKey()
            {
                Fingerprint = fingerprint,
                Name        = request.Name,
                Pem         = exportedPrivateKey,
                Private     = exportedPpkKey,
                Public      = exportedPublicKey
            };

            if ((await sshKeyRepository.InsertAsync(keyToInsert)) > 0)
            {
                logger.LogInformation("Key insert.");

                return(true);
            }

            return(false);
        }
Esempio n. 33
0
        public void DeleteSshKey(String name, String sshkey)
        {
            var user = User.FindByName(name);

            if (user == null)
            {
                return;
            }

            var key = SshKey.FindByUserID(user.ID);

            if (key == null)
            {
                return;
            }

            if (key.Fingerprint == sshkey)
            {
                key.Delete();
            }
        }
Esempio n. 34
0
        public void sshCreateIndexShowDestroy()
        {
            netClient.Core.APIClient.Instance.InitWebClient();
            netClient.Core.APIClient.Instance.Authenticate(this.authUserName, this.authPassword, this.accountID);

            List <SshKey> sshKeys = SshKey.index(this.awsUSEastCloudID);

            Assert.IsNotNull(sshKeys);
            Assert.IsTrue(sshKeys.Count > 0);

            string sshID = SshKey.create(this.awsUSEastCloudID, this.testSSHKeyName);

            Assert.IsNotNull(sshID);
            Assert.IsTrue(sshID.Length > 0);

            SshKey showTest = SshKey.show(this.awsUSEastCloudID, sshID);

            Assert.IsNotNull(showTest);
            Assert.IsTrue(showTest.ID == sshID);

            List <SshKey> newSshKeys = SshKey.index(this.awsUSEastCloudID);

            Assert.IsNotNull(newSshKeys);
            Assert.IsTrue(newSshKeys.Count > 0);

            Assert.IsTrue(newSshKeys.Count > sshKeys.Count);

            bool isDestroyed = SshKey.destroy(this.awsUSEastCloudID, sshID);

            Assert.IsTrue(isDestroyed);

            List <SshKey> backToNormalSSHKeys = SshKey.index(this.awsUSEastCloudID);

            Assert.IsNotNull(backToNormalSSHKeys);
            Assert.IsTrue(backToNormalSSHKeys.Count > 0);

            Assert.IsTrue(backToNormalSSHKeys.Count == sshKeys.Count);

            netClient.Core.APIClient.Instance.InitWebClient();
        }
            public void ReturnsFalseWhenCompareKeyIsNull()
            {
                var key = new SshKey("ssh-dsa AAAAB3NzaC1yc2EAAAABIwAA", "somekey");

                Assert.False(key.HasSameDataAs(null));
            }