예제 #1
0
        private Task ListManagedCompanies(string _)
        {
            var tab = new Tabulate(6);

            tab.AddHeader("Company Name", "Company ID", "License", "# Seats", "# Users", "Paused");
            foreach (var mc in _managedCompanies)
            {
                tab.AddRow(mc.McEnterpriseName, mc.McEnterpriseId, mc.ProductId,
                           mc.NumberOfSeats, mc.NumberOfUsers, mc.Paused ? "Yes" : "");
            }
            tab.Sort(0);
            tab.DumpRowNo = true;
            tab.Dump();
            return(Task.CompletedTask);
        }
예제 #2
0
        internal static async Task RunAuditEventsReport(this IEnterpriseContext context, AuditReportOptions options)
        {
            if (context.AuditEvents == null)
            {
                var auditEvents = await context.Enterprise.Auth.GetAvailableEvents();

                lock (context)
                {
                    context.AuditEvents = new ConcurrentDictionary <string, AuditEventType>();
                    foreach (var evt in auditEvents)
                    {
                        context.AuditEvents[evt.Name] = evt;
                    }
                }
            }

            var filter = new ReportFilter();

            if (!string.IsNullOrEmpty(options.Created))
            {
                filter.Created = ParseDateCreatedFilter(options.Created);
            }

            if (options.EventType != null && options.EventType.Any())
            {
                filter.EventTypes = options.EventType.ToArray();
            }

            if (!string.IsNullOrEmpty(options.Username))
            {
                filter.Username = options.Username;
            }

            if (!string.IsNullOrEmpty(options.RecordUid))
            {
                filter.RecordUid = options.RecordUid;
            }

            if (!string.IsNullOrEmpty(options.SharedFolderUid))
            {
                filter.SharedFolderUid = options.SharedFolderUid;
            }

            var rq = new GetAuditEventReportsCommand
            {
                Filter = filter,
                Limit  = options.Limit,
            };

            var rs = await context.Enterprise.Auth.ExecuteAuthCommand <GetAuditEventReportsCommand, GetAuditEventReportsResponse>(rq);

            var tab = new Tabulate(4)
            {
                DumpRowNo = true
            };

            tab.AddHeader("Created", "Username", "Event", "Message");
            tab.MaxColumnWidth = 100;
            foreach (var evt in rs.Events)
            {
                if (!evt.TryGetValue("audit_event_type", out var v))
                {
                    continue;
                }
                var eventName = v.ToString();
                if (!context.AuditEvents.TryGetValue(eventName, out var eventType))
                {
                    continue;
                }

                var message = eventType.SyslogMessage;
                do
                {
                    var match = Regex.Match(message, ParameterPattern);
                    if (!match.Success)
                    {
                        break;
                    }
                    if (match.Groups.Count != 2)
                    {
                        break;
                    }
                    var parameter = match.Groups[1].Value;
                    var value     = "";
                    if (evt.TryGetValue(parameter, out v))
                    {
                        value = v.ToString();
                    }

                    message = message.Remove(match.Groups[0].Index, match.Groups[0].Length);
                    message = message.Insert(match.Groups[0].Index, value);
                } while (true);
                var created = "";
                if (evt.TryGetValue("created", out v))
                {
                    created = v.ToString();
                    if (long.TryParse(created, out var epoch))
                    {
                        created = DateTimeOffset.FromUnixTimeSeconds(epoch).ToString("G");
                    }
                }
                var username = "";
                if (evt.TryGetValue("username", out v))
                {
                    username = v.ToString();
                }
                tab.AddRow(created, username, eventName, message);
            }
            tab.Dump();
        }
