コード例 #1
0
ファイル: api_lib.py プロジェクト: evido3s/f5configbackup
def encrypt():
   '''
Encryption function - encrypt string using key from file
   '''
   try:
      # Check for element string and that it is not blank
      if 'string' not in request.json.keys():
         abort(400)
      elif not request.json or len(request.json['string']) == 0:
         abort(400)
   except:
      abort(400)
   
   # Get encryption password or give 500 error
   try:
      with open('%s/.keystore/backup.key' % sys.path[0],'r') as psfile:
         cryptokey = psfile.readline().rstrip()
   except:
      abort(500)
   
   # Encrypt string and return response, m2secret does not like unicode
   secret = m2secret.Secret()
   secret.encrypt(str(request.json['string']), cryptokey)
   serialized = secret.serialize()
   
   return jsonify( {'result' : serialized } )
コード例 #2
0
   def getcreds(self,key,id=0):
      '''
getcreds(key, id=0) - Gets user credentials from DB 
args - key: encryption key used by m2secret 
id - device id of creds to fetch, default is for default creds
Return - dict of creds
      '''
      # Get user and encypted pass from DB, convert to dict of str types
      self.dbc.execute("SELECT NAME,PASS FROM BACKUP_USER WHERE ID = %d" % id)
      raw_creds = dict(zip( ['name','passwd'], [str(i) for i in self.dbc.fetchone()] ))
      
      # Decrypt pass and return dict of creds
      secret = m2secret.Secret()
      secret.deserialize(raw_creds['passwd'])
      return { 'name' : raw_creds['name'], 'passwd' : secret.decrypt(key) }
コード例 #3
0
 def formatter(self, value):
     secret = m2secret.Secret()
     secret.deserialize(value)
     return (secret.decrypt(self.key), None)
コード例 #4
0
 def __call__(self, value):
     secret = m2secret.Secret()
     secret.encrypt(value, self.key)
     return secret.serialize()
