Exemple #1
0
        public IActionResult Get(int keySizeInBits)
        {
            byte[] privateKeyBytes;
            byte[] publicKeyBytes;

            byte[] rsaPublicPKCS1Bytes;


            var keygen = new SshKeyGenerator.SshKeyGenerator(keySizeInBits);

            string privateKey = keygen.ToPrivateKey();
            string publicKey  = keygen.ToPublicKey();
            string sshPubKey  = keygen.ToRfcPublicKey();

            privateKeyBytes     = Encoding.Default.GetBytes(privateKey);
            publicKeyBytes      = Encoding.Default.GetBytes(publicKey);
            rsaPublicPKCS1Bytes = Encoding.Default.GetBytes(sshPubKey);



            MemoryFile mfPriv   = new MemoryFile($"{KEYTYPE}-{keySizeInBits}bits-private-key.pem", privateKeyBytes);
            MemoryFile mfPublic = new MemoryFile($"{KEYTYPE}-{keySizeInBits}bits-public-key.pem", publicKeyBytes);
            MemoryFile mfRSAPublicPKCS1Bytes = new MemoryFile($"{KEYTYPE}-{keySizeInBits}bits-public-ssh-key.pem", rsaPublicPKCS1Bytes);

            byte[] zipBytes = ZipMemoryFile.ZipItAllFromAndToMemory(CompressionLevel.Optimal, mfPriv, mfPublic, mfRSAPublicPKCS1Bytes);

            var result = new FileContentResult(zipBytes, "application/zip")
            {
                FileDownloadName = $"RSA-keypair-{keySizeInBits}bits.zip"
            };

            return(result);
        }
Exemple #2
0
        static void Main(string[] args)
        {
            var keygen = new SshKeyGenerator.SshKeyGenerator(2048);

            var privateKey = keygen.ToPrivateKey();

            Console.WriteLine(privateKey);

            var publicSshKey = keygen.ToRfcPublicKey();

            Console.WriteLine(publicSshKey);

            var publicSshKeyWithComment = keygen.ToRfcPublicKey("*****@*****.**");

            Console.WriteLine(publicSshKeyWithComment);
        }
Exemple #3
0
        public static async Task <IActionResult> Run(
            [HttpTrigger(AuthorizationLevel.Function, "get", Route = null)] HttpRequest req,
            ILogger log)
        {
            string passwordGenerated = string.Empty;

            /* Uncomment below code if log analytics push is to be done*/
            #region dynamic jobject creation for log analytics logs
            // dynamic jObject = new JObject();
            // jObject.LogFileName = ConstantsHelper.GetEnvironmentVariable(ConstantsHelper.logName);
            // jObject.AutomationName = "Reusable";
            // jObject.ModuleName = "GenerateSSHKey";
            // dynamic logJObject = new JObject();
            #endregion

            log.LogInformation("GenerateSSHKey Function is called");
            /* Uncomment below code if log analytics push is to be done*/
            //logJObject.LogInformation = "GenerateSSHKey Function is called";

            try
            {
                int keyBits = 2048;
                //get VM Name for which key needs to be generated
                string keyComment = req.Query["VMName"];
                if (!String.IsNullOrEmpty(keyComment))
                {
                    string  requestBody = await new StreamReader(req.Body).ReadToEndAsync();
                    dynamic data        = JsonConvert.DeserializeObject(requestBody);
                    keyComment = keyComment ?? data?.VMName;
                    keyComment = keyComment + "-" + DateTime.Now.ToShortDateString();

                    //Generate new SSH Keys
                    var generator = new SshKeyGenerator.SshKeyGenerator(keyBits);

                    if (generator != null)
                    {
                        SSHKeyPair generatedPair = new SSHKeyPair();
                        generatedPair.SSHPrivateKey = generator.ToPrivateKey();
                        generatedPair.SSHPublicKey  = generator.ToRfcPublicKey(keyComment);
                        log.LogInformation("Keys have been generated.");
                        /* Uncomment below code if log analytics push is to be done*/
                        //logJObject.LogInformation += "\n Keys have been generated.";
                        return(new OkObjectResult(JsonConvert.SerializeObject(generatedPair)));
                    }
                    else
                    {
                        log.LogInformation("Exception has been occured in GenerateSSHKey. Please check Function logs under Monitor.");
                        /* Uncomment below code if log analytics push is to be done*/
                        //logJObject.LogInformation += "\n Exception has been occured in GenerateSSHKey. Please check Function logs under Monitor.";
                        return(new NotFoundObjectResult("error result"));
                    }
                }
                else
                {
                    return(new OkObjectResult(JsonConvert.SerializeObject("Please provide a VM Name for which SSH Keys are to be generated.")));
                }
            }
            catch (Exception ex)
            {
                log.LogInformation($"GenerateSSHKey got Exception Time: { DateTime.Now} Exception{ ex.Message}");
                /* Uncomment below code if log analytics push is to be done*/
                //logJObject.LogInformation += $"\n GenerateSSHKey got Exception Time: { DateTime.Now} Exception{ ex.Message}";
                return(new NotFoundObjectResult(""));
            }
            /* Uncomment below code if log analytics push is to be done*/
            #region finally block for pushing logs into log analytics workspace
            // finally
            // {
            //     using(var client = new HttpClient())
            //     {
            //         string logJson = logJObject.ToString(Newtonsoft.Json.Formatting.None);
            //         jObject.LogData = logJson;
            //         string myJson = jObject.ToString(Newtonsoft.Json.Formatting.None);
            //         //Invoking PushLogsToLogAnalytics API for logging in Log Analytics
            //         client.DefaultRequestHeaders.Add(ConstantsHelper.ocp_Apim_Subscription_Key, ConstantsHelper.GetEnvironmentVariable(ConstantsHelper.ocp_Apim_Subscription_Key));
            //         var response = await client.PostAsync(ConstantsHelper.GetEnvironmentVariable(ConstantsHelper.PushLogsToLogAnalyticsAPI), new StringContent(myJson, System.Text.Encoding.UTF8, "application/json"));
            //         if (response.StatusCode == System.Net.HttpStatusCode.OK)
            //         {

            //             log.LogInformation("Logging is completed successfully with status code : " +response.StatusCode);
            //         }
            //         else
            //         {
            //             log.LogInformation("Logging is failed with status code : " + response.StatusCode);
            //         }
            //     }
            // }
            #endregion
        }