예제 #3
0
        public static async Task EnterpriseDeviceCommand(this IEnterpriseContext context, EnterpriseDeviceOptions arguments)
        {
            if (arguments.AutoApprove.HasValue)
            {
                context.AutoApproveAdminRequests = arguments.AutoApprove.Value;
                Console.WriteLine($"Automatic Admin Device Approval is {(context.AutoApproveAdminRequests ? "ON" : "OFF")}");
            }

            if (string.IsNullOrEmpty(arguments.Command))
            {
                arguments.Command = "list";
            }

            if (arguments.Force || context.DeviceForAdminApprovals == null)
            {
                await context.GetEnterpriseData("devices_request_for_admin_approval");
            }

            if (context.DeviceForAdminApprovals == null || context.DeviceForAdminApprovals.Length == 0)
            {
                Console.WriteLine("There are no pending devices");
                return;
            }

            var cmd = arguments.Command.ToLowerInvariant();

            switch (cmd)
            {
            case "list":
                var tab = new Tabulate(4)
                {
                    DumpRowNo = false
                };
                Console.WriteLine();
                tab.AddHeader("Email", "Device ID", "Device Name", "Client Version");
                foreach (var device in context.DeviceForAdminApprovals)
                {
                    if (!context.Enterprise.TryGetUserById(device.EnterpriseUserId, out var user))
                    {
                        continue;
                    }

                    var deiceToken = device.EncryptedDeviceToken.Base64UrlDecode();
                    tab.AddRow(user.Email, deiceToken.TokenToString(), device.DeviceName, device.ClientVersion);
                }

                tab.Sort(1);
                tab.Dump();
                break;

            case "approve":
            case "deny":
                if (string.IsNullOrEmpty(arguments.Match))
                {
                    Console.WriteLine($"{arguments.Command} command requires device ID or user email parameter.");
                }
                else
                {
                    var devices = context.DeviceForAdminApprovals
                                  .Where(x =>
                    {
                        if (arguments.Match == "all")
                        {
                            return(true);
                        }
                        var deviceToken = x.EncryptedDeviceToken.Base64UrlDecode();
                        var deviceId    = deviceToken.TokenToString();
                        if (deviceId.StartsWith(arguments.Match))
                        {
                            return(true);
                        }

                        if (!context.Enterprise.TryGetUserById(x.EnterpriseUserId, out var user))
                        {
                            return(false);
                        }
                        return(user.Email == arguments.Match);
                    }).ToArray();

                    if (devices.Length > 0)
                    {
                        if (cmd == "approve")
                        {
                            await context.ApproveAdminDeviceRequests(devices);
                        }
                        else
                        {
                            await context.DenyAdminDeviceRequests(devices);
                        }
                    }
                    else
                    {
                        Console.WriteLine($"No device found matching {arguments.Match}");
                    }
                }

                break;
            }
        }
