def main(): keychain_file = get_apsd_configuration().keychain fh = open(keychain_file) apsd_prefs = get_apsd_preferences() password = calculate_apsd_keychain_password(apsd_prefs) master_key = getdbkey(fh, password) keychain = Keychain(fh) # record type 16 - private keys # see CSSM_DL_DB_RECORD_PRIVATE_KEY in cssmtype.h (libsecurity_cssm) table = keychain.table_by_record_type(16) record = table.find_record_by_attribute("PrintName", apsd_prefs["CertificateName"]) key = decrypt_rsa_key(record.data, master_key) key_pem = rsa_key_der_to_pem(key) certificate_pem = extract_certificate(keychain_file) push_cert_file = join(CERT_PATH, apsd_prefs["CertificateName"] + ".pem") cert_fh = sys.stdout if len(sys.argv) > 1 and sys.argv[1] == "-f": cert_fh = open(push_cert_file, "wb") sys.stderr.write("Writing private key and certificate to %s\n" % push_cert_file) cert_fh.write(key_pem) cert_fh.write(certificate_pem)
def main(): keychain_file = get_apsd_configuration().keychain fh = open(keychain_file) apsd_prefs = get_apsd_preferences() password = calculate_apsd_keychain_password(apsd_prefs) master_key = getdbkey(fh, password) keychain = Keychain(fh) # record type 16 - private keys # see CSSM_DL_DB_RECORD_PRIVATE_KEY in cssmtype.h (libsecurity_cssm) table = keychain.table_by_record_type(16) record = table.find_record_by_attribute('PrintName', apsd_prefs['CertificateName']) key = decrypt_rsa_key(record.data, master_key) key_pem = rsa_key_der_to_pem(key) certificate_pem = extract_certificate(keychain_file) push_cert_file = join(CERT_PATH, apsd_prefs['CertificateName'] + '.pem') cert_fh = sys.stdout if len(sys.argv) > 1 and sys.argv[1] == '-f': cert_fh = open(push_cert_file, 'wb') sys.stderr.write('Writing private key and certificate to %s\n' % push_cert_file) cert_fh.write(key_pem) cert_fh.write(certificate_pem)
class Preferences(NSWindowController): # IBOutlets email = IBOutlet() password = IBOutlet() def init(self): NSLog('Preferences: init') self = super(Preferences, self).init() self.initWithWindowNibName_('Preferences') return self def awakeFromNib(self): NSLog('Preferences: awakeFromNib') self.keychain = Keychain() # We need to get the account email so we can do the keychain lookup try: f = open('account') except IOError: pass else: account = f.readline() # If there is no value then the details haven't been set yet if account != '': account = account.replace('\n', '') key = self.keychain.getgenericpassword('login', account) # If the keychain exists then we can set the default value for the fields if key != False: NSLog('Preferences: awakeFromNib - keychain exists, setting fields') self.email.setStringValue_(key['account']) self.password.setStringValue_(key['password']) @IBAction def problem_(self, sender): NSLog('Preferences: problem_') ws = NSWorkspace.sharedWorkspace() url = NSURL.URLWithString_('http://www.google.com/support/accounts/bin/answer.py?answer=48598') ws.openURL_(url) @IBAction def showWindow_(self, sender): NSLog('Preferences: showWindow') super(Preferences, self).showWindow_(sender) @IBAction def save_(self, sender): NSLog('Preferences: save_') self.keychain.setgenericpassword('login', self.email.stringValue(), self.password.stringValue(), 'GFGain') # Save the account email so we can use it later f = open('account', 'w') f.write(self.email.stringValue()) f.close() self.close()
def save_db(creds, password=''): creds['password'] = password and hexlify(encrypt(password, creds['password'])) or creds['password'] creds['username'] = password and hexlify(encrypt(password, creds['username'])) or creds['username'] keychain = Keychain() account = getlogin() password = "******" % (creds['username'], JOIN_STRING, creds['password']) return keychain.set_generic_password(KEYCHAIN, account, password, SERVICE_NAME)
def __init__(self, *args, **kwargs): Keychain.__init__(self, *args, **kwargs) self.kcName = "TemplateDesigner" self.kcPassword = "******" self.kcLock = True self.kcTimeout = 300 self.recursionTest = False self.testKeyChain()
def load_db(password=''): creds = {} keychain = Keychain() account = getlogin() payload = keychain.get_generic_password(KEYCHAIN, account, SERVICE_NAME) if payload and 'password' in payload: parts = payload['password'].split(JOIN_STRING) if(len(parts) > 1): creds['password'] = password and decrypt(password, unhexlify(parts[1])) or parts[1] creds['username'] = password and decrypt(password, unhexlify(parts[0])) or parts[0] return creds
def __init__(self, stdin=sys.stdin, stdout=sys.stdout, stderr=sys.stderr, getpass=getpass.getpass, arguments=sys.argv[1:]): self.stdin = stdin self.stdout = stdout self.stderr = stderr self.getpass = getpass self.arguments = self.argument_parser().parse_args(arguments) self.keychain = Keychain(self.arguments.path)
def __init__(self): super(App, self).__init__("HipStatus") self.icon = _menu_bar_icon(0) self.preferences = Preferences() self._validate_preferences() self.keychain = Keychain(self.preferences.email()) self._validate_keychain() self.hipchat = HipChat(self.keychain.read_token()) self.office365 = Office365(self.preferences.email(), self.keychain.read_o365()) self.menu_pause_button = rumps.MenuItem("Pause HipStatus", self.timer_pause) self.menu_preferences = rumps.MenuItem('Preferences...') self.menu = [ self.menu_pause_button, rumps.separator, self.menu_preferences, rumps.separator ] self.menu_preferences_message = rumps.MenuItem( "", self.preferences_message) if self.preferences.default_message(): self.menu_preferences_message.title = self.preferences.default_message( ) else: self.menu_preferences_message.title = "None..." self.menu_preferences_email = rumps.MenuItem( "Change email address", self.preferences_update_email) self.menu_preferences_o365 = rumps.MenuItem( "Update saved Office 365 password", self.preferences_update_o365) self.menu_preferences_token = rumps.MenuItem( "Update saved HipChat token", self.preferences_update_token) self.menu_preferences_get_token = rumps.MenuItem( "Get your HipChat token", open_browser) self.menu_preferences.add(rumps.MenuItem('Status message...')) self.menu_preferences.add(self.menu_preferences_message) self.menu_preferences.add(rumps.separator) self.menu_preferences.add(rumps.MenuItem('Preferences...')) self.menu_preferences.add(self.menu_preferences_email) self.menu_preferences.add(self.menu_preferences_o365) self.menu_preferences.add(self.menu_preferences_token) self.menu_preferences.add(rumps.separator) self.menu_preferences.add(self.menu_preferences_get_token) self.main_timer = rumps.Timer(self.timer_trigger, 300) self.main_timer.start()
def get_item(query, property, wf): keychain_file = wf.settings.get('keychain_file', None) if not keychain_file: return '503: No keychain file set' query = query.split('|||') try: keychain = Keychain(keychain_file) item = keychain.get_item(query[0], query[1]) return getattr(item, property) except KeychainItemNotFound: return '404: ' + query[0] except: return '400: ' + query[0]
def get_login_parameters(config_dict) : """ Get the login details from the keychain """ keychain = Keychain() keychain_service = config_dict['keychain_service'] spider_data = keychain.get_generic_password('login', servicename = keychain_service) user = spider_data['account'] user32 = re.search('^([^=]*)(==*)$', base64.b32encode(user)).group(1) password = spider_data['password'] return user32, password
class PasswordStore: def __init__(self, chain="login", account=None, service=None): if account is None: account = keyinfo.account if service is None: service = keyinfo.realm self.chain = chain self.account = account self.service = service self.keychain = Keychain() def unlock(self): self.keychain.unlockkeychain(self.chain) def lock(self): self.keychain.lockkeychain(chain) def password(self, account=None): if account is None: account = self.account _, password = self.keychain.getgenericpassword(self.chain, account, self.service) return password def save_password(self, password, account=None): if account is None: account = keyinfo.account self.keychain.setgenericpassword(self.chain, account, password, self.service)
def __init__(self, chain="login", account=None, service=None): if account is None: account = keyinfo.account if service is None: service = keyinfo.realm self.chain = chain self.account = account self.service = service self.keychain = Keychain()
def decrypt_item(self, row): version, clas = struct.unpack("<LL", row["data"][0:8]) if version >= 2: dict = self.decrypt_blob(row["data"]) if "v_Data" in dict: dict["data"] = dict["v_Data"].data else: dict["data"] = "-- empty --" dict["rowid"] = row["rowid"] return dict return Keychain.decrypt_item(self, row)
def main(argv=None): if argv is None: argv = sys.argv try: message = argv[1] except IndexError: message = None if not message: growl.notify("failure", "No message", "You need to actually say something!") return # Check length # TODO: use URL shortening service if len(message) > MAX_MSG: growl.notify("failure", "Message too long", "%d characters, %d allowed." % (len(message), MAX_MSG)) return # get credentials: keychain = Keychain() credentials = keychain.get_generic_password('login', servicename='Twitterrific') # getgenericpassword returns a tuple upon error but a dict on success, duh: if type(credentials) == type(tuple): # if Twitterific hasn't stored credentials, we try a generic key credentials = keychain.get_generic_password('login', item=FALLBACK_KEY) if type(credentials) == type(tuple): # notify the user about where to store credentials, if none are stored growl.notify("failure", "No credentials", "Please add username/password to your login keychain with the item name '%s'" \ % FALLBACK_KEY, sticky=True) return # post the message twit = Twitter(credentials['account'], credentials['password'], agent=AGENT_STR) message = (message.encode('utf8', 'replace')) twit.statuses.update(status=message) growl.notify("success", "Tweet sent.", message)
def decrypt_item(self, row): version, clas = struct.unpack("<LL", row["data"][0:8]) if self.keybag.isBackupKeybag(): if clas >= 9 and not self.keybag.deviceKey: return {} if version >= 2: dict = self.decrypt_blob(row["data"]) if not dict: return {} if dict.has_key("v_Data"): dict["data"] = dict["v_Data"].data else: dict["data"] = "" dict["rowid"] = row["rowid"] return dict return Keychain.decrypt_item(self, row)
def GetGain(self): NSLog('AppDelegate: GetGain') if self.gf == False: NSLog('AppDelegate: GetGain - gf == False') # We need to get the account email so we can do the keychain lookup try: f = open('account') except IOError: pass else: account = f.readline() # If there is no value then the details haven't been set yet if account != '': account = account.replace('\n', '') # Don't need the trailing newline character if self.keychain == False: NSLog('AppDelegate: GetGain - keychain == false') self.keychain = Keychain() key = self.keychain.getgenericpassword('login', account) print key # Can we create the GoogleFinance object from the keychain? if key != False: NSLog('AppDelegate: GetGain - Keychain details exist') self.gf = GoogleFinance(key['account'], key['password']) else: NSLog('AppDelegate: GetGain - Keychain details don\'t exist') if self.gf != False: # GoogleFinance exists so we can reget the gain data NSLog('AppDelegate: GetGain - Getting gain') self.statusItem.setTitle_('Updating...') gain = '%.2f' % self.gf.GetGain() self.statusItem.setTitle_(gain) else: # User needs to set their prefs NSLog('AppDelegate: GetGain - gf == false (again)') self.statusItem.setTitle_('Click to set prefs')
def __init__(self): super(App, self).__init__("HipStatus") self.icon = _menu_bar_icon(0) self.preferences = Preferences() self._validate_preferences() self.keychain = Keychain(self.preferences.email()) self._validate_keychain() self.hipchat = HipChat(self.keychain.read_token()) self.office365 = Office365(self.preferences.email(), self.keychain.read_o365()) self.menu_pause_button = rumps.MenuItem("Pause HipStatus", self.timer_pause) self.menu_preferences = rumps.MenuItem('Preferences...') self.menu = [self.menu_pause_button, rumps.separator, self.menu_preferences, rumps.separator] self.menu_preferences_message = rumps.MenuItem("", self.preferences_message) if self.preferences.default_message(): self.menu_preferences_message.title = self.preferences.default_message() else: self.menu_preferences_message.title = "None..." self.menu_preferences_email = rumps.MenuItem("Change email address", self.preferences_update_email) self.menu_preferences_o365 = rumps.MenuItem("Update saved Office 365 password", self.preferences_update_o365) self.menu_preferences_token = rumps.MenuItem("Update saved HipChat token", self.preferences_update_token) self.menu_preferences_get_token = rumps.MenuItem("Get your HipChat token", open_browser) self.menu_preferences.add(rumps.MenuItem('Status message...')) self.menu_preferences.add(self.menu_preferences_message) self.menu_preferences.add(rumps.separator) self.menu_preferences.add(rumps.MenuItem('Preferences...')) self.menu_preferences.add(self.menu_preferences_email) self.menu_preferences.add(self.menu_preferences_o365) self.menu_preferences.add(self.menu_preferences_token) self.menu_preferences.add(rumps.separator) self.menu_preferences.add(self.menu_preferences_get_token) self.main_timer = rumps.Timer(self.timer_trigger, 300) self.main_timer.start()
def decrypt_item(self, row): version, clas = struct.unpack("<LL", row["data"][0:8]) clas &= 0xF if self.keybag.isBackupKeybag(): if clas >= 9 and not self.keybag.deviceKey: return {} if version >= 2: dict = self.decrypt_blob(row["data"]) if not dict: return {"clas": clas, "rowid": row["rowid"]} if dict.has_key("v_Data"): try: dict["data"] = dict["v_Data"].data except AttributeError: dict["data"] = dict["v_Data"] else: dict["data"] = "" dict["rowid"] = row["rowid"] dict["clas"] = clas return dict row["clas"] = clas return Keychain.decrypt_item(self, row)
def awakeFromNib(self): NSLog('Preferences: awakeFromNib') self.keychain = Keychain() # We need to get the account email so we can do the keychain lookup try: f = open('account') except IOError: pass else: account = f.readline() # If there is no value then the details haven't been set yet if account != '': account = account.replace('\n', '') key = self.keychain.getgenericpassword('login', account) # If the keychain exists then we can set the default value for the fields if key != False: NSLog('Preferences: awakeFromNib - keychain exists, setting fields') self.email.setStringValue_(key['account']) self.password.setStringValue_(key['password'])
class App(rumps.App): """This is the main class that runs the HipStatus app""" def __init__(self): super(App, self).__init__("HipStatus") self.icon = _menu_bar_icon(0) self.preferences = Preferences() self._validate_preferences() self.keychain = Keychain(self.preferences.email()) self._validate_keychain() self.hipchat = HipChat(self.keychain.read_token()) self.office365 = Office365(self.preferences.email(), self.keychain.read_o365()) self.menu_pause_button = rumps.MenuItem("Pause HipStatus", self.timer_pause) self.menu_preferences = rumps.MenuItem('Preferences...') self.menu = [ self.menu_pause_button, rumps.separator, self.menu_preferences, rumps.separator ] self.menu_preferences_message = rumps.MenuItem( "", self.preferences_message) if self.preferences.default_message(): self.menu_preferences_message.title = self.preferences.default_message( ) else: self.menu_preferences_message.title = "None..." self.menu_preferences_email = rumps.MenuItem( "Change email address", self.preferences_update_email) self.menu_preferences_o365 = rumps.MenuItem( "Update saved Office 365 password", self.preferences_update_o365) self.menu_preferences_token = rumps.MenuItem( "Update saved HipChat token", self.preferences_update_token) self.menu_preferences_get_token = rumps.MenuItem( "Get your HipChat token", open_browser) self.menu_preferences.add(rumps.MenuItem('Status message...')) self.menu_preferences.add(self.menu_preferences_message) self.menu_preferences.add(rumps.separator) self.menu_preferences.add(rumps.MenuItem('Preferences...')) self.menu_preferences.add(self.menu_preferences_email) self.menu_preferences.add(self.menu_preferences_o365) self.menu_preferences.add(self.menu_preferences_token) self.menu_preferences.add(rumps.separator) self.menu_preferences.add(self.menu_preferences_get_token) self.main_timer = rumps.Timer(self.timer_trigger, 300) self.main_timer.start() def _validate_preferences(self): if not self.preferences.email().strip(): logging.warning("No email address on record in preferences") self.preferences_update_email(None) def _validate_keychain(self): try: self.keychain.read_o365() except KeychainValueNotFound: logging.warning("Office 365 password not found") self.keychain.write_o365("Enter Password") self.preferences_update_o365(None, menu_call=False) try: self.keychain.read_token() except KeychainValueNotFound: logging.warning("HipChat API token not found") self.keychain.write_token("Enter Token") self.preferences_update_token(None, menu_call=False) @rumps.notifications def notification_center(self, info): logging.debug("Notification has been clicked") if 'update_o365' in info: self.preferences_update_o365(None) elif 'update_token' in info: self.preferences_update_token(None) elif 'update_email' in info: self.preferences_update_email(None) elif 'open_ticket' in info: webbrowser.open(info['open_ticket']) else: pass def preferences_message(self, sender): text = self.preferences.default_message() if text is None: text = '' prompt = rumps.Window( "Leave blank to not set a status message", "Enter a message to display when you are set to 'Do not disturb'", text, dimensions=(275, 25)) result = prompt.run() self.preferences.default_message(result.text) if self.preferences.default_message(): self.menu_preferences_message.title = self.preferences.default_message( ) else: self.menu_preferences_message.title = "None..." def preferences_update_email(self, sender): text = self.preferences.email() logging.info("Prompting for new email") prompt = rumps.Window("", "Enter your email address", text, dimensions=(275, 25)) result = prompt.run() self.preferences.email(result.text) def preferences_update_o365(self, sender, message="", menu_call=True): text = self.keychain.read_o365() logging.info("Prompting for Office 365 password...") prompt = SecureRumpsWindow(message, "Enter your Office 365 password:"******"", menu_call=True): text = self.keychain.read_token() message = "Paste your key using Ctrl+Click on the text field" logging.info("Prompting for HipChat API token...") prompt = rumps.Window(message, "Enter your HipChat API token:", text, dimensions=(375, 25)) prompt.add_button('Get HipChat token...') result = prompt.run() if result.clicked == 2: open_browser() self.preferences_update_token( None, "Log into HipChat in the browser to copy your token, paste using " "Ctrl+Click on the text field", menu_call=menu_call) else: token = result.text self.keychain.write_token(token) if menu_call: self.hipchat.update_token(self.keychain.read_token()) def timer_pause(self, sender): if not sender.state: self.icon = _menu_bar_icon(1) sender.title = "Resume HipStatus" logging.info("User has paused HipStatus") else: self.icon = _menu_bar_icon(0) sender.title = "Pause HipStatus" logging.info("User has resumed HipStatus") sender.state = not sender.state def timer_trigger(self, sender): now = datetime.datetime.now() delta = (5 - (now.minute % 5)) * 60 - now.second logging.debug("Timer will execute in {} seconds".format(delta)) t = threading.Thread(target=self._update_status, args=[delta]) t.start() def _update_status(self, delay): time.sleep(delay) if self.menu_pause_button.state: logging.info("HipStatus is paused: status will not be updated") return now = datetime.datetime.utcnow().strftime("%Y-%m-%d %H:%M:%S") try: hipchat_user = self.hipchat.get_status(self.preferences.email()) except Unauthorized: rumps.notification( "Authentication error to HipChat", '', "It looks like something may be wrong with your API token. Click here to update, or use " "the 'Preferences...' menu option.", data={'update_token': ''}) return except UserNotFound: rumps.notification( "Could not find the user in HipChat", self.preferences.email(), "Your saved email address could not be found in HipChat. Click here to update, or use " "the 'Preferences...' menu option.", data={'update_email': ''}) return except (RateLimited, ServerError, ServiceUnavailable): rumps.notification( "There seems to be a problem with HipChat", '', "There was an error indicating an issue " "on HipChat's end. If the issue persists click here to open an IT Help ticket.", data={'open_ticket': ticket_url}) return if not hipchat_user['presence']: logging.info("The user is not online") return busy_hipstatus = True if hipchat_user['presence'][ 'show'] != 'chat' else False try: office365_calendar = self.office365.calendar_status(now) except Unauthorized: rumps.notification( "Authentication error to Office 365", '', "Something may be wrong with your Office 365 email address/password. Click here to try " "updating your password.", data={'update_o365': ''}) return except ServerError: rumps.notification( "There seems to be a problem with Office 365", '', "There was an error indicating an " "issue on Office 365's end. If the issue persists click here to open an IT Help ticket.", data={'open_ticket': ticket_url}) return if office365_calendar['value']: busy_office365 = True if office365_calendar['value'][0][ 'ShowAs'] == 'Busy' else False else: busy_office365 = False if busy_hipstatus == busy_office365: logging.info("Status unchanged") return message = '' update_data = { 'name': hipchat_user['name'], 'email': hipchat_user['email'], 'mention_name': hipchat_user['mention_name'], 'title': hipchat_user['title'], 'timezone': self.preferences.timezone(), 'is_group_admin': hipchat_user['is_group_admin'], 'presence': { 'status': None, 'show': None, } } if busy_hipstatus and not busy_office365: logging.info("Setting HipChat status to 'Available'") update_data['presence']['status'] = '' update_data['presence']['show'] = None message = "You are now 'Available'" elif busy_office365 and not busy_hipstatus: logging.info("Setting HipChat status to 'Do not disturb'") update_data['presence'][ 'status'] = self.preferences.default_message() update_data['presence']['show'] = 'dnd' message = "You are now set to 'Do not disturb'" self.hipchat.update_status(update_data) rumps.notification("Status Updated", message, "Your status in HipChat has been updated", sound=False)
def __init__(self, filename, keybag): if not keybag.unlocked: print "Keychain object created with locked keybag, some items won't be decrypted" Keychain.__init__(self, filename) self.keybag = keybag
class App(rumps.App): """This is the main class that runs the HipStatus app""" def __init__(self): super(App, self).__init__("HipStatus") self.icon = _menu_bar_icon(0) self.preferences = Preferences() self._validate_preferences() self.keychain = Keychain(self.preferences.email()) self._validate_keychain() self.hipchat = HipChat(self.keychain.read_token()) self.office365 = Office365(self.preferences.email(), self.keychain.read_o365()) self.menu_pause_button = rumps.MenuItem("Pause HipStatus", self.timer_pause) self.menu_preferences = rumps.MenuItem('Preferences...') self.menu = [self.menu_pause_button, rumps.separator, self.menu_preferences, rumps.separator] self.menu_preferences_message = rumps.MenuItem("", self.preferences_message) if self.preferences.default_message(): self.menu_preferences_message.title = self.preferences.default_message() else: self.menu_preferences_message.title = "None..." self.menu_preferences_email = rumps.MenuItem("Change email address", self.preferences_update_email) self.menu_preferences_o365 = rumps.MenuItem("Update saved Office 365 password", self.preferences_update_o365) self.menu_preferences_token = rumps.MenuItem("Update saved HipChat token", self.preferences_update_token) self.menu_preferences_get_token = rumps.MenuItem("Get your HipChat token", open_browser) self.menu_preferences.add(rumps.MenuItem('Status message...')) self.menu_preferences.add(self.menu_preferences_message) self.menu_preferences.add(rumps.separator) self.menu_preferences.add(rumps.MenuItem('Preferences...')) self.menu_preferences.add(self.menu_preferences_email) self.menu_preferences.add(self.menu_preferences_o365) self.menu_preferences.add(self.menu_preferences_token) self.menu_preferences.add(rumps.separator) self.menu_preferences.add(self.menu_preferences_get_token) self.main_timer = rumps.Timer(self.timer_trigger, 300) self.main_timer.start() def _validate_preferences(self): if not self.preferences.email().strip(): logging.warning("No email address on record in preferences") self.preferences_update_email(None) def _validate_keychain(self): try: self.keychain.read_o365() except KeychainValueNotFound: logging.warning("Office 365 password not found") self.keychain.write_o365("Enter Password") self.preferences_update_o365(None, menu_call=False) try: self.keychain.read_token() except KeychainValueNotFound: logging.warning("HipChat API token not found") self.keychain.write_token("Enter Token") self.preferences_update_token(None, menu_call=False) @rumps.notifications def notification_center(self, info): logging.debug("Notification has been clicked") if 'update_o365' in info: self.preferences_update_o365(None) elif 'update_token' in info: self.preferences_update_token(None) elif 'update_email' in info: self.preferences_update_email(None) elif 'open_ticket' in info: webbrowser.open(info['open_ticket']) else: pass def preferences_message(self, sender): text = self.preferences.default_message() if text is None: text = '' prompt = rumps.Window("Leave blank to not set a status message", "Enter a message to display when you are set to 'Do not disturb'", text, dimensions=(275, 25)) result = prompt.run() self.preferences.default_message(result.text) if self.preferences.default_message(): self.menu_preferences_message.title = self.preferences.default_message() else: self.menu_preferences_message.title = "None..." def preferences_update_email(self, sender): text = self.preferences.email() logging.info("Prompting for new email") prompt = rumps.Window("", "Enter your email address", text, dimensions=(275, 25)) result = prompt.run() self.preferences.email(result.text) def preferences_update_o365(self, sender, message="", menu_call=True): text = self.keychain.read_o365() logging.info("Prompting for Office 365 password...") prompt = SecureRumpsWindow(message, "Enter your Office 365 password:"******"", menu_call=True): text = self.keychain.read_token() message = "Paste your key using Ctrl+Click on the text field" logging.info("Prompting for HipChat API token...") prompt = rumps.Window(message, "Enter your HipChat API token:", text, dimensions=(375, 25)) prompt.add_button('Get HipChat token...') result = prompt.run() if result.clicked == 2: open_browser() self.preferences_update_token(None, "Log into HipChat in the browser to copy your token, paste using " "Ctrl+Click on the text field", menu_call=menu_call) else: token = result.text self.keychain.write_token(token) if menu_call: self.hipchat.update_token(self.keychain.read_token()) def timer_pause(self, sender): if not sender.state: self.icon = _menu_bar_icon(1) sender.title = "Resume HipStatus" logging.info("User has paused HipStatus") else: self.icon = _menu_bar_icon(0) sender.title = "Pause HipStatus" logging.info("User has resumed HipStatus") sender.state = not sender.state def timer_trigger(self, sender): now = datetime.datetime.now() delta = (5 - (now.minute % 5)) * 60 - now.second logging.debug("Timer will execute in {} seconds".format(delta)) t = threading.Thread(target=self._update_status, args=[delta]) t.start() def _update_status(self, delay): time.sleep(delay) if self.menu_pause_button.state: logging.info("HipStatus is paused: status will not be updated") return now = datetime.datetime.utcnow().strftime("%Y-%m-%d %H:%M:%S") try: hipchat_user = self.hipchat.get_status(self.preferences.email()) except Unauthorized: rumps.notification("Authentication error to HipChat",'', "It looks like something may be wrong with your API token. Click here to update, or use " "the 'Preferences...' menu option.", data={'update_token': ''}) return except UserNotFound: rumps.notification("Could not find the user in HipChat", self.preferences.email(), "Your saved email address could not be found in HipChat. Click here to update, or use " "the 'Preferences...' menu option.", data={'update_email': ''}) return except (RateLimited, ServerError, ServiceUnavailable): rumps.notification("There seems to be a problem with HipChat", '', "There was an error indicating an issue " "on HipChat's end. If the issue persists click here to open an IT Help ticket.", data={'open_ticket': ticket_url}) return if not hipchat_user['presence']: logging.info("The user is not online") return busy_hipstatus = True if hipchat_user['presence']['show'] != 'chat' else False try: office365_calendar = self.office365.calendar_status(now) except Unauthorized: rumps.notification("Authentication error to Office 365", '', "Something may be wrong with your Office 365 email address/password. Click here to try " "updating your password.", data={'update_o365': ''}) return except ServerError: rumps.notification("There seems to be a problem with Office 365", '', "There was an error indicating an " "issue on Office 365's end. If the issue persists click here to open an IT Help ticket.", data={'open_ticket': ticket_url}) return if office365_calendar['value']: busy_office365 = True if office365_calendar['value'][0]['ShowAs'] == 'Busy' else False else: busy_office365 = False if busy_hipstatus == busy_office365: logging.info("Status unchanged") return message = '' update_data = { 'name': hipchat_user['name'], 'email': hipchat_user['email'], 'mention_name': hipchat_user['mention_name'], 'title': hipchat_user['title'], 'timezone': self.preferences.timezone(), 'is_group_admin': hipchat_user['is_group_admin'], 'presence': { 'status': None, 'show': None, } } if busy_hipstatus and not busy_office365: logging.info("Setting HipChat status to 'Available'") update_data['presence']['status'] = '' update_data['presence']['show'] = None message = "You are now 'Available'" elif busy_office365 and not busy_hipstatus: logging.info("Setting HipChat status to 'Do not disturb'") update_data['presence']['status'] = self.preferences.default_message() update_data['presence']['show'] = 'dnd' message = "You are now set to 'Do not disturb'" self.hipchat.update_status(update_data) rumps.notification("Status Updated", message, "Your status in HipChat has been updated", sound=False)
def __init__(self, filename, keybag): if not keybag.unlocked: raise Exception("Keychain4 object created with locked keybag") Keychain.__init__(self, filename) self.keybag = keybag
class AppDelegate(NSObject): gf = False now = NSDate.date() preferences = False keychain = False def applicationDidFinishLaunching_(self, sender): NSLog('AppDelegate: applicationDidFinishLaunching') # Set this up as a class attribute so we can modify it later NSLog('AppDelegate: applicationDidFinishLaunching - setting up statusItem') self.statusItem = NSStatusBar.systemStatusBar().statusItemWithLength_(NSVariableStatusItemLength) self.statusItem.setHighlightMode_(TRUE) self.statusItem.setEnabled_(TRUE) self.statusItem.retain() # http://stackoverflow.com/questions/141432/how-can-i-create-a-status-bar-item-with-cocoa-and-python-pyobjc self.GetGain() # Build a simple menu for the statusItem NSLog('AppDelegate: applicationDidFinishLaunching - setting up menu') menu = NSMenu.alloc().init() menuitem = NSMenuItem.alloc().initWithTitle_action_keyEquivalent_('Preferences', 'launchPreferences:', '') menu.addItem_(menuitem) menuitem = NSMenuItem.alloc().initWithTitle_action_keyEquivalent_('Quit', 'terminate:', '') menu.addItem_(menuitem) self.statusItem.setMenu_(menu) # Set up the timer to periodically update the details # Timer help from http://the.taoofmac.com/space/blog/2007/04/22/1745 NSLog('AppDelegate: applicationDidFinishLaunching - setting up timer') self.timer = NSTimer.alloc().initWithFireDate_interval_target_selector_userInfo_repeats_(self.now, 60.0, self, 'tick:', None, True) NSRunLoop.currentRunLoop().addTimer_forMode_(self.timer, NSDefaultRunLoopMode) self.timer.fire() def GetGain(self): NSLog('AppDelegate: GetGain') if self.gf == False: NSLog('AppDelegate: GetGain - gf == False') # We need to get the account email so we can do the keychain lookup try: f = open('account') except IOError: pass else: account = f.readline() # If there is no value then the details haven't been set yet if account != '': account = account.replace('\n', '') # Don't need the trailing newline character if self.keychain == False: NSLog('AppDelegate: GetGain - keychain == false') self.keychain = Keychain() key = self.keychain.getgenericpassword('login', account) print key # Can we create the GoogleFinance object from the keychain? if key != False: NSLog('AppDelegate: GetGain - Keychain details exist') self.gf = GoogleFinance(key['account'], key['password']) else: NSLog('AppDelegate: GetGain - Keychain details don\'t exist') if self.gf != False: # GoogleFinance exists so we can reget the gain data NSLog('AppDelegate: GetGain - Getting gain') self.statusItem.setTitle_('Updating...') gain = '%.2f' % self.gf.GetGain() self.statusItem.setTitle_(gain) else: # User needs to set their prefs NSLog('AppDelegate: GetGain - gf == false (again)') self.statusItem.setTitle_('Click to set prefs') def launchPreferences_(self, notification): NSLog('AppDelegate: launchPreferences') self.preferences = Preferences.alloc().init() self.preferences.showWindow_(self) def tick_(self, notification): NSLog('AppDelegate: tick') # We only want to get the gain again if trading is ongoing (i.e. Mon - Fri 9:30 a.m. to 4:00 p.m EST) utc = time.gmtime() # Determine whether it is DST or not because if it is then the UTC offset will be different if utc[8] == 0: # EST = UTC - 5 hours (18000 seconds) NSLog('AppDelegate: tick - Timezone = EST') est = time.mktime(utc) - 18000 marketTime = time.gmtime(est) else: # If DST then EDT # EDT = UTC - 4 hours (14400 seconds) NSLog('AppDelegate: tick - Timezone = EDT') edt = time.mktime(utc) - 14400 marketTime = time.gmtime(edt) # If it is Fri or Sat, don't bother getting data if marketTime[6] == 5 or marketTime[6] == 6: NSLog('AppDelegate: tick - It\'s the weekend! Yay') open = False else: NSLog('AppDelegate: tick - Mon - Fri') # If it's after 9.30am then open, otherwise closed! if marketTime[3] == 9: if marketTime[4] >= 30: NSLog('AppDelegate: tick - 9...open') open = True else: NSLog('AppDelegate: tick - 9...closed') open = False # Define which hours are open to make it easier than devising crazy hour based logic hoursOpen = [10, 11, 12, 13, 14, 15] # So if it is within 10am, 11am, 12pm, 1pm, 2pm or 3pm then it's open. Before and after those closed if marketTime[3] not in hoursOpen: NSLog('AppDelegate: tick - closed') open = False else: NSLog('AppDelegate: tick - open') open = True; if open == True: self.GetGain()
def __init__(self, filename, key835=None): Keychain.__init__(self, filename) self.key835 = key835
class CLI(object): """ The 1pass command line interface. """ def __init__(self, stdin=sys.stdin, stdout=sys.stdout, stderr=sys.stderr, getpass=getpass.getpass, arguments=sys.argv[1:]): self.stdin = stdin self.stdout = stdout self.stderr = stderr self.getpass = getpass self.arguments = self.argument_parser().parse_args(arguments) self.keychain = Keychain(self.arguments.path) def run(self): """ The main entry point, performs the appropriate action for the given arguments. """ if not self.arguments.item: for k in self.keychain.get_items(): self.stdout.write("%s\n" % k) return self._unlock_keychain() item = self.keychain.item( self.arguments.item, fuzzy_threshold=self._fuzzy_threshold(), ) if item is not None: if self.arguments.all: for d in item._data: self.stdout.write("%s\n"%d) if d == 'fields': for i in item._data[d]: self.stdout.write("\t%s: %s\n"%(i['name'], i['value'])) elif d == 'URLs': for i in item._data[d]: self.stdout.write("\t%s\n"%(i['url'])) else: self.stdout.write("\t%s\n" % item._data[d]) elif self.arguments.username: self.stdout.write("%s %s\n" % (item.username, item.password)) else: self.stdout.write("%s\n" % item.password) else: self.stderr.write("1pass: Could not find an item named '%s'\n" % ( self.arguments.item, )) sys.exit(os.EX_DATAERR) def argument_parser(self): parser = argparse.ArgumentParser() parser.add_argument("item", help="The name of the key to decrypt," " if ommited prints out the list of all keys in the keychain", nargs="?") parser.add_argument( "-p", "--path", default=os.environ.get('ONEPASSWORD_KEYCHAIN', DEFAULT_KEYCHAIN_PATH), help="Path to your 1Password.agilekeychain file", ) parser.add_argument( "-f", "--fuzzy", action="store_true", help="Perform fuzzy matching on the item", ) parser.add_argument( "-n", "--no-prompt", action="store_true", help="Don't prompt for a password, read from STDIN instead", ) parser.add_argument( "-a", "--all", action="store_true", help="Print all information stored for the item.", ) parser.add_argument( "-u", "--username", action="store_true", help="Print username and password stored for the item.", ) return parser def _unlock_keychain(self): if self.arguments.no_prompt: self._unlock_keychain_stdin() else: self._unlock_keychain_prompt() def _unlock_keychain_stdin(self): password = self.stdin.read().strip() self.keychain.unlock(password) if self.keychain.locked: self.stderr.write("1pass: Incorrect master password\n") sys.exit(os.EX_DATAERR) def _unlock_keychain_prompt(self): while self.keychain.locked: try: self.keychain.unlock(self.getpass("Master password: "******"\n") sys.exit(0) def _fuzzy_threshold(self): if self.arguments.fuzzy: return 70 else: return 100
def get_data(keychain_file): """Retrieve items from Keychain""" keychain = Keychain(keychain_file) items = keychain.get_all() return items
class CLI(object): """ The 1pass command line interface. """ def __init__(self, stdin=sys.stdin, stdout=sys.stdout, stderr=sys.stderr, getpass=getpass.getpass, arguments=sys.argv[1:]): self.stdin = stdin self.stdout = stdout self.stderr = stderr self.getpass = getpass self.arguments = self.argument_parser().parse_args(arguments) self.keychain = Keychain(self.arguments.path) def run(self): """ The main entry point, performs the appropriate action for the given arguments. """ if not self.arguments.item: for k in self.keychain.get_items(): self.stdout.write("%s\n" % k) return self._unlock_keychain() item = self.keychain.item( self.arguments.item, fuzzy_threshold=self._fuzzy_threshold(), ) if item is not None: if self.arguments.all: for d in item._data: self.stdout.write("%s\n" % d) if d == 'fields': for i in item._data[d]: self.stdout.write("\t%s: %s\n" % (i['name'], i['value'])) elif d == 'URLs': for i in item._data[d]: self.stdout.write("\t%s\n" % (i['url'])) else: self.stdout.write("\t%s\n" % item._data[d]) elif self.arguments.username: self.stdout.write("%s %s\n" % (item.username, item.password)) else: self.stdout.write("%s\n" % item.password) else: self.stderr.write("1pass: Could not find an item named '%s'\n" % (self.arguments.item, )) sys.exit(os.EX_DATAERR) def argument_parser(self): parser = argparse.ArgumentParser() parser.add_argument( "item", help="The name of the key to decrypt," " if ommited prints out the list of all keys in the keychain", nargs="?") parser.add_argument( "-p", "--path", default=os.environ.get('ONEPASSWORD_KEYCHAIN', DEFAULT_KEYCHAIN_PATH), help="Path to your 1Password.agilekeychain file", ) parser.add_argument( "-f", "--fuzzy", action="store_true", help="Perform fuzzy matching on the item", ) parser.add_argument( "-n", "--no-prompt", action="store_true", help="Don't prompt for a password, read from STDIN instead", ) parser.add_argument( "-a", "--all", action="store_true", help="Print all information stored for the item.", ) parser.add_argument( "-u", "--username", action="store_true", help="Print username and password stored for the item.", ) return parser def _unlock_keychain(self): if self.arguments.no_prompt: self._unlock_keychain_stdin() else: self._unlock_keychain_prompt() def _unlock_keychain_stdin(self): password = self.stdin.read().strip() self.keychain.unlock(password) if self.keychain.locked: self.stderr.write("1pass: Incorrect master password\n") sys.exit(os.EX_DATAERR) def _unlock_keychain_prompt(self): while self.keychain.locked: try: self.keychain.unlock(self.getpass("Master password: "******"\n") sys.exit(0) def _fuzzy_threshold(self): if self.arguments.fuzzy: return 70 else: return 100
import itertools import alfred import github_api from argparse import ArgumentParser from util import * from fuzzy_matching import fuzzy_match from keychain import Keychain import gui parser = ArgumentParser() parser.add_argument('-l', '--lazy', help='get repos only from cache', action='store_true') parser.add_argument('--debug', help='show debug messages', action='store_true') parser.add_argument('query', help='get repos only from cache', nargs='?') args = parser.parse_args() keychain = Keychain('Alfred Github') token = keychain.get_password('Alfred Github') if not token: print("Authorizing") github_username = gui.input_box("Github username") github_password = gui.input_box("Github password") token = github_api.authorize(username=github_username, password=github_password, client_id=alfred.preferences['github_api']['client_id'], client_secret=alfred.preferences['github_api']['client_secret'], scopes=['repo'], note='Alfred Github extension') keychain.store_password('Alfred Github', token)