コード例 #5
0
    def prepare(self):
        '''
   Prepares a the message for sending. Gets setting from DB. Also
   pulls certs from DB and creates email message and headers sending.
      '''
        try:
            # Connect to DB
            self.log.debug('Email prepare, connecting to DB.')
            db = sq.connect(sys.path[0] + '/db/main.db')
            dbc = db.cursor()

            # Get email settings from DB
            self.log.debug('Email prepare, getting email settings from DB.')
            dbc.execute('''SELECT SENDER,SENDER_TITLE,TO_MAIL,SUBJECT,HIDE_ACK,
         TLS,SERVER,PORT,LOGIN,LOGIN_USER,LOGIN_PASS FROM EMAIL WHERE ID =0''')
            db_values_temp = dbc.fetchone()
        except:
            e = sys.exc_info()[1]
            self.log.critical('Email prepare - %s' % e)
            raise

        # Convert unicode into str
        self.log.debug('Email prepare, convert unicode.')
        db_values = []
        for i in db_values_temp:
            if type(i).__name__ == 'unicode':
                i = str(i)
            # Add new string to new list
            db_values.append(i)

        # Create email settings dict
        self.log.debug('Email prepare, creating email dict.')
        db_keys = [
            'sender', 'sender_title', 'to_mail', 'subject', 'hide_ack', 'tls',
            'server', 'port', 'login', 'login_user', 'login_crypt'
        ]
        self.email_set = dict(zip(db_keys, db_values))

        # Get user password
        try:
            # Get crypto key
            self.log.debug('Email prepare, getting key from keystore.')
            with open(sys.path[0] + '/.keystore/backup.key', 'r') as psfile:
                key = psfile.readline().rstrip()
        except:
            e = sys.exc_info()[1]
            self.log.critical('Can\'t get key from keystore - %s' % e)
            raise

        # Decrypting user password
        if self.email_set['login']:
            self.log.debug('Email prepare, decrypting email password.')
            try:
                secret = m2secret.Secret()
                secret.deserialize(self.email_set['login_crypt'])
                self.email_set['login_pass'] = secret.decrypt(key)
            except:
                e = sys.exc_info()[1]
                self.log.critical('Can\'t decrypt email login password - %e' %
                                  e)
                raise

        # build device dict
        self.log.debug('Email prepare, building device list.')
        dbc.execute('SELECT ID,NAME FROM DEVICES')
        self.dev_dict = {}
        for idn, name in dbc.fetchall():
            self.dev_dict[idn] = str(name)

        # Get certs expiring between 30 and 7 days
        self.log.debug('Email prepare, getting 30 to 7 certs.')
        dbc.execute(
            '''SELECT ID,NAME,DEVICE,SUB_CN,EXPIRE FROM CERTS WHERE 
                     EXPIRE < ? AND EXPIRE > ? AND ACK = 0 ORDER BY EXPIRE''',
            (self.thirty_days, self.seven_days))
        thirty_to_seven = self._get_certs(dbc.fetchall())

        # Get certs expiring between 7 days and now
        self.log.debug('Email prepare, getting 7 to now certs.')
        dbc.execute(
            '''SELECT ID,NAME,DEVICE,SUB_CN,EXPIRE FROM CERTS WHERE 
                     EXPIRE < ? AND EXPIRE > ? AND ACK = 0 ORDER BY EXPIRE''',
            (self.seven_days, self.now))

        seven_to_now = self._get_certs(dbc.fetchall())

        # Get expired certs
        self.log.debug('Email prepare, getting expireed certs.')
        dbc.execute(
            '''SELECT ID,NAME,DEVICE,SUB_CN,EXPIRE FROM CERTS WHERE 
                     EXPIRE < ?  AND ACK = 0 ORDER BY EXPIRE''', (self.now, ))
        expired = self._get_certs(dbc.fetchall())

        # Get expired and expiring with in 30 days that have been acked
        self.log.debug('Email prepare, getting acked certs.')
        dbc.execute(
            '''SELECT ID,NAME,DEVICE,SUB_CN,EXPIRE FROM CERTS WHERE 
                     EXPIRE < ? AND ACK = 1 ORDER BY EXPIRE''',
            (self.thirty_days, ))
        acked = self._get_certs(dbc.fetchall())

        # build table of acked certs
        acked_certs = ''
        if not self.email_set['hide_ack']:
            acked_certs = '''
   <div align="center"><strong>Certs Expired or Expiring Within 30 Days (Acknowledged)</strong></div>
   %s
   <br>''' % self._cert_table(acked)

        # Build email header
        self.log.debug('Email prepare, building header.')
        self.header = '''From: %s <%s>
To: %s
MIME-Version: 1.0
Content-type: text/html
Subject: %s 
''' % (self.email_set['sender_title'], self.email_set['sender'],
        self.email_set['to_mail'], self.email_set['subject'])

        # Build Email body
        self.log.debug('Email prepare, building message body.')
        self.msg_body = '''
<html>
<body>
<style>
body {
   text-align:center;
}
table.cert {
   border: 1px solid #999999;
   border-collapse:collapse;
   text-align:center;
}
table.cert th {
   border: 1px solid #999999;
   border-collapse:collapse;
   padding:2px 12px 2px 12px;
   height: 25px;
  /* background-image:url('/images/banner.png');
   background-repeat:repeat-x; */
}
table.cert td {
   border: 1px solid #999999;
   border-collapse:collapse;
   padding:2px 12px 2px 12px;
}
table.title {
   text-align: center;
}
table.title th {
   font-size:30px;
   font-weight:bold;
}
</style>

   <table class="title" align="center">
      <th>Certificate Report</th>
      <tr><td>Config Backup for F5</td></tr>
   </table>
   <br />
   
   <div align="center"><strong>Certs Expiring in 30 to 7 Days (Not Acknowledged)</strong></div>
   %s
   <br>

   <div align="center"><strong>Certs Expiring Within 7 Days (Not Acknowledged)</strong></div>
   %s
   <br>
   
   <div align="center"><strong>Expired Certs (Not Acknowledged)</strong></div>
   %s
   <br>
   %s
</body>
</html>''' % (self._cert_table(thirty_to_seven),
              self._cert_table(seven_to_now), self._cert_table(expired),
              acked_certs)
        #Close DB connection
        self.log.debug('Email prepare, closing DB.')
        db.close