예제 #4
0
        public static async Task EnterpriseTeamCommand(this IEnterpriseContext context, EnterpriseTeamOptions arguments)
        {
            if (arguments.Force)
            {
                await context.Enterprise.PopulateEnterprise();
            }

            if (string.IsNullOrEmpty(arguments.Command))
            {
                arguments.Command = "list";
            }
            if (string.CompareOrdinal(arguments.Command, "list") == 0)
            {
                var teams = context.Enterprise.Teams
                            .Where(x =>
                {
                    if (string.IsNullOrEmpty(arguments.Name))
                    {
                        return(true);
                    }
                    if (arguments.Name == x.Uid)
                    {
                        return(true);
                    }
                    var m = Regex.Match(x.Name, arguments.Name, RegexOptions.IgnoreCase);
                    return(m.Success);
                })
                            .ToArray();
                var tab = new Tabulate(7)
                {
                    DumpRowNo = true
                };
                tab.AddHeader("Team Name", "Team UID", "Node Name", "Restrict Edit", "Restrict Share", "Restrict View", "Users");
                foreach (var team in teams)
                {
                    EnterpriseNode node = null;
                    if (team.ParentNodeId > 0)
                    {
                        context.Enterprise.TryGetNode(team.ParentNodeId, out node);
                    }
                    else
                    {
                        node = context.Enterprise.RootNode;
                    }

                    tab.AddRow(team.Name,
                               team.Uid,
                               node != null ? node.DisplayName : "",
                               team.RestrictEdit ? "X" : "-",
                               team.RestrictSharing ? "X" : "-",
                               team.RestrictView ? "X" : "-",
                               team.Users.Count.ToString());
                }

                tab.Sort(1);
                tab.Dump();
            }
            else
            {
                var team = context.Enterprise.Teams
                           .FirstOrDefault(x =>
                {
                    if (string.IsNullOrEmpty(arguments.Name))
                    {
                        return(true);
                    }
                    if (arguments.Name == x.Uid)
                    {
                        return(true);
                    }
                    return(string.Compare(x.Name, arguments.Name, StringComparison.CurrentCultureIgnoreCase) == 0);
                });
                if (string.CompareOrdinal(arguments.Command, "delete") == 0)
                {
                    if (team == null)
                    {
                        Console.WriteLine($"Team \"{arguments.Name}\" not found");
                        return;
                    }

                    await context.Enterprise.DeleteTeam(team.Uid);
                }
                else if (string.CompareOrdinal(arguments.Command, "view") == 0)
                {
                    if (team == null)
                    {
                        Console.WriteLine($"Team \"{arguments.Name}\" not found");
                        return;
                    }

                    var tab = new Tabulate(2)
                    {
                        DumpRowNo = false
                    };
                    tab.SetColumnRightAlign(0, true);
                    tab.AddRow(" Team Name:", team.Name);
                    tab.AddRow(" Team UID:", team.Uid);
                    tab.AddRow(" Restrict Edit:", team.RestrictEdit ? "Yes" : "No");
                    tab.AddRow(" Restrict Share:", team.RestrictSharing ? "Yes" : "No");
                    tab.AddRow(" Restrict View:", team.RestrictView ? "Yes" : "No");
                    var users = team.Users
                                .Select(x => context.Enterprise.TryGetUserById(x, out var user) ? user.Email : null)
                                .Where(x => !string.IsNullOrEmpty(x))
                                .ToArray();
                    Array.Sort(users);
                    tab.AddRow(" Users:", users.Length > 0 ? users[0] : "");
                    for (var i = 1; i < users.Length; i++)
                    {
                        tab.AddRow("", users[i]);
                    }

                    if (context.Enterprise.TryGetNode(team.ParentNodeId, out var node))
                    {
                        var nodes = context.GetNodePath(node).ToArray();
                        Array.Reverse(nodes);
                        tab.AddRow(" Node:", string.Join(" -> ", nodes));
                    }

                    tab.Dump();
                }
                else if (string.CompareOrdinal(arguments.Command, "update") == 0 || string.CompareOrdinal(arguments.Command, "add") == 0)
                {
                    if (team == null)
                    {
                        if (string.CompareOrdinal(arguments.Command, "update") == 0 ||
                            string.CompareOrdinal(arguments.Command, "view") == 0)
                        {
                            Console.WriteLine($"Team \"{arguments.Name}\" not found");
                            return;
                        }

                        team = new EnterpriseTeam
                        {
                            ParentNodeId = context.Enterprise.RootNode.Id
                        };
                    }
                    else
                    {
                        if (string.CompareOrdinal(arguments.Command, "add") == 0)
                        {
                            Console.WriteLine($"Team with name \"{arguments.Name}\" already exists.\nDo you want to create a new one? Yes/No");
                            var answer = await Program.GetInputManager().ReadLine();

                            if (string.Compare("y", answer, StringComparison.InvariantCultureIgnoreCase) == 0)
                            {
                                answer = "yes";
                            }

                            if (string.Compare(answer, "yes", StringComparison.InvariantCultureIgnoreCase) != 0)
                            {
                                return;
                            }
                        }
                    }

                    team.Name = arguments.Name;
                    if (CliCommands.ParseBoolOption(arguments.RestrictEdit, out var b))
                    {
                        team.RestrictEdit = b;
                    }

                    if (CliCommands.ParseBoolOption(arguments.RestrictShare, out b))
                    {
                        team.RestrictSharing = b;
                    }

                    if (CliCommands.ParseBoolOption(arguments.RestrictView, out b))
                    {
                        team.RestrictView = b;
                    }

                    if (!string.IsNullOrEmpty(arguments.Node))
                    {
                        long?asId = null;
                        if (arguments.Node.All(char.IsDigit))
                        {
                            if (long.TryParse(arguments.Node, out var l))
                            {
                                asId = l;
                            }
                        }

                        var node = context.Enterprise.Nodes
                                   .FirstOrDefault(x =>
                        {
                            if (asId.HasValue && asId.Value == x.Id)
                            {
                                return(true);
                            }
                            return(string.Compare(x.DisplayName, arguments.Node, StringComparison.CurrentCultureIgnoreCase) == 0);
                        });
                        if (node != null)
                        {
                            team.ParentNodeId = node.Id;
                        }
                    }

                    await context.Enterprise.UpdateTeam(team);
                }
                else
                {
                    Console.WriteLine($"Unsupported command \"{arguments.Command}\". Valid commands are  \"list\", \"view\", \"add\", \"delete\", \"update\"");
                }
            }
        }