Exemple #4
0
        public async Task <bool> BatchCreateUsersFromCSV(UserFile userFile, SemesterDto semester)
        {
            using (var reader = new StreamReader(userFile.FilePath))
                using (var csv = new CsvReader(reader, CultureInfo.InvariantCulture))
                {
                    //csv.Configuration.PrepareHeaderForMatch = (string header, int index) => header.ToLower();
                    var records = csv.GetRecords <ClassListDto>();

                    foreach (var record in records.ToList())
                    {
                        var props = record.GetType().GetProperties();
                        // var sb = new StringBuilder();
                        foreach (var p in props)
                        {
                            //System.Console.WriteLine(p.Name + ": " + p.GetValue(record, null));
                            // sb.AppendLine(p.Name + ": " + p.GetValue(obj, null));
                        }

                        // System.Console.WriteLine("!!!" + record.MAJOR);
                        // return sb.ToString();

                        // Check if it is a new user
                        if (!string.IsNullOrEmpty(record.STUDENT_ID) &&
                            !await this.userManager.Users.AnyAsync(x => x.UserName == "siu" + record.STUDENT_ID))
                        {
                            // System.Console.WriteLine("siu" + record.STUDENT_ID + " doesn't exist.");

                            if (Int32.TryParse(record.STUDENT_ID, out int siuDawgTag))
                            {
                                var user = new AppUser
                                {
                                    UserName            = "******" + record.STUDENT_ID.ToLower(),
                                    KnownAs             = record.STUDENT_NAME,
                                    EmailSIU            = record.INTERNET_ADDRESS,
                                    PrimaryMajor        = record.MAJOR,
                                    PrimaryMajorProgram = record.PROGRAM,
                                    DawgTag             = siuDawgTag,
                                    CLASS_LEVEL_BOAP    = record.CLASS_LEVEL_BOAP,
                                    EnrollmentStartYear = semester.Year,
                                    EnrollmentStartTerm = semester.Term,
                                    AccessPermitted     = true
                                };

                                // Assign public ssh key
                                var keygen       = new SshKeyGenerator.SshKeyGenerator(2048);
                                var privateKey   = keygen.ToPrivateKey();
                                var publicSshKey = keygen.ToRfcPublicKey();

                                user.PrivateKeySSH1 = privateKey;
                                user.PublicKeySSH1  = publicSshKey;
                                user.PrivateKeySSH2 = privateKey;
                                user.PublicKeySSH2  = publicSshKey;

                                // Create web user personal url
                                System.Console.WriteLine(sshServer.Pc00host);
                                System.Console.WriteLine(sshServer.Pc00port);
                                System.Console.WriteLine(sshServer.Pc00user);
                                System.Console.WriteLine(sshServer.Pc00passwd);
                                var    client  = this.setupConnection(sshServer.Pc00host, sshServer.Pc00port, sshServer.Pc00user, sshServer.Pc00passwd);
                                string command = $"sudo -H -u {user.UserName} bash -c 'mkdir -p ~/.ssh; echo \"{user.PublicKeySSH1}\" > ~/.ssh/authorized_keys; chmod 644 ~/.ssh/authorized_keys; echo \"{user.PublicKeySSH1}\" > ~/.ssh/id_rsa.pub; chmod 644 ~/.ssh/id_rsa.pub; echo \"{user.PrivateKeySSH1}\" > ~/.ssh/id_rsa; chmod 600 ~/.ssh/id_rsa'";
                                var    retCode = await this.RunClientCommandAsync(client, command);

                                client.Disconnect();

                                if (retCode != 0)
                                {
                                    return(false);
                                }

                                client  = this.setupConnection(sshServer.Pc01host, sshServer.Pc01port, sshServer.Pc01user, sshServer.Pc01passwd);
                                command = $"sudo -H -u {user.UserName} bash -c 'mkdir -p ~/.ssh; echo \"{user.PublicKeySSH1}\" > ~/.ssh/authorized_keys; chmod 644 ~/.ssh/authorized_keys; echo \"{user.PublicKeySSH1}\" > ~/.ssh/id_rsa.pub; chmod 644 ~/.ssh/id_rsa.pub; echo \"{user.PrivateKeySSH1}\" > ~/.ssh/id_rsa; chmod 600 ~/.ssh/id_rsa'";
                                retCode = await this.RunClientCommandAsync(client, command);

                                client.Disconnect();

                                if (retCode != 0)
                                {
                                    return(false);
                                }

                                // Transfer keys to server for their Personal URL User
                                // if( ! await this.accountService.IssueUserWebKeysAsync(user.PersonalURL, publicSshKey, privateKey)) {
                                //     return false;
                                // }
                                // End assign public ssh key

                                var tempPassword = "******";
                                var result       = await userManager.CreateAsync(user, tempPassword);

                                if (!result.Succeeded)
                                {
                                    return(false);
                                }

                                var roleResult = await userManager.AddToRoleAsync(user, "Member");

                                if (!roleResult.Succeeded)
                                {
                                    return(false);
                                }

                                System.Console.WriteLine("siu" + record.STUDENT_ID + " added.");
                            }
                        }
                    }
                    return(true);
                }
        }
