i'm about to totally re-do how i'm approaching SSH tunneling, sooo...

This commit is contained in:
brent s 2017-11-13 23:38:52 -05:00
parent fd68ba87b7
commit 1bac4a9d78
5 changed files with 1458 additions and 0 deletions

1
mumble/.gitignore vendored Normal file
View File

@ -0,0 +1 @@
/docs

56
mumble/getusers.py Executable file
View File

@ -0,0 +1,56 @@
#!/usr/bin/env python3

import copy
import pprint
import usrmgmt2

# NOTE: THIS IS ONLY FOR TESTING/DEVELOPMENT PURPOSES.
# IT WILL BE REMOVED ONCE THE ACTUAL STUFF IS FINISHED.

args = vars(usrmgmt2.parseArgs().parse_args())
args['operation'] = 'ls'
args['verbose'] = True
args['cfgfile'] = '/home/bts/.config/optools/mumbleadmin.ini'
#if not args['operation']:
#raise RuntimeError('You must specify an operation to perform. Try running with -h/--help.')
# exit('You must specify an operation to perform. Try running with -h/--help.')

mgmt = usrmgmt2.IceMgr(args)

def dictify(obj):
# thanks, https://github.com/alfg/murmur-rest/blob/master/app/utils.py
_rv = {'_type': str(type(obj))}
if type(obj) in (bool, int, float, str, bytes):
return(obj)
if type(obj) in (list, tuple):
return([dictify(i) for i in obj])
if type(obj) == dict:
return(dict((str(k), dictify(v)) for k, v in obj.items()))
return(dictify(obj.__dict__))


# Here we actually print users
#print(inspect.getmembers(Murmur.UserInfo))
#for s in mgmt.conn['read'].getAllServers(): # iterate through all servers
#userattrs = [Murmur.UserInfo.Username, Murmur.UserInfo.UserEmail,
# Murmur.UserInfo.UserHash, Murmur.UserInfo.UserLastActive,
# Murmur.UserInfo.UserComment]
#print(type(s))
#pprint.pprint(s.getRegisteredUsers('')) # either print a UID:username map...
# for uid, uname in s.getRegisteredUsers('').items(): # or let's try to get full info on them
#print('user: {0}\nusername: {1}\n'.format(uid, uname))
# _u = dictify(s.getRegistration(uid))
# if uid == 3:
# print(_u)

_server = mgmt.conn['read'].getServer(1)


#acl = _server.getACL(0)
#print(acl[0])



#pprint.pprint(dictify(acl), indent = 4)

mgmt.close()

888
mumble/murmur.ice Normal file
View File

@ -0,0 +1,888 @@
// https://raw.githubusercontent.com/mumble-voip/mumble/master/src/murmur/Murmur.ice
// http://mumble.sourceforge.net/slice/1.3.0/Murmur.html

// Copyright 2005-2017 The Mumble Developers. All rights reserved.
// Use of this source code is governed by a BSD-style license
// that can be found in the LICENSE file at the root of the
// Mumble source tree or at <https://www.mumble.info/LICENSE>.

/**
*
* Information and control of the murmur server. Each server has
* one {@link Meta} interface that controls global information, and
* each virtual server has a {@link Server} interface.
*
**/

#include <Ice/SliceChecksumDict.ice>