예제 #5
0
        public static async Task EnterpriseUserCommand(this IEnterpriseContext context, EnterpriseUserOptions arguments)
        {
            if (string.IsNullOrEmpty(arguments.Command))
            {
                arguments.Command = "list";
            }

            if (arguments.Force)
            {
                await context.Enterprise.PopulateEnterprise();
            }

            if (string.Compare(arguments.Command, "list", StringComparison.InvariantCultureIgnoreCase) == 0)
            {
                var users = context.Enterprise.Users
                            .Where(x =>
                {
                    if (string.IsNullOrEmpty(arguments.Name))
                    {
                        return(true);
                    }
                    var m = Regex.Match(x.Email, arguments.Name, RegexOptions.IgnoreCase);
                    if (m.Success)
                    {
                        return(true);
                    }
                    if (!string.IsNullOrEmpty(x.DisplayName))
                    {
                        m = Regex.Match(x.DisplayName, arguments.Name, RegexOptions.IgnoreCase);
                        if (m.Success)
                        {
                            return(true);
                        }
                    }

                    var status = x.UserStatus.ToString();
                    m          = Regex.Match(status, arguments.Name, RegexOptions.IgnoreCase);
                    return(m.Success);
                })
                            .ToArray();

                var tab = new Tabulate(4)
                {
                    DumpRowNo = true
                };
                tab.AddHeader("Email", "Display Name", "Status", "Teams");
                foreach (var user in users)
                {
                    tab.AddRow(user.Email, user.DisplayName, user.UserStatus.ToString(), user.Teams.Count);
                }

                tab.Sort(1);
                tab.Dump();
            }
            else if (string.Compare(arguments.Command, "view", StringComparison.InvariantCultureIgnoreCase) == 0)
            {
                var user = context.Enterprise.Users
                           .FirstOrDefault(x =>
                {
                    if (string.Compare(x.DisplayName, arguments.Name, StringComparison.CurrentCultureIgnoreCase) == 0)
                    {
                        return(true);
                    }
                    if (x.Email.StartsWith(arguments.Name, StringComparison.InvariantCulture))
                    {
                        return(true);
                    }
                    return(false);
                });
                if (user == null)
                {
                    Console.WriteLine($"Enterprise user \"{arguments.Name}\" not found");
                    return;
                }
                var tab = new Tabulate(2)
                {
                    DumpRowNo = false
                };
                tab.SetColumnRightAlign(0, true);
                tab.AddRow(" User Email:", user.Email);
                tab.AddRow(" User Name:", user.DisplayName);
                tab.AddRow(" User ID:", user.Id.ToString());
                tab.AddRow(" Status:", user.UserStatus.ToString());

                var teams = user.Teams
                            .Select(x => context.Enterprise.TryGetTeam(x, out var team) ? team.Name : null)
                            .Where(x => !string.IsNullOrEmpty(x))
                            .ToArray();
                Array.Sort(teams);
                tab.AddRow(" Teams:", teams.Length > 0 ? teams[0] : "");
                for (var i = 1; i < teams.Length; i++)
                {
                    tab.AddRow("", teams[i]);
                }

                if (context.Enterprise.TryGetNode(user.ParentNodeId, out var node))
                {
                    var nodes = context.GetNodePath(node).ToArray();
                    Array.Reverse(nodes);
                    tab.AddRow(" Node:", string.Join(" -> ", nodes));
                }

                tab.Dump();
            }
            else if (string.Compare(arguments.Command, "team-add", StringComparison.InvariantCultureIgnoreCase) == 0 || string.Compare(arguments.Command, "team-remove", StringComparison.InvariantCultureIgnoreCase) == 0)
            {
                var user = context.Enterprise.Users
                           .FirstOrDefault(x =>
                {
                    if (string.Compare(x.DisplayName, arguments.Name, StringComparison.CurrentCultureIgnoreCase) == 0)
                    {
                        return(true);
                    }
                    if (string.Compare(x.Email, arguments.Name, StringComparison.InvariantCulture) == 0)
                    {
                        return(true);
                    }
                    return(true);
                });
                if (user == null)
                {
                    Console.WriteLine($"Enterprise user \"{arguments.Name}\" not found");
                    return;
                }

                if (string.IsNullOrEmpty(arguments.Team))
                {
                    Console.WriteLine("Team name parameter is mandatory.");
                    return;
                }

                var team = context.Enterprise.Teams
                           .FirstOrDefault(x =>
                {
                    if (string.CompareOrdinal(x.Uid, arguments.Team) == 0)
                    {
                        return(true);
                    }
                    return(string.Compare(x.Name, arguments.Team, StringComparison.CurrentCultureIgnoreCase) == 0);
                });
                if (team == null)
                {
                    Console.WriteLine($"Team {arguments.Team} cannot be found.");
                    return;
                }

                if (string.Compare(arguments.Command, "team-add", StringComparison.InvariantCultureIgnoreCase) == 0)
                {
                    await context.Enterprise.AddUsersToTeams(new[] { user.Email }, new[] { team.Uid }, Console.WriteLine);
                }
                else
                {
                    await context.Enterprise.RemoveUsersFromTeams(new[] { user.Email }, new[] { team.Uid }, Console.WriteLine);
                }
            }
            else
            {
                Console.WriteLine($"Unsupported command \"{arguments.Command}\". Commands are \"list\", \"view\", \"team-add\", \"team-remove\"");
            }
        }