コード例 #6
0
def adauthenicate(user, passwd):
    '''
   Config backup function for authenticating user in active directory
   
   @param user:   Username you wish to authenicate
   @param passwd: Password of user
   @param log:    Log object
   
   This function gets the AD info from the DB and tracks which servers 
   in and up/down state. If AD server is down it is not attempted again 
   for another 10 minutes. 
   '''
    # Create logging for authentication
    logfile = '%s/log/auth.log' % sys.path[0]
    authlog = logsimple.LogSimple(logfile, max_files=5)
    authlog.setlevel('INFO')

    # Connect to DB
    try:
        db = sq.connect(sys.path[0] + '/db/main.db')
        dbc = db.cursor()
        authlog.debug('Connected to DB.')

        # Retrieve bind user, password, domain from DB
        authlog.debug('Getting bind username and password.')
        dbc.execute("SELECT AUTHACCT,AUTHHASH,DOMAIN FROM AUTH WHERE ID = 0")
        bind = dbc.fetchone()
    except:
        e = sys.exc_info()[1]
        authlog.critical('DB connect failed - %s' % e)
        authlog.close()
        raise StandardError(e)

    # Get log level from DB and reset in logging object
    dbc.execute("SELECT LEVEL FROM LOGGING WHERE NAME = 'AUTH'")
    authlog.setlevel(str(dbc.fetchone()[0]))

    # Check for value in list bind
    if type(bind) is tuple:
        #Convert result into dict
        bind = {'acct': bind[0], 'passwd': bind[1], 'domain': bind[2]}
    else:
        authlog.error('No credentials avilable in DB.')
        authlog.close()
        return [False, 'No credentials avilable in DB.']

    #Decrypt password
    try:
        authlog.debug('Getting crypto key from key store.')
        with open(sys.path[0] + '/.keystore/backup.key', 'r') as psfile:
            cryptokey = psfile.readline().rstrip()
        authlog.debug('Decrypting bind password.')
        secret = m2secret.Secret()
        secret.deserialize(bind['passwd'])
        bind['passwd'] = secret.decrypt(cryptokey)
    except:
        e = sys.exc_info()[1]
        authlog.critical('Can\'t get credentials from DB - %s' % e)
        authlog.close()
        raise StandardError(e)

    # Retrieve list of servers from DB
    authlog.debug('Getting list of servers from DB.')
    dbc.execute("SELECT ID,SERVER,TLS,TIMEDOWN FROM AUTHSERVERS")
    servers = [{
        'id': id,
        'server': server,
        'tls': tls,
        'timedown': timedown
    } for id, server, tls, timedown in dbc.fetchall()]

    # loop through list of servers
    for server in servers:
        try:
            # Has server been declared down within the last 10 min ?
            if (server['timedown'] + 600) > int(time.time()):
                # If yes skip to next server
                next_try = (server['timedown'] + 600) - int(time.time())
                authlog.debug(
                    'Server %s was down within 10 minutes. %d seconds until next retry.'
                    % (server['server'], next_try))
                continue

            # If this server works do auth and return result
            authlog.debug('Authenicating to server %s.' % server['server'])
            authlog.info('Authenicating user %s.' % user)
            auth = adauth.ADAuth(server['server'], bind['acct'],
                                 bind['passwd'], bind['domain'], server['tls'])
            result = auth.Authenticate(user, passwd)
            if result[0] == True:
                authlog.info('User successfully authenticated. User:%s.' %
                             user)
                authlog.debug('User %s attr - %s' % (user, str(result[1])))
            elif result[0] == False:
                authlog.info('User auth failed - User:%s, Reason:%s.' %
                             (user, result[1]))
            authlog.close()
            return result
        except ldap.SERVER_DOWN as e:
            # If server down mark in DB and go to next
            authlog.error('Server %s is not up. Marking server down.' %
                          server['server'])
            try:
                dbc.execute('UPDATE AUTHSERVERS SET TIMEDOWN = ? WHERE ID = ?',
                            (int(time.time()), server['id']))
                db.commit()
            except:
                e = sys.exc_info()[1]
                authlog.error('Server down DB update - %s' % e)
            #Skip to next device
            continue
    else:
        authlog.error('No AD servers avilable.')
        authlog.close()
        return [False, 'No auth servers avilable.']