Exemple #5
0
        public async Task <ActionResult <MemberSshKeysDto> > GenerateNewSshKeys()
        {
            // Get username From token (can't trust client)
            //var username = User.FindFirst(ClaimTypes.NameIdentifier)?.Value;
            // var username = User.GetUsername();
            var username = User.GetUsername();
            // var username = memberUpdateDto.Username;

            var user = await this.unitOfWork.UserRepository.GetUserByUsernameAsync(username);

            // Use Automapper to make from memberUpdateDto to AppUser
            // this.mapper.Map(memberUpdateDto, user);

            user.PublicKeySSH1  = null;
            user.PrivateKeySSH1 = null;

            var keygen = new SshKeyGenerator.SshKeyGenerator(2048);

            var privateKey = keygen.ToPrivateKey();
            // Console.WriteLine(privateKey);

            var publicSshKey = keygen.ToRfcPublicKey();
            // Console.WriteLine(publicSshKey);

            var comment = user.UserName + "@www2.cs.siu.edu";
            var publicSshKeyWithComment = keygen.ToRfcPublicKey(comment);

            // var publicSshKeyWithComment = keygen.ToRfcPublicKey("*****@*****.**");
            // Console.WriteLine(publicSshKeyWithComment);

            user.PrivateKeySSH1 = privateKey;
            user.PublicKeySSH1  = publicSshKey;
            // user.PublicKeySSH1 = publicSshKeyWithComment;

            user.PrivateKeySSH2 = privateKey;
            user.PublicKeySSH2  = publicSshKey;

            this.unitOfWork.UserRepository.Update(user);

            // Transfer keys to server
            // if( ! await this.accountService.IssueUserKeysAsync(user.UserName, publicSshKeyWithComment, privateKey)) {
            if (!await this.accountService.IssueUserKeysAsync(user.UserName, publicSshKey, privateKey))
            {
                // System.Console.WriteLine($"{loginDto.Username} {loginDto.Password}");
                return(BadRequest("Unable to assign ssh keys"));
            }

            // Transfer keys to server for their Personal User
            if (!await this.accountService.IssueUserWebKeysAsync(user.PersonalURL, publicSshKey, privateKey))
            {
                // System.Console.WriteLine($"{loginDto.Username} {loginDto.Password}");
                return(BadRequest("Unable to assign ssh keys"));
            }

            if (await this.unitOfWork.Complete())
            {
                // return NoContent();
                var user2 = await this.unitOfWork.UserRepository.GetMemberSshKeysAsync(user.Id);

                return(Ok(user2));
            }


            return(BadRequest("Failed to update user."));
        }