예제 #6
0
        private Task ListCommand(ListCommandOptions options)
        {
            FolderNode node = null;

            if (!string.IsNullOrEmpty(_currentFolder))
            {
                _vault.TryGetFolder(_currentFolder, out node);
            }
            if (node == null)
            {
                node = _vault.Root;
            }

            if (options.Details)
            {
                if (node.Children.Count > 0)
                {
                    var tab = new Tabulate(2)
                    {
                        DumpRowNo = true
                    };
                    tab.AddHeader(new string[] { "Folder UID", "Name" });
                    foreach (var uid in node.Children)
                    {
                        if (_vault.TryGetFolder(uid, out FolderNode f))
                        {
                            tab.AddRow(new string[] { f.FolderUid, f.Name });
                        }
                    }

                    tab.Sort(1);
                    tab.Dump();
                }

                if (node.Records.Count > 0)
                {
                    var tab = new Tabulate(4)
                    {
                        DumpRowNo = true
                    };
                    tab.AddHeader(new string[] { "Record UID", "Title", "Login", "URL" });
                    foreach (var uid in node.Records)
                    {
                        if (_vault.TryGetRecord(uid, out PasswordRecord r))
                        {
                            tab.AddRow(new string[] { r.Uid, r.Title, r.Login, r.Link });
                        }
                    }

                    tab.Sort(1);
                    tab.Dump();
                }
            }
            else
            {
                List <string> names = new List <string>();
                foreach (var uid in node.Children)
                {
                    if (_vault.TryGetFolder(uid, out FolderNode subnode))
                    {
                        names.Add(subnode.Name + "/");
                    }
                }
                names.Sort(StringComparer.InvariantCultureIgnoreCase);
                int len = names.Count;
                foreach (var uid in node.Records)
                {
                    if (_vault.TryGetRecord(uid, out PasswordRecord record))
                    {
                        names.Add(record.Title);
                    }
                }
                names.Sort(len, names.Count - len, StringComparer.InvariantCultureIgnoreCase);
                if (names.Count > 0)
                {
                    len = names.Select(x => x.Length).Max();
                    if (len < 16)
                    {
                        len = 16;
                    }
                    len += 2;
                    int columns = Console.BufferWidth / len;
                    if (columns < 1)
                    {
                        columns = 1;
                    }
                    int columnWidth = Console.BufferWidth / columns;
                    int colNo       = 0;
                    for (int i = 0; i < names.Count; i++)
                    {
                        Console.Write(names[i].PadRight(columnWidth - 1));
                        colNo++;
                        if (colNo >= columns)
                        {
                            Console.WriteLine();
                            colNo = 0;
                        }
                    }
                }
            }

            return(Task.FromResult(true));
        }