module Murmur
{

/** A network address in IPv6 format.
**/
["python:seq:tuple"] sequence<byte> NetAddress;

/** A connected user.
**/
struct User {
/** Session ID. This identifies the connection to the server. */
int session;
/** User ID. -1 if the user is anonymous. */
int userid;
/** Is user muted by the server? */
bool mute;
/** Is user deafened by the server? If true, this implies mute. */
bool deaf;
/** Is the user suppressed by the server? This means the user is not muted, but does not have speech privileges in the current channel. */
bool suppress;
/** Is the user a priority speaker? */
bool prioritySpeaker;
/** Is the user self-muted? */
bool selfMute;
/** Is the user self-deafened? If true, this implies mute. */
bool selfDeaf;
/** Is the User recording? (This flag is read-only and cannot be changed using setState().) **/
bool recording;
/** Channel ID the user is in. Matches {@link Channel.id}. */
int channel;
/** The name of the user. */
string name;
/** Seconds user has been online. */
int onlinesecs;
/** Average transmission rate in bytes per second over the last few seconds. */
int bytespersec;
/** Client version. Major version in upper 16 bits, followed by 8 bits of minor version and 8 bits of patchlevel. Version 1.2.3 = 0x010203. */
int version;
/** Client release. For official releases, this equals the version. For snapshots and git compiles, this will be something else. */
string release;
/** Client OS. */
string os;
/** Client OS Version. */
string osversion;
/** Plugin Identity. This will be the user's unique ID inside the current game. */
string identity;
/**
Base64-encoded Plugin context. This is a binary blob identifying the game and team the user is on.

The used Base64 alphabet is the one specified in RFC 2045.

Before Mumble 1.3.0, this string was not Base64-encoded. This could cause problems for some Ice
implementations, such as the .NET implementation.

If you need the exact string that is used by Mumble, you can get it by Base64-decoding this string.

If you simply need to detect whether two users are in the same game world, string comparisons will
continue to work as before.
*/
string context;
/** User comment. Shown as tooltip for this user. */
string comment;
/** Client address. */
NetAddress address;
/** TCP only. True until UDP connectivity is established. */
bool tcponly;
/** Idle time. This is how many seconds it is since the user last spoke. Other activity is not counted. */
int idlesecs;
/** UDP Ping Average. This is the average ping for the user via UDP over the duration of the connection. */
float udpPing;
/** TCP Ping Average. This is the average ping for the user via TCP over the duration of the connection. */
float tcpPing;
};

sequence<int> IntList;

/** A text message between users.
**/
struct TextMessage {
/** Sessions (connected users) who were sent this message. */
IntList sessions;
/** Channels who were sent this message. */
IntList channels;
/** Trees of channels who were sent this message. */
IntList trees;
/** The contents of the message. */
string text;
};

/** A channel.
**/
struct Channel {
/** Channel ID. This is unique per channel, and the root channel is always id 0. */
int id;
/** Name of the channel. There can not be two channels with the same parent that has the same name. */
string name;
/** ID of parent channel, or -1 if this is the root channel. */
int parent;
/** List of id of linked channels. */
IntList links;
/** Description of channel. Shown as tooltip for this channel. */
string description;
/** Channel is temporary, and will be removed when the last user leaves it. */
bool temporary;
/** Position of the channel which is used in Client for sorting. */
int position;
};

/** A group. Groups are defined per channel, and can inherit members from parent channels.
**/
struct Group {
/** Group name */
string name;
/** Is this group inherited from a parent channel? Read-only. */
bool inherited;
/** Does this group inherit members from parent channels? */
bool inherit;
/** Can subchannels inherit members from this group? */
bool inheritable;
/** List of users to add to the group. */
IntList add;
/** List of inherited users to remove from the group. */
IntList remove;
/** Current members of the group, including inherited members. Read-only. */
IntList members;
};

/** Write access to channel control. Implies all other permissions (except Speak). */
const int PermissionWrite = 0x01;
/** Traverse channel. Without this, a client cannot reach subchannels, no matter which privileges he has there. */
const int PermissionTraverse = 0x02;
/** Enter channel. */
const int PermissionEnter = 0x04;
/** Speak in channel. */
const int PermissionSpeak = 0x08;
/** Whisper to channel. This is different from Speak, so you can set up different permissions. */
const int PermissionWhisper = 0x100;
/** Mute and deafen other users in this channel. */
const int PermissionMuteDeafen = 0x10;
/** Move users from channel. You need this permission in both the source and destination channel to move another user. */
const int PermissionMove = 0x20;
/** Make new channel as a subchannel of this channel. */
const int PermissionMakeChannel = 0x40;
/** Make new temporary channel as a subchannel of this channel. */
const int PermissionMakeTempChannel = 0x400;
/** Link this channel. You need this permission in both the source and destination channel to link channels, or in either channel to unlink them. */
const int PermissionLinkChannel = 0x80;
/** Send text message to channel. */
const int PermissionTextMessage = 0x200;
/** Kick user from server. Only valid on root channel. */
const int PermissionKick = 0x10000;
/** Ban user from server. Only valid on root channel. */
const int PermissionBan = 0x20000;
/** Register and unregister users. Only valid on root channel. */
const int PermissionRegister = 0x40000;
/** Register and unregister users. Only valid on root channel. */
const int PermissionRegisterSelf = 0x80000;


/** Access Control List for a channel. ACLs are defined per channel, and can be inherited from parent channels.
**/
struct ACL {
/** Does the ACL apply to this channel? */
bool applyHere;
/** Does the ACL apply to subchannels? */
bool applySubs;
/** Is this ACL inherited from a parent channel? Read-only. */
bool inherited;
/** ID of user this ACL applies to. -1 if using a group name. */
int userid;
/** Group this ACL applies to. Blank if using userid. */
string group;
/** Binary mask of privileges to allow. */
int allow;
/** Binary mask of privileges to deny. */
int deny;
};

/** A single ip mask for a ban.
**/
struct Ban {
/** Address to ban. */
NetAddress address;
/** Number of bits in ban to apply. */
int bits;
/** Username associated with ban. */
string name;
/** Hash of banned user. */
string hash;
/** Reason for ban. */
string reason;
/** Date ban was applied in unix time format. */
int start;
/** Duration of ban. */
int duration;
};

/** A entry in the log.
**/
struct LogEntry {
/** Timestamp in UNIX time_t */
int timestamp;
/** The log message. */
string txt;
};

class Tree;
sequence<Tree> TreeList;

enum ChannelInfo { ChannelDescription, ChannelPosition };
enum UserInfo { UserName, UserEmail, UserComment, UserHash, UserPassword, UserLastActive };

dictionary<int, User> UserMap;
dictionary<int, Channel> ChannelMap;
sequence<Channel> ChannelList;
sequence<User> UserList;
sequence<Group> GroupList;
sequence<ACL> ACLList;
sequence<LogEntry> LogList;
sequence<Ban> BanList;
sequence<int> IdList;
sequence<string> NameList;
dictionary<int, string> NameMap;
dictionary<string, int> IdMap;
sequence<byte> Texture;
dictionary<string, string> ConfigMap;
sequence<string> GroupNameList;
sequence<byte> CertificateDer;
sequence<CertificateDer> CertificateList;

/** User information map.
* Older versions of ice-php can't handle enums as keys. If you are using one of these, replace 'UserInfo' with 'byte'.
*/

dictionary<UserInfo, string> UserInfoMap;

/** User and subchannel state. Read-only.
**/
class Tree {
/** Channel definition of current channel. */
Channel c;
/** List of subchannels. */
TreeList children;
/** Users in this channel. */
UserList users;
};

exception MurmurException {};
/** This is thrown when you specify an invalid session. This may happen if the user has disconnected since your last call to {@link Server.getUsers}. See {@link User.session} */
exception InvalidSessionException extends MurmurException {};
/** This is thrown when you specify an invalid channel id. This may happen if the channel was removed by another provess. It can also be thrown if you try to add an invalid channel. */
exception InvalidChannelException extends MurmurException {};
/** This is thrown when you try to do an operation on a server that does not exist. This may happen if someone has removed the server. */
exception InvalidServerException extends MurmurException {};
/** This happens if you try to fetch user or channel state on a stopped server, if you try to stop an already stopped server or start an already started server. */
exception ServerBootedException extends MurmurException {};
/** This is thrown if {@link Server.start} fails, and should generally be the cause for some concern. */
exception ServerFailureException extends MurmurException {};
/** This is thrown when you specify an invalid userid. */
exception InvalidUserException extends MurmurException {};
/** This is thrown when you try to set an invalid texture. */
exception InvalidTextureException extends MurmurException {};
/** This is thrown when you supply an invalid callback. */
exception InvalidCallbackException extends MurmurException {};
/** This is thrown when you supply the wrong secret in the calling context. */
exception InvalidSecretException extends MurmurException {};
/** This is thrown when the channel operation would excede the channel nesting limit */
exception NestingLimitException extends MurmurException {};
/** This is thrown when you ask the server to disclose something that should be secret. */
exception WriteOnlyException extends MurmurException {};
/** This is thrown when invalid input data was specified. */
exception InvalidInputDataException extends MurmurException {};

/** Callback interface for servers. You can supply an implementation of this to receive notification
* messages from the server.
* If an added callback ever throws an exception or goes away, it will be automatically removed.
* Please note that all callbacks are done asynchronously; murmur does not wait for the callback to
* complete before continuing processing.
* Note that callbacks are removed when a server is stopped, so you should have a callback for
* {@link MetaCallback.started} which calls {@link Server.addCallback}.
* @see MetaCallback
* @see Server.addCallback
*/
interface ServerCallback {
/** Called when a user connects to the server.
* @param state State of connected user.
*/
idempotent void userConnected(User state);
/** Called when a user disconnects from the server. The user has already been removed, so you can no longer use methods like {@link Server.getState}
* to retrieve the user's state.
* @param state State of disconnected user.
*/
idempotent void userDisconnected(User state);
/** Called when a user state changes. This is called if the user moves, is renamed, is muted, deafened etc.
* @param state New state of user.
*/
idempotent void userStateChanged(User state);
/** Called when user writes a text message
* @param state the User sending the message
* @param message the TextMessage the user has sent
*/
idempotent void userTextMessage(User state, TextMessage message);
/** Called when a new channel is created.
* @param state State of new channel.
*/
idempotent void channelCreated(Channel state);
/** Called when a channel is removed. The channel has already been removed, you can no longer use methods like {@link Server.getChannelState}
* @param state State of removed channel.
*/
idempotent void channelRemoved(Channel state);
/** Called when a new channel state changes. This is called if the channel is moved, renamed or if new links are added.
* @param state New state of channel.
*/
idempotent void channelStateChanged(Channel state);
};

/** Context for actions in the Server menu. */
const int ContextServer = 0x01;
/** Context for actions in the Channel menu. */
const int ContextChannel = 0x02;
/** Context for actions in the User menu. */
const int ContextUser = 0x04;

/** Callback interface for context actions. You need to supply one of these for {@link Server.addContext}.
* If an added callback ever throws an exception or goes away, it will be automatically removed.
* Please note that all callbacks are done asynchronously; murmur does not wait for the callback to
* complete before continuing processing.
*/
interface ServerContextCallback {
/** Called when a context action is performed.
* @param action Action to be performed.
* @param usr User which initiated the action.
* @param session If nonzero, session of target user.
* @param channelid If not -1, id of target channel.
*/
idempotent void contextAction(string action, User usr, int session, int channelid);
};

/** Callback interface for server authentication. You need to supply one of these for {@link Server.setAuthenticator}.
* If an added callback ever throws an exception or goes away, it will be automatically removed.
* Please note that unlike {@link ServerCallback} and {@link ServerContextCallback}, these methods are called
* synchronously. If the response lags, the entire murmur server will lag.
* Also note that, as the method calls are synchronous, making a call to {@link Server} or {@link Meta} will
* deadlock the server.
*/
interface ServerAuthenticator {
/** Called to authenticate a user. If you do not know the username in question, always return -2 from this
* method to fall through to normal database authentication.
* Note that if authentication succeeds, murmur will create a record of the user in it's database, reserving
* the username and id so it cannot be used for normal database authentication.
* The data in the certificate (name, email addresses etc), as well as the list of signing certificates,
* should only be trusted if certstrong is true.
*
* Internally, Murmur treats usernames as case-insensitive. It is recommended
* that authenticators do the same. Murmur checks if a username is in use when
* a user connects. If the connecting user is registered, the other username is
* kicked. If the connecting user is not registered, the connecting user is not
* allowed to join the server.
*
* @param name Username to authenticate.
* @param pw Password to authenticate with.
* @param certificates List of der encoded certificates the user connected with.
* @param certhash Hash of user certificate, as used by murmur internally when matching.
* @param certstrong True if certificate was valid and signed by a trusted CA.
* @param newname Set this to change the username from the supplied one.
* @param groups List of groups on the root channel that the user will be added to for the duration of the connection.
* @return UserID of authenticated user, -1 for authentication failures, -2 for unknown user (fallthrough),
* -3 for authentication failures where the data could (temporarily) not be verified.
*/
idempotent int authenticate(string name, string pw, CertificateList certificates, string certhash, bool certstrong, out string newname, out GroupNameList groups);

/** Fetch information about a user. This is used to retrieve information like email address, keyhash etc. If you
* want murmur to take care of this information itself, simply return false to fall through.
* @param id User id.
* @param info Information about user. This needs to include at least "name".
* @return true if information is present, false to fall through.
*/
idempotent bool getInfo(int id, out UserInfoMap info);
/** Map a name to a user id.
* @param name Username to map.
* @return User id or -2 for unknown name.
*/
idempotent int nameToId(string name);

/** Map a user id to a username.
* @param id User id to map.
* @return Name of user or empty string for unknown id.
*/
idempotent string idToName(int id);

/** Map a user to a custom Texture.
* @param id User id to map.
* @return User texture or an empty texture for unknwon users or users without textures.
*/
idempotent Texture idToTexture(int id);
};

/** Callback interface for server authentication and registration. This allows you to support both authentication
* and account updating.
* You do not need to implement this if all you want is authentication, you only need this if other scripts
* connected to the same server calls e.g. {@link Server.setTexture}.
* Almost all of these methods support fall through, meaning murmur should continue the operation against its
* own database.
*/
interface ServerUpdatingAuthenticator extends ServerAuthenticator {
/** Register a new user.
* @param info Information about user to register.
* @return User id of new user, -1 for registration failure, or -2 to fall through.
*/
int registerUser(UserInfoMap info);

/** Unregister a user.
* @param id Userid to unregister.
* @return 1 for successfull unregistration, 0 for unsuccessfull unregistration, -1 to fall through.
*/
int unregisterUser(int id);

/** Get a list of registered users matching filter.
* @param filter Substring usernames must contain. If empty, return all registered users.
* @return List of matching registered users.
*/
idempotent NameMap getRegisteredUsers(string filter);

/** Set additional information for user registration.
* @param id Userid of registered user.
* @param info Information to set about user. This should be merged with existing information.
* @return 1 for successfull update, 0 for unsuccessfull update, -1 to fall through.
*/
idempotent int setInfo(int id, UserInfoMap info);

/** Set texture (now called avatar) of user registration.
* @param id registrationId of registered user.
* @param tex New texture.
* @return 1 for successfull update, 0 for unsuccessfull update, -1 to fall through.
*/
idempotent int setTexture(int id, Texture tex);
};

/** Per-server interface. This includes all methods for configuring and altering
* the state of a single virtual server. You can retrieve a pointer to this interface
* from one of the methods in {@link Meta}.
**/
["amd"] interface Server {
/** Shows if the server currently running (accepting users).
*
* @return Run-state of server.
*/
idempotent bool isRunning() throws InvalidSecretException;

/** Start server. */
void start() throws ServerBootedException, ServerFailureException, InvalidSecretException;

/** Stop server.
* Note: Server will be restarted on Murmur restart unless explicitly disabled
* with setConf("boot", false)
*/
void stop() throws ServerBootedException, InvalidSecretException;

/** Delete server and all it's configuration. */
void delete() throws ServerBootedException, InvalidSecretException;

/** Fetch the server id.
*
* @return Unique server id.
*/
idempotent int id() throws InvalidSecretException;

/** Add a callback. The callback will receive notifications about changes to users and channels.
*
* @param cb Callback interface which will receive notifications.
* @see removeCallback
*/
void addCallback(ServerCallback *cb) throws ServerBootedException, InvalidCallbackException, InvalidSecretException;

/** Remove a callback.
*
* @param cb Callback interface to be removed.
* @see addCallback
*/
void removeCallback(ServerCallback *cb) throws ServerBootedException, InvalidCallbackException, InvalidSecretException;

/** Set external authenticator. If set, all authentications from clients are forwarded to this
* proxy.
*
* @param auth Authenticator object to perform subsequent authentications.
*/
void setAuthenticator(ServerAuthenticator *auth) throws ServerBootedException, InvalidCallbackException, InvalidSecretException;

/** Retrieve configuration item.
* @param key Configuration key.
* @return Configuration value. If this is empty, see {@link Meta.getDefaultConf}
*/
idempotent string getConf(string key) throws InvalidSecretException, WriteOnlyException;

/** Retrieve all configuration items.
* @return All configured values. If a value isn't set here, the value from {@link Meta.getDefaultConf} is used.
*/
idempotent ConfigMap getAllConf() throws InvalidSecretException;

/** Set a configuration item.
* @param key Configuration key.
* @param value Configuration value.
*/
idempotent void setConf(string key, string value) throws InvalidSecretException;

/** Set superuser password. This is just a convenience for using {@link updateRegistration} on user id 0.
* @param pw Password.
*/
idempotent void setSuperuserPassword(string pw) throws InvalidSecretException;

/** Fetch log entries.
* @param first Lowest numbered entry to fetch. 0 is the most recent item.
* @param last Last entry to fetch.
* @return List of log entries.
*/
idempotent LogList getLog(int first, int last) throws InvalidSecretException;

/** Fetch length of log
* @return Number of entries in log
*/
idempotent int getLogLen() throws InvalidSecretException;

/** Fetch all users. This returns all currently connected users on the server.
* @return List of connected users.
* @see getState
*/
idempotent UserMap getUsers() throws ServerBootedException, InvalidSecretException;

/** Fetch all channels. This returns all defined channels on the server. The root channel is always channel 0.
* @return List of defined channels.
* @see getChannelState
*/
idempotent ChannelMap getChannels() throws ServerBootedException, InvalidSecretException;

/** Fetch certificate of user. This returns the complete certificate chain of a user.
* @param session Connection ID of user. See {@link User.session}.
* @return Certificate list of user.
*/
idempotent CertificateList getCertificateList(int session) throws ServerBootedException, InvalidSessionException, InvalidSecretException;

/** Fetch all channels and connected users as a tree. This retrieves an easy-to-use representation of the server
* as a tree. This is primarily used for viewing the state of the server on a webpage.
* @return Recursive tree of all channels and connected users.
*/
idempotent Tree getTree() throws ServerBootedException, InvalidSecretException;

/** Fetch all current IP bans on the server.
* @return List of bans.
*/
idempotent BanList getBans() throws ServerBootedException, InvalidSecretException;

/** Set all current IP bans on the server. This will replace any bans already present, so if you want to add a ban, be sure to call {@link getBans} and then
* append to the returned list before calling this method.
* @param bans List of bans.
*/
idempotent void setBans(BanList bans) throws ServerBootedException, InvalidSecretException;

/** Kick a user. The user is not banned, and is free to rejoin the server.
* @param session Connection ID of user. See {@link User.session}.
* @param reason Text message to show when user is kicked.
*/
void kickUser(int session, string reason) throws ServerBootedException, InvalidSessionException, InvalidSecretException;

/** Get state of a single connected user.
* @param session Connection ID of user. See {@link User.session}.
* @return State of connected user.
* @see setState
* @see getUsers
*/
idempotent User getState(int session) throws ServerBootedException, InvalidSessionException, InvalidSecretException;

/** Set user state. You can use this to move, mute and deafen users.
* @param state User state to set.
* @see getState
*/
idempotent void setState(User state) throws ServerBootedException, InvalidSessionException, InvalidChannelException, InvalidSecretException;

/** Send text message to a single user.
* @param session Connection ID of user. See {@link User.session}.
* @param text Message to send.
* @see sendMessageChannel
*/
void sendMessage(int session, string text) throws ServerBootedException, InvalidSessionException, InvalidSecretException;

/** Check if user is permitted to perform action.
* @param session Connection ID of user. See {@link User.session}.
* @param channelid ID of Channel. See {@link Channel.id}.
* @param perm Permission bits to check.
* @return true if any of the permissions in perm were set for the user.
*/
bool hasPermission(int session, int channelid, int perm) throws ServerBootedException, InvalidSessionException, InvalidChannelException, InvalidSecretException;
/** Return users effective permissions
* @param session Connection ID of user. See {@link User.session}.
* @param channelid ID of Channel. See {@link Channel.id}.
* @return bitfield of allowed actions
*/
idempotent int effectivePermissions(int session, int channelid) throws ServerBootedException, InvalidSessionException, InvalidChannelException, InvalidSecretException;

/** Add a context callback. This is done per user, and will add a context menu action for the user.
*
* @param session Session of user which should receive context entry.
* @param action Action string, a unique name to associate with the action.
* @param text Name of action shown to user.
* @param cb Callback interface which will receive notifications.
* @param ctx Context this should be used in. Needs to be one or a combination of {@link ContextServer}, {@link ContextChannel} and {@link ContextUser}.
* @see removeContextCallback
*/
void addContextCallback(int session, string action, string text, ServerContextCallback *cb, int ctx) throws ServerBootedException, InvalidCallbackException, InvalidSecretException;

/** Remove a callback.
*
* @param cb Callback interface to be removed. This callback will be removed from all from all users.
* @see addContextCallback
*/
void removeContextCallback(ServerContextCallback *cb) throws ServerBootedException, InvalidCallbackException, InvalidSecretException;
/** Get state of single channel.
* @param channelid ID of Channel. See {@link Channel.id}.
* @return State of channel.
* @see setChannelState
* @see getChannels
*/
idempotent Channel getChannelState(int channelid) throws ServerBootedException, InvalidChannelException, InvalidSecretException;

/** Set state of a single channel. You can use this to move or relink channels.
* @param state Channel state to set.
* @see getChannelState
*/
idempotent void setChannelState(Channel state) throws ServerBootedException, InvalidChannelException, InvalidSecretException, NestingLimitException;

/** Remove a channel and all its subchannels.
* @param channelid ID of Channel. See {@link Channel.id}.
*/
void removeChannel(int channelid) throws ServerBootedException, InvalidChannelException, InvalidSecretException;

/** Add a new channel.
* @param name Name of new channel.
* @param parent Channel ID of parent channel. See {@link Channel.id}.
* @return ID of newly created channel.
*/
int addChannel(string name, int parent) throws ServerBootedException, InvalidChannelException, InvalidSecretException, NestingLimitException;

/** Send text message to channel or a tree of channels.
* @param channelid Channel ID of channel to send to. See {@link Channel.id}.
* @param tree If true, the message will be sent to the channel and all its subchannels.
* @param text Message to send.
* @see sendMessage
*/
void sendMessageChannel(int channelid, bool tree, string text) throws ServerBootedException, InvalidChannelException, InvalidSecretException;

/** Retrieve ACLs and Groups on a channel.
* @param channelid Channel ID of channel to fetch from. See {@link Channel.id}.
* @param acls List of ACLs on the channel. This will include inherited ACLs.
* @param groups List of groups on the channel. This will include inherited groups.
* @param inherit Does this channel inherit ACLs from the parent channel?
*/
idempotent void getACL(int channelid, out ACLList acls, out GroupList groups, out bool inherit) throws ServerBootedException, InvalidChannelException, InvalidSecretException;

/** Set ACLs and Groups on a channel. Note that this will replace all existing ACLs and groups on the channel.
* @param channelid Channel ID of channel to fetch from. See {@link Channel.id}.
* @param acls List of ACLs on the channel.
* @param groups List of groups on the channel.
* @param inherit Should this channel inherit ACLs from the parent channel?
*/
idempotent void setACL(int channelid, ACLList acls, GroupList groups, bool inherit) throws ServerBootedException, InvalidChannelException, InvalidSecretException;

/** Temporarily add a user to a group on a channel. This state is not saved, and is intended for temporary memberships.
* @param channelid Channel ID of channel to add to. See {@link Channel.id}.
* @param session Connection ID of user. See {@link User.session}.
* @param group Group name to add to.
*/
idempotent void addUserToGroup(int channelid, int session, string group) throws ServerBootedException, InvalidChannelException, InvalidSessionException, InvalidSecretException;

/** Remove a user from a temporary group membership on a channel. This state is not saved, and is intended for temporary memberships.
* @param channelid Channel ID of channel to add to. See {@link Channel.id}.
* @param session Connection ID of user. See {@link User.session}.
* @param group Group name to remove from.
*/
idempotent void removeUserFromGroup(int channelid, int session, string group) throws ServerBootedException, InvalidChannelException, InvalidSessionException, InvalidSecretException;

/** Redirect whisper targets for user. If set, whenever a user tries to whisper to group "source", the whisper will be redirected to group "target".
* To remove a redirect pass an empty target string. This is intended for context groups.
* @param session Connection ID of user. See {@link User.session}.
* @param source Group name to redirect from.
* @param target Group name to redirect to.
*/
idempotent void redirectWhisperGroup(int session, string source, string target) throws ServerBootedException, InvalidSessionException, InvalidSecretException;

/** Map a list of {@link User.userid} to a matching name.
* @param List of ids.
* @return Matching list of names, with an empty string representing invalid or unknown ids.
*/
idempotent NameMap getUserNames(IdList ids) throws ServerBootedException, InvalidSecretException;

/** Map a list of user names to a matching id.
* @param List of names.
* @reuturn List of matching ids, with -1 representing invalid or unknown user names.
*/
idempotent IdMap getUserIds(NameList names) throws ServerBootedException, InvalidSecretException;

/** Register a new user.
* @param info Information about new user. Must include at least "name".
* @return The ID of the user. See {@link RegisteredUser.userid}.
*/
int registerUser(UserInfoMap info) throws ServerBootedException, InvalidUserException, InvalidSecretException;

/** Remove a user registration.
* @param userid ID of registered user. See {@link RegisteredUser.userid}.
*/
void unregisterUser(int userid) throws ServerBootedException, InvalidUserException, InvalidSecretException;

/** Update the registration for a user. You can use this to set the email or password of a user,
* and can also use it to change the user's name.
* @param registration Updated registration record.
*/
idempotent void updateRegistration(int userid, UserInfoMap info) throws ServerBootedException, InvalidUserException, InvalidSecretException;

/** Fetch registration for a single user.
* @param userid ID of registered user. See {@link RegisteredUser.userid}.
* @return Registration record.
*/
idempotent UserInfoMap getRegistration(int userid) throws ServerBootedException, InvalidUserException, InvalidSecretException;

/** Fetch a group of registered users.
* @param filter Substring of user name. If blank, will retrieve all registered users.
* @return List of registration records.
*/
idempotent NameMap getRegisteredUsers(string filter) throws ServerBootedException, InvalidSecretException;

/** Verify the password of a user. You can use this to verify a user's credentials.
* @param name User name. See {@link RegisteredUser.name}.
* @param pw User password.
* @return User ID of registered user (See {@link RegisteredUser.userid}), -1 for failed authentication or -2 for unknown usernames.
*/
idempotent int verifyPassword(string name, string pw) throws ServerBootedException, InvalidSecretException;

/** Fetch user texture. Textures are stored as zlib compress()ed 600x60 32-bit BGRA data.
* @param userid ID of registered user. See {@link RegisteredUser.userid}.
* @return Custom texture associated with user or an empty texture.
*/
idempotent Texture getTexture(int userid) throws ServerBootedException, InvalidUserException, InvalidSecretException;

/** Set a user texture (now called avatar).
* @param userid ID of registered user. See {@link RegisteredUser.userid}.
* @param tex Texture (as a Byte-Array) to set for the user, or an empty texture to remove the existing texture.
*/
idempotent void setTexture(int userid, Texture tex) throws ServerBootedException, InvalidUserException, InvalidTextureException, InvalidSecretException;

/** Get virtual server uptime.
* @return Uptime of the virtual server in seconds
*/
idempotent int getUptime() throws ServerBootedException, InvalidSecretException;

/**
* Update the server's certificate information.
*
* Reconfigure the running server's TLS socket with the given
* certificate and private key.
*
* The certificate and and private key must be PEM formatted.
*
* New clients will see the new certificate.
* Existing clients will continue to see the certificate the server
* was using when they connected to it.
*
* This method throws InvalidInputDataException if any of the
* following errors happen:
* - Unable to decode the PEM certificate and/or private key.
* - Unable to decrypt the private key with the given passphrase.
* - The certificate and/or private key do not contain RSA keys.
* - The certificate is not usable with the given private key.
*/
idempotent void updateCertificate(string certificate, string privateKey, string passphrase) throws ServerBootedException, InvalidSecretException, InvalidInputDataException;
};

/** Callback interface for Meta. You can supply an implementation of this to receive notifications
* when servers are stopped or started.
* If an added callback ever throws an exception or goes away, it will be automatically removed.
* Please note that all callbacks are done asynchronously; murmur does not wait for the callback to
* complete before continuing processing.
* @see ServerCallback
* @see Meta.addCallback
*/
interface MetaCallback {
/** Called when a server is started. The server is up and running when this event is sent, so all methods that
* need a running server will work.
* @param srv Interface for started server.
*/
void started(Server *srv);

/** Called when a server is stopped. The server is already stopped when this event is sent, so no methods that
* need a running server will work.
* @param srv Interface for started server.
*/
void stopped(Server *srv);
};

sequence<Server *> ServerList;

/** This is the meta interface. It is primarily used for retrieving the {@link Server} interfaces for each individual server.
**/
["amd"] interface Meta {
/** Fetch interface to specific server.
* @param id Server ID. See {@link Server.getId}.
* @return Interface for specified server, or a null proxy if id is invalid.
*/
idempotent Server *getServer(int id) throws InvalidSecretException;

/** Create a new server. Call {@link Server.getId} on the returned interface to find it's ID.
* @return Interface for new server.
*/
Server *newServer() throws InvalidSecretException;

/** Fetch list of all currently running servers.
* @return List of interfaces for running servers.
*/
idempotent ServerList getBootedServers() throws InvalidSecretException;

/** Fetch list of all defined servers.
* @return List of interfaces for all servers.
*/
idempotent ServerList getAllServers() throws InvalidSecretException;

/** Fetch default configuraion. This returns the configuration items that were set in the configuration file, or
* the built-in default. The individual servers will use these values unless they have been overridden in the
* server specific configuration. The only special case is the port, which defaults to the value defined here +
* the servers ID - 1 (so that virtual server #1 uses the defined port, server #2 uses port+1 etc).
* @return Default configuration of the servers.
*/
idempotent ConfigMap getDefaultConf() throws InvalidSecretException;

/** Fetch version of Murmur.
* @param major Major version.
* @param minor Minor version.
* @param patch Patchlevel.
* @param text Textual representation of version. Note that this may not match the {@link major}, {@link minor} and {@link patch} levels, as it
* may be simply the compile date or the SVN revision. This is usually the text you want to present to users.
*/
idempotent void getVersion(out int major, out int minor, out int patch, out string text);

/** Add a callback. The callback will receive notifications when servers are started or stopped.
*
* @param cb Callback interface which will receive notifications.
*/
void addCallback(MetaCallback *cb) throws InvalidCallbackException, InvalidSecretException;

/** Remove a callback.
*
* @param cb Callback interface to be removed.
*/
void removeCallback(MetaCallback *cb) throws InvalidCallbackException, InvalidSecretException;
/** Get murmur uptime.
* @return Uptime of murmur in seconds
*/
idempotent int getUptime();

/** Get slice file.
* @return Contents of the slice file server compiled with.
*/
idempotent string getSlice();

/** Returns a checksum dict for the slice file.
* @return Checksum dict
*/
idempotent Ice::SliceChecksumDict getSliceChecksums();
};
};

