5 Gentoo-keys - gkeyldap/actions.py
7 Primary api interface module
9 @copyright: 2012 by Brian Dolbec <dol-sen@gentoo.org>
10 @license: GNU GPL2, see COPYING for details.
16 from gkeys.config import GKEY, KEYID, LONGKEYID, FINGERPRINT
17 from gkeys.seed import Seeds
18 from gkeyldap.search import (LdapSearch, UID, gkey2ldap_map, gkey2SEARCH)
28 Avialable_Actions = ['ldapsearch', 'updateseeds']
31 def get_key_ids(key, info):
32 '''Small utility function to return only keyid (short)
35 @param key: string, the key length desired
36 @param info: list of keysid's to process
37 @return list of the desired key length id's
41 if x.startswith('0x'):
42 mylen = KEY_LEN[key] + 2
50 class Actions(object):
53 def __init__(self, config, output=None, logger=None):
58 self.fingerprint_re = re.compile('[0-9A-Fa-f]{40}')
61 def ldapsearch(self, args):
63 self.logger.info("Search...establishing connection")
64 self.output("Search...establishing connection")
66 self.logger.info("Aborting Search...Connection failed")
67 self.output("Aborting Search...Connection failed")
69 self.logger.debug("MAIN: _action_ldapsearch; args = %s" % str(args))
70 x, target, search_field = self.get_args(args)
71 results = l.search(target, search_field)
72 devs = l.result2dict(results, gkey2ldap_map[x])
73 for dev in sorted(devs):
74 self.output(dev, devs[dev])
75 self.output("============================================")
76 self.output("Total number of devs in results:", len(devs))
77 self.logger.info("============================================")
78 self.logger.info("Total number of devs in results: %d" % len(devs))
82 def updateseeds(self, args):
83 self.logger.info("Beginning ldap search...")
84 self.output("Beginning ldap search...")
87 self.output("Aborting Update...Connection failed")
88 self.logger.info("Aborting Update...Connection failed")
90 results = l.search('*', UID)
91 info = l.result2dict(results, 'uid')
93 "MAIN: _action_updateseeds; got results :) converted to info")
94 if not self.create_seedfile(info):
95 self.logger.error("Dev seed file update failure: "
96 "Original seed file is intact & untouched.")
97 filename = self.config['dev-seedfile']
98 old = filename + '.old'
100 self.output("Backing up existing file...")
101 self.logger.info("Backing up existing file...")
102 if os.path.exists(old):
104 "MAIN: _action_updateseeds; Removing 'old' seed file: %s"
107 if os.path.exists(filename):
109 "MAIN: _action_updateseeds; Renaming current seed file to: "
111 os.rename(filename, old)
113 "MAIN: _action_updateseeds; Renaming '.new' seed file to: %s"
115 os.rename(filename + '.new', filename)
118 self.output("Developer Seed file updated")
122 def create_seedfile(self, devs):
123 self.output("Creating seeds from ldap data...")
124 filename = self.config['dev-seedfile'] + '.new'
125 self.seeds = Seeds(filename)
128 for dev in sorted(devs):
129 if devs[dev]['gentooStatus'][0] not in ['active']:
131 #self.logger.debug("create_seedfile, dev = "
132 # "%s, %s" % (str(dev), str(devs[dev])))
133 keyinfo = self.build_gkeylist(devs[dev])
135 new_gkey = GKEY._make(keyinfo)
136 self.seeds.add(new_gkey)
140 self.output("Total number of seeds created:", count)
141 self.output("Seeds created...saving file: %s" % filename)
142 self.output("Total number of Dev's with gpg errors:", error_count)
143 self.logger.info("Total number of seeds created: %d" % count)
144 self.logger.info("Seeds created...saving file: %s" % filename)
145 self.logger.info("Total number of Dev's with gpg errors: %d" % error_count)
146 return self.seeds.save()
151 for x in ['nick', 'name', 'gpgkey', 'fingerprint', 'status']:
153 target = getattr(args, x)
154 search_field = gkey2SEARCH[x]
156 return (x, target, search_field)
160 def build_gkeydict(self, info):
162 for x in GKEY._fields:
163 field = gkey2ldap_map[x]
167 # strip errant line feeds
168 values = [y.strip('\n') for y in info[field]]
169 if values and values in ['uid', 'cn' ]:
171 # separate out short/long key id's
172 elif values and x in ['keyid', 'longkeyid']:
173 value = get_key_ids(x, values)
176 if 'undefined' in values:
177 self.logger.error('%s = "undefined" for %s, %s'
178 %(field, info['uid'][0], info['cn'][0]))
186 def build_gkeylist(self, info):
189 keyid_missing = False
190 # assume it's good until found an error is found
192 #self.logger.debug("MAIN: build_gkeylist; info = %s" % str(info))
193 for x in GKEY._fields:
194 field = gkey2ldap_map[x]
199 # strip errant line feeds
200 values = [y.strip('\n') for y in info[field]]
201 if values and field in ['uid', 'cn' ]:
203 # separate out short/long key id's
204 elif values and x in ['keyid', 'longkeyid']:
205 value = get_key_ids(x, values)
208 elif values and x in ['fingerprint']:
209 value = [v.replace(' ', '') for v in values]
212 if 'undefined' in values:
213 self.logger.error('ERROR in ldap info for: %s, %s'
214 %(info['uid'][0],info['cn'][0]))
215 self.logger.error(' %s = "undefined"' %(field))
217 keyinfo.append(value)
219 self.logger.debug('Ldap info for: %s, %s'
220 %(info['uid'][0],info['cn'][0]))
221 self.logger.debug(' MISSING or EMPTY ldap field ' +
222 '[%s] GPGKey field [%s]' %(field, x))
223 if x in ['keyid', 'longkeyid']:
228 if not keyid_found and keyid_missing:
231 fingerprint = info[gkey2ldap_map['fingerprint']]
232 self.logger.debug(' Generate gpgkey, Found ldap fingerprint field')
234 gpgkey = 'Missing fingerprint from ldap info'
235 self.logger.debug(' Generate gpgkey, ldap fingerprint KeyError')
237 values = [y.strip('\n') for y in fingerprint]
238 value = [v.replace(' ', '') for v in values]
239 # assign it to gpgkey to prevent a possible
240 # "gpgkey" undefined error
241 gpgkey = ['0x' + x[-KEY_LEN['longkeyid']:] for x in value]
242 keyinfo[LONGKEYID] = gpgkey
243 self.logger.debug(' Generate gpgkey, NEW keyinfo[LONGKEYID] = %s'
244 % str(keyinfo[LONGKEYID]))
246 gpgkey = 'Missing or Bad fingerprint from ldap info'
248 if not keyinfo[LONGKEYID]:
249 self.logger.error('ERROR in ldap info for: %s, %s'
250 %(info['uid'][0],info['cn'][0]))
251 self.logger.error(' A valid keyid, longkeyid or fingerprint '
252 'was not found for %s : gpgkey = %s' %(info['cn'][0], gpgkey))
255 if keyinfo[FINGERPRINT]: # fingerprints exist check
256 is_ok = self._check_fingerprint_integrity(info, keyinfo)
257 is_match = self._check_id_fingerprint_match(info, keyinfo)
258 if not is_ok or not is_match:
265 def _check_id_fingerprint_match(self, info, keyinfo):
266 # assume it's good until found an error is found
268 for x in [KEYID, LONGKEYID]:
269 # skip blank id field
273 index = len(y.lstrip('0x'))
274 if y.lstrip('0x').upper() not in \
275 [x[-index:].upper() for x in keyinfo[FINGERPRINT]]:
276 self.logger.error('ERROR in ldap info for: %s, %s'
277 %(info['uid'][0],info['cn'][0]))
278 self.logger.error(' ' + str(keyinfo))
279 self.logger.error(' GPGKey id %s not found in the '
280 % y.lstrip('0x') + 'listed fingerprint(s)')
285 def _check_fingerprint_integrity(self, info, keyinfo):
286 # assume it's good until found an error is found
288 for x in keyinfo[FINGERPRINT]:
289 # check fingerprint integrity
291 self.logger.error('ERROR in ldap info for: %s, %s'
292 %(info['uid'][0],info['cn'][0]))
293 self.logger.error(' GPGKey incorrect fingerprint ' +
294 'length (%s) for fingerprint: %s' %(len(x), x))
297 if not self.fingerprint_re.match(x):
298 self.logger.error('ERROR in ldap info for: %s, %s'
299 %(info['uid'][0],info['cn'][0]))
300 self.logger.error(' GPGKey: Non hexadecimal digits in ' +
301 'fingerprint for fingerprint: ' + x)