예제 #7
0
        private Task GetCommand(string uid)
        {
            var tab = new Tabulate(3);

            if (_vault.TryGetRecord(uid, out PasswordRecord record))
            {
                tab.AddRow(new[] { "Record UID:", record.Uid });
                tab.AddRow(new[] { "Title:", record.Title });
                tab.AddRow(new[] { "Login:"******"Password:"******"Login URL:", record.Link });
                tab.AddRow(new[] { "Notes:", record.Notes });
                if (record.Custom != null && record.Custom.Count > 0)
                {
                    tab.AddRow(new[] { "" });
                    tab.AddRow(new[] { "Custom Fields:", "" });
                    foreach (var c in record.Custom)
                    {
                        tab.AddRow(new[] { c.Name + ":", c.Value });
                    }
                }
            }
            else if (_vault.TryGetSharedFolder(uid, out SharedFolder sf))
            {
                tab.AddRow(new[] { "Shared Folder UID:", sf.Uid });
                tab.AddRow(new[] { "Name:", sf.Name });
                tab.AddRow(new[] { "Default Manage Records:", sf.DefaultManageRecords.ToString() });
                tab.AddRow(new[] { "Default Manage Users:", sf.DefaultManageUsers.ToString() });
                tab.AddRow(new[] { "Default Can Edit:", sf.DefaultCanEdit.ToString() });
                tab.AddRow(new[] { "Default Can Share:", sf.DefaultCanShare.ToString() });
                if (sf.Records.Count > 0)
                {
                    tab.AddRow(new[] { "" });
                    tab.AddRow(new[] { "Record Permissions:" });
                    foreach (var r in sf.Records)
                    {
                        tab.AddRow(new[] { r.RecordUid + ":", "Can Edit: " + r.CanEdit.ToString(), "Can Share: " + r.CanShare.ToString() });
                    }
                }
                if (sf.Users.Count > 0)
                {
                    tab.AddRow(new[] { "" });
                    tab.AddRow(new[] { "User Permissions:" });
                    foreach (var u in sf.Users)
                    {
                        tab.AddRow(new[] { u.Username + ":", "Can Manage Records: " + u.ManageRecords.ToString(), "Can Manage Users: " + u.ManageUsers.ToString() });
                    }
                }
                if (sf.Teams.Count > 0)
                {
                    tab.AddRow(new[] { "" });
                    tab.AddRow(new[] { "Team Permissions:" });
                    foreach (var t in sf.Teams)
                    {
                        tab.AddRow(new[] { t.Name + ":", "Can Manage Records: " + t.ManageRecords.ToString(), "Can Manage Users: " + t.ManageUsers.ToString() });
                    }
                }
            }
            else if (_vault.TryGetFolder(uid, out FolderNode f))
            {
                tab.AddRow(new[] { "Folder UID:", f.FolderUid });
                if (!string.IsNullOrEmpty(f.ParentUid))
                {
                    tab.AddRow(new[] { "Parent Folder UID:", f.ParentUid });
                }
                tab.AddRow(new[] { "Folder Type:", f.FolderType.ToString() });
                tab.AddRow(new[] { "Name:", f.Name });
            }
            else
            {
                Console.WriteLine(string.Format("UID {0} is not a valid Keeper object", uid));
                return(Task.FromResult(false));
            }
            Console.WriteLine();
            tab.SetColumnRightAlign(0, true);
            tab.LeftPadding = 4;
            tab.Dump();
            return(Task.FromResult(true));
        }