View File

@ -0,0 +1,79 @@
[ICE]

# Examples:
# fqdn.domain.tld
# 127.0.0.1
# shorthost
# ::1
host = localhost

# The port ICE is running on
port = 6502

# One of udp or tcp. You probably want to use tcp.
proto = tcp

# You probably will need to change this.
# If you need a copy, you can get the most recent at:
# https://github.com/mumble-voip/mumble/blob/master/src/murmur/Murmur.ice
# If you leave this empty ("slice = "), we will attempt to fetch the slice from the remote
# instance ("host" above).
slice = /usr/local/lib/optools/mumble/murmur.ice

# The maximum size for ICE Messages (in KB)
# You're probably fine with the default.
max_size = 1024


[AUTH]

# The Ice secret for read-only operations.
# Set to a blank string if you want to only make a write-only connection.
read =

# The Ice secret for write-only operations.
# Set to a blank string if you want to only make a read-only connection.
write =

[TUNNEL]
# NOTE: TO USE SSH TUNNELING, YOU MUST HAVE THE PARAMIKO PYTHON MODULE INSTALLED.
# If enabled, we will bind the remote port to the host and port given in the [ICE] section.
# So you probably want to use localhost/127.0.0.1/::1 up there, and if you're
# running this script as a non-root user (you should be), then you'll want an
# ephemeral/non-privileged port that doesn't have anything bound to it.

# If this is enabled, we will try to initiate an SSH tunnel to the remote server,
# and use the Ice interface through that. Probably only works with TCP Ice instances.
# "enable" should be true or false. If blank, assume true. It's a VERY GOOD IDEA
# to use this feature, as it greatly heightens the security.
enable = true

# The remote host to bind a port with. In most cases, this is going to be the host
# that your Murmur instance is running on.
host = your.murmur.server.tld

# The remote user to auth as. If blank, use the current (local) username.
user =

# The port for SSH. In most cases, 22 is what you want. You can leave it blank,
# we'll use the default in that case.
port = 22

# The authentication method. Currently supported methods are "key" and "passphrase".
# Key is recommended (and the default). See:
# https://sysadministrivia.com/news/hardening-ssh-security#auth_client
# (and/or a multitude of other resources) on how to set up pubkey auth for SSH.
auth = key

# If "auth" is "password", enter the password here. If password auth is used
# and no password is provided, you will be prompted to enter it.
passphrase =

# If "auth" is "key", enter the path to the *private* (not public) key here.
# If none is provided, we'll use the default of ~/.ssh/id_rsa.
# Note that if your key is password-protected, you should enable "key_passphrase".
key = ~/.ssh/id_rsa

# Should we (securely) prompt for a key_passphrase? This is REQUIRED if your key
# is password-protected and you're using key authentication. Can be "true" or "false".
key_passphrase = false

434
mumble/usrmgmt2.py Executable file
View File

@ -0,0 +1,434 @@
#!/usr/bin/env python3
# Thanks to https://github.com/alfg/murmur-rest/blob/master/app/__init__.py

import argparse
from collections import defaultdict
import configparser
import datetime
import email.utils
import getpass
import hashlib
import Ice # python-zeroc-ice in AUR
import IcePy # python-zeroc-ice in AUR
import getpass
import os
import re
import subprocess
import sys
import tempfile


class IceMgr(object):
def __init__(self, args):
self.args = args
if 'interactive' not in self.args.keys():
self.args['interactive'] = False
if self.args['verbose']:
import pprint
self.getCfg()
self.connect()

def getCfg(self):
_cfg = os.path.join(os.path.abspath(os.path.expanduser(self.args['cfgfile'])))
if not os.path.isfile(_cfg):
raise FileNotFoundError('{0} does not exist!'.format(_cfg))
return()
_parser = configparser.ConfigParser()
_parser._interpolation = configparser.ExtendedInterpolation()
_parser.read(_cfg)
self.cfg = defaultdict(dict)
for section in _parser.sections():
self.cfg[section] = {}
for option in _parser.options(section):
self.cfg[section][option] = _parser.get(section, option)
return()

def sshTunnel(self):
try:
import paramiko
except ImportError:
raise ImportError('You must install Paramiko to use SSH tunneling!')
# This is the start of an ugly, ugly hack.
# All because, to my knowledge, Paramiko can't guess the key type and still
# let us use .connect() with a passphrase on the key, etc. etc.
_keyidmap = {'dsa': 'DSS',
'ecdsa': 'ECDSA',
'ed25519': 'Ed25519',
'rsa': 'RSA'}
_sshcfg = self.cfg['TUNNEL']
# Do some munging to make this easier to deal with.
if _sshcfg['user'] == '':
_sshcfg['user'] = getpass.getuser()
if _sshcfg['port'] == '':
_sshcfg['port'] = 22
else:
_sshcfg['port'] = int(_sshcfg['port'])
if _sshcfg['auth'].lower() == 'passphrase':
if _sshcfg['passphrase'] == '':
_sshcfg['passphrase'] = getpass.getpass(('What passphrase should ' +
'we use for {0}@{1}:{2}? (Will not ' +
'echo back.)\nPassphrase: ').format(
_sshcfg['user'],
_sshcfg['host'],
_sshcfg['port'])).encode('utf-8')
else:
_sshcfg['passphrase'] = _sshcfg['passphrase'].encode('utf-8')
_sshcfg['key'] = None
else:
if _sshcfg['key'] == '':
_sshcfg['key'] = '~/.ssh/id_rsa'
_key = os.path.abspath(os.path.expanduser(_sshcfg['key']))
# We need to convert it to a Paramiko Pkey type.
if _sshcfg['key_passphrase'].lower() == 'true':
_keypass = getpass.getpass(('What is the passphrase for {0}? ' +
'(Will not be echoed back.)\nPassphrase: ')).encode('utf-8')
else:
_keypass = None
# Remember that "ugly hack" I mention at the beginning of this method?
# Here's the rest of it. Recoil in terror.
_cmd = subprocess.run(['ssh-keygen', '-l', '-f', _key],
stdout = subprocess.PIPE)
_kt = re.sub('[()]', '', _cmd.stdout.decode('utf-8').split()[-1]).lower()
_keyfunc = getattr(paramiko, '{0}Key'.format(_keyidmap[_kt]))
_sshcfg['key'] = _keyfunc.from_private_key_file(_key,
_keypass)
# That... was painful. But it *works*, darn it!
#self.ssh = paramiko.SSHClient()
self.ssh = paramiko.Transport((_sshcfg['host'],
_sshcfg['port']))
#self.ssh.set_missing_host_key_policy(paramiko.AutoAddPolicy())
self.ssh.connect(_sshcfg['host'],
username = _sshcfg['user'],
password = _ssh['passphrase'],
pkey = _sshcfg['key'])
return()

def connect(self):
if self.cfg['TUNNEL']['enable'].lower() == 'true':
self.sshTunnel()
_props = {'ImplicitContext': 'Shared',
'Default.EncodingVersion': '1.0',
'MessageSizeMax': str(self.cfg['ICE']['max_size'])}
_prop_data = Ice.createProperties()
for k, v in _props.items():
_prop_data.setProperty('Ice.{0}'.format(k), v)
_conn = Ice.InitializationData()
_conn.properties = _prop_data
self.ice = Ice.initialize(_conn)
_host = 'Meta:{0} -h {1} -p {2}'.format(self.cfg['ICE']['proto'],
self.cfg['ICE']['host'],
self.cfg['ICE']['port'])
_ctx = self.ice.stringToProxy(_host)
# I owe a lot of neat tricks here to:
# https://raw.githubusercontent.com/mumble-voip/mumble-scripts/master/Helpers/mice.py
# Namely, the load-slice-from-server stuff especially
_slicedir = Ice.getSliceDir()
if not _slicedir:
_slicedir = ["-I/usr/share/Ice/slice", "-I/usr/share/slice"]
else:
_slicedir = ['-I' + _slicedir]
if self.cfg['ICE']['slice'] == '':
if IcePy.intVersion() < 30500:
# Old 3.4 signature with 9 parameters
_op = IcePy.Operation('getSlice',
Ice.OperationMode.Idempotent,
Ice.OperationMode.Idempotent,
True,
(), (), (),
IcePy._t_string, ())
else:
# New 3.5 signature with 10 parameters.
_op = IcePy.Operation('getSlice',
Ice.OperationMode.Idempotent,
Ice.OperationMode.Idempotent,
True,
None,
(), (), (),
((), IcePy._t_string, False, 0),
())
_slice = _op.invoke(_ctx,
((), None))
(_filedesc, _filepath) = tempfile.mkstemp(suffix = '.ice')
_slicefile = os.fdopen(_filedesc, 'w')
_slicefile.write(_slice)
_slicefile.flush()
Ice.loadSlice('', _slicedir + [_filepath])
_slicefile.close()
os.remove(_filepath)
else: # A .ice file was explicitly defined in the cfg
_slicedir.append(os.path.join(os.path.abspath(os.path.expanduser(self.cfg['ICE']['slice']))))
Ice.loadSlice('', _slicedir)
import Murmur
self.conn = {}
if self.cfg['AUTH']['read'] != '':
_secret = self.ice.getImplicitContext().put("secret",
self.cfg['AUTH']['read'])
self.conn['read'] = Murmur.MetaPrx.checkedCast(_ctx)
else:
self.conn['read'] = False
if self.cfg['AUTH']['write'] != '':
_secret = self.ice.getImplicitContext().put("secret",
self.cfg['AUTH']['write'])
self.conn['write'] = Murmur.MetaPrx.checkedCast(_ctx)
else:
self.conn['write'] = False
return()

def dictify(self, obj):
# Thanks to:
# https://github.com/alfg/murmur-rest/blob/master/app/utils.py
# (Modified to be python 3 compatible)
_rv = {'_type': str(type(obj))}
if type(obj) in (bool, int, float, str, bytes):
return(obj)
if type(obj) in (list, tuple):
return([dictify(i) for i in obj])
if type(obj) == dict:
return(dict((str(k), dictify(v)) for k, v in obj.items()))
return(dictify(obj.__dict__))

def add(self):
_userinfo = {Murmur.UserInfo.UserName: self.args['UserName']}
if not self.conn['write']:
raise PermissionError('You do not have write access configured!')
if not (self.args['certhash'] or self.args['password']):
raise RuntimeError(('You must specify either a certificate hash ' +
'or a method for getting the password.'))
if self.args['certhash']: # it's a certificate fingerprint hash
_e = '{0} is not a valid certificate fingerprint hash.'.format(self.args['certhash'])
try:
# Try *really hard* to mahe sure it's a SHA1.
# SHA1s are 160 bits in length, in binary representation.
# (the string representations are 40 chars in hex).
# However, we use 161 because of the prefix python3 adds
# automatically: "0b". I know. "This should be 162!" Shut up, trust me.
# Change it to 162 and watch it break if you don't believe me.
h = int(self.args['certhash'], 16)
try:
assert len(bin(h)) == 161
#_userinfo[Murmur.UserInfo.UserPassword] = None
_userinfo[Murmur.UserInfo.UserHash] = self.args['UserHash']
except AssertionError:
raise ValueError(_e)
except (ValueError, TypeError):
raise ValueError(_e)
if self.args['UserPassword']: # it's a password
if self.args['UserPassword'] == 'stdin':
#self.args['password'] = hashlib.sha1(sys.stdin.read().replace('\n', '').encode('utf-8')).hexdigest().lower()
_userinfo[Murmur.UserInfo.UserPassword] = sys.stdin.read().replace('\n', '').encode('utf-8')
#_userinfo[Murmur.UserInfo.UserHash] = None
else:
_repeat = True
while _repeat == True:
_pass_in = getpass.getpass('What password should {0} have (will not echo back)? '.format(self.args['UserName']))
if not _pass_in or _pass_in == '':
print('Invalid password. Please re-enter: ')
else:
_repeat = False
#self.args['password'] = hashlib.sha1(_pass_in.replace('\n', '').encode('utf-8')).hexdigest().lower()
_userinfo[Murmur.UserInfo.UserPassword] = _pass_in.replace('\n', '').encode('utf-8')
#_userinfo[Murmur.UserInfo.UserHash] = None
# Validate the email address
if self.args['UserEmail']:
_email = email.utils.parseaddr(self.args['UserEmail'])
# This is a stupidly simplified regex. For reasons why, see:
# https://stackoverflow.com/questions/8022530/python-check-for-valid-email-address
# http://www.regular-expressions.info/email.html
# TL;DR: email is really fucking hard to regex against,
# even (especially) if you follow RFC5322, and I don't want to have
# to rely on https://pypi.python.org/pypi/validate_email
if not re.match('[^@]+@[^@]+\.[^@]+', _email[1]):
raise ValueError('{0} is not a valid email address!'.format(self.args['UserEmail']))
else:
_userinfo[Murmur.UserInfo.UserEmail] = _email[1]
#else:
# _userinfo[Murmur.UserInfo.UserEmail] = None
if self.args['UserComment']:
_userinfo[Murmur.UserInfo.UserComment] = self.args['UserComment']
# Set a dummy LastActive
_userinfo[Murmur.UserInfo.LastActive] = str(datetime.datetime.now().strftime('%Y-%m-%d %H:%M:%S'))
# Now we Do the Thing(TM)
_server = self.conn['write'].getServer(self.args['server'])
_regid = _server.registerUser(_userinfo)
# And a little more Doing the Thing(TM), add groups.
# This is... a little convoluted.
# See https://sourceforge.net/p/mumble/discussion/492607/thread/579de8f9/
if args['groups']:
# First we get the ACL listings. The groups are *actually stored in
# the ACLs*, which is... insane to me, sort of, but whatever.
_acl = _server.getACL()
# Then build a dict of all groups to assign.
_groups = {}
for g in self.args['groups'].split(','):
_g = g.strip().split(':')
if _g[0] not in _groups.keys():
_groups[_g[0]] = [g[1]]
else:
_groups[_g[0]].append(_g[1])
# Now we need to see which groups currently exist and which down't.
if sys.stdout.isatty():
print('Added user {0} (UID: {1})'.format(self.args['UserName'],
_regid))
if self.args['verbose']:
_u = _server.getRegistration(_regid)
pprint.pprint(self.dictify(_u))

return()

def rm(self):
pass

def lsUsers(self):
pass

def lsGroups(self):
pass

def edit(self):
pass

def status(self):
# https://github.com/alfg/murmur-rest/blob/master/app/api.py#L71
pass

def close(self):
self.ice.destroy()
return()

def parseArgs():
_cfgfile = os.path.abspath(os.path.join(os.path.expanduser('~'),
'.config',
'optools',
'mumbleadmin.ini'))
commonargs = argparse.ArgumentParser(add_help = False)
reqcommon = commonargs.add_argument_group('REQUIRED common arguments')
optcommon = argparse.ArgumentParser(add_help = False)
reqcommon.add_argument('-u', '--user',
type = str,
dest = 'UserName',
required = True,
help = 'The username to perform the action for.')
reqcommon.add_argument('-s', '--server',
type = int,
dest = 'server',
default = 1,
help = ('The server ID. ' +
'Defaults to \033[1m{0}\033[0m').format(1))
optcommon.add_argument('-f', '--config',
type = str,
dest = 'cfgfile',
metavar = '/path/to/mumbleadmin.ini',
default = _cfgfile,
help = ('The path to the configuration file ' +
'("mumleadmin.ini"). Default: \033[1m{0}\033[0m').format(_cfgfile))
optcommon.add_argument('-v', '--verbose',
dest = 'verbose',
action = 'store_true',
help = ('If specified, print more information than normal'))
args = argparse.ArgumentParser(epilog = 'This program has context-sensitive help (e.g. try "... add --help")')
subparsers = args.add_subparsers(help = 'Operation to perform',
dest = 'operation')
addargs = subparsers.add_parser('add',
parents = [commonargs, optcommon],
help = 'Add a user to the Murmur database')
delargs = subparsers.add_parser('rm',
parents = [commonargs, optcommon],
help = 'Remove a user from the Murmur database')
listargs = subparsers.add_parser('ls',
parents = [optcommon],
help = 'List users in the Murmur database')
editargs = subparsers.add_parser('edit',
parents = [commonargs, optcommon],
help = 'Edit a user in the Murmur database')
# Operation-specific optional arguments
# Why did I even add this? It's not used *anywhere*.
#addargs.add_argument('-n', '--name',
# type = str,
# metavar = '"Firstname Lastname"',
# dest = 'name',
# default = None,
# help = 'The new user\'s (real) name')
addargs.add_argument('-c', '--comment',
type = str,
metavar = '"This comment becomes the user\'s profile."',
dest = 'UserComment',
default = None,
help = 'The comment for the new user')
addargs.add_argument('-e', '--email',
type = str,
metavar = 'email@domain.tld',
dest = 'UserEmail',
default = None,
help = 'The email address for the new user')
addargs.add_argument('-C', '--certhash',
type = str,
metavar = 'CERTIFICATE_FINGERPRINT_HASH',
default = None,
dest = 'UserHash',
help = ('The certificate fingerprint hash. See gencerthash.py. ' +
'This is the preferred way. ' +
'If you do not specify this, you must specify -p/--passwordhash'))
addargs.add_argument('-p', '--password',
type = str,
dest = 'UserPassword',
choices = ['stdin', 'prompt'],
default = None,
help = ('If not specified, you must specify -C/--certhash. Otherwise, either ' +
'\'stdin\' (the password is being piped into this program) or \'prompt\' ' +
'(a password will be asked for in a non-echoing prompt). "prompt" is much more secure and recommended.'))
addargs.add_argument('-g', '--groups',
type = str,
metavar = 'CHANID:GROUP1(,CHANID:GROUP2,CHANID:GROUP3...)',
default = None,
help = ('A comma-separated list of groups the user should be added to. If a group ' +
'doesn\'t exist, it will be created. CHANID is a ' +
'numerical ID of the channel to assign the group to. ' +
'(You can get channel IDs by doing "... ls -gv".) ' +
'If no CHANID is provided, the root channel (0) will be used.'))
# Listing should only take the DB as the "common" arg
listargs.add_argument('-g', '--groups',
action = 'store_true',
dest = 'groups',
help = 'If specified, list groups (and their members), not users')
listargs.add_argument('-s', '--server',
type = str,
dest = 'server',
default = None,
help = 'The server ID. Defaults to all servers. Specify one by the numerical ID.')
# Deleting args
delargs.add_argument('-n', '--no-prune',
dest = 'noprune',
action = 'store_true',
help = ('If specified, do NOT remove the ACLs and user info for the user as well (profile, ' +
'certificate fingerprint, etc.)'))
delargs.add_argument('-P', '--prune-groups',
dest = 'prunegrps',
action = 'store_true',
help = ('If specified, remove any groups the user was in ' +
'that are now empty (i.e. the user was the only member)'))
return(args)

def main():
args = vars(parseArgs().parse_args())
if not args['operation']:
#raise RuntimeError('You must specify an operation to perform. Try running with -h/--help.')
exit('You must specify an operation to perform. Try running with -h/--help.')
args['interactive'] = True
mgmt = IceMgr(args)
if args['operation'] == 'add':
mgmt.add()
elif args['operation'] == 'rm':
mgmt.rm()
elif args['operation'] == 'ls':
if not args['groups']:
mgmt.lsUsers()
else:
mgmt.lsGroups()
elif args['operation'] == 'edit':
mgmt.edit()
else:
pass # No-op because something went SUPER wrong.
mgmt.close()

if __name__ == '__main__':
main()