summaryrefslogtreecommitdiff
blob: 04fe3a9c7e5158cde103a51cd0a5fc6012244aa8 (plain)
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
287
288
289
290
291
292
293
294
295
296
297
298
299
300
301
302
303
304
305
306
307
308
309
310
311
312
313
314
315
316
317
318
319
320
321
322
323
324
325
326
327
328
329
330
331
332
333
334
335
336
337
338
339
340
341
342
343
344
345
346
347
348
349
350
351
352
353
354
355
356
357
358
359
360
361
362
363
364
365
366
367
368
369
370
371
372
373
374
375
376
377
378
379
380
381
382
383
384
385
386
387
388
389
390
391
392
393
394
395
396
397
398
399
400
401
402
403
404
405
406
407
408
409
410
411
412
413
414
415
416
417
418
419
420
421
422
423
424
425
426
427
428
429
430
431
432
433
434
435
436
437
438
439
440
441
442
443
444
445
446
447
448
449
450
451
452
453
454
455
456
457
458
459
460
461
462
463
464
465
466
467
468
469
470
471
472
473
474
475
476
477
478
479
480
481
482
483
484
485
#!/usr/bin/env python
# -*- coding: utf-8 -*-

# $Id: pyCrypto.py,v 0.1 2006/05/18 06:15:20 wolfwood Exp $
#
# pyCrypto 0.1 - Object oriented pycrypto class with key serializing.
# http://starwind.homelinux.com/
#
# Copyright (c) 2006 Blackace Enterprises
#
# This program is free software; you can redistribute it and/or
# modify it under the terms of the GNU General Public License
# as published by the Free Software Foundation; either version 2
# of the License, or (at your option) any later version.
#
# This program is distributed in the hope that it will be useful,
# but WITHOUT ANY WARRANTY; without even the implied warranty of
# MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE.  See the
# GNU General Public License for more details.
#
# You should have received a copy of the GNU General Public License
# along with this program; if not, write to the Free Software
# Foundation, Inc., 59 Temple Place - Suite 330, Boston, MA  02111-1307, USA.
#

import sys, os, time, syslog, types, re, struct, binascii
from Crypto.Hash import SHA, MD5
from Crypto.Cipher import DES3
from Crypto.PublicKey import ElGamal, RSA
from Crypto.Util.randpool import RandomPool
from Crypto.Util import number as CryptoNumber

def log(priority, message):
  priorities = {
    'emerg': syslog.LOG_EMERG,
    'alert': syslog.LOG_ALERT,
    'crit': syslog.LOG_CRIT,
    'err': syslog.LOG_ERR,
    'warn': syslog.LOG_WARNING,
    'notice': syslog.LOG_NOTICE,
    'info': syslog.LOG_INFO,
    'debug': syslog.LOG_DEBUG
  }
  name = re.compile('^(?:[^/]*/)?(.*?)(?:\.py)?$').sub('\\1', sys.argv[0])
  syslog.openlog(name, syslog.LOG_PID, syslog.LOG_DAEMON)
  syslog.syslog(priorities[priority], message)
  syslog.closelog()

def die(message):
  log('err', 'died with error: ' + message)
  sys.stderr.write(message + '\n\r')
  sys.exit(1)

class pyCrypto:
  keytypes = {
    'ElGamal': ElGamal,
    'ELGAMAL': ElGamal,
    'scire-elgamal': ElGamal,
    'ssh-elgamal': ElGamal,
    'rsa': RSA,
    'RSA': RSA,
    'scire-rsa': RSA,
    'ssh-rsa': RSA
  }

  def __init__(self, keylength=2048, keytype='ElGamal', hashtype='SHA', keypath='file:///etc/scire/id_elgamal'):
    self.keylength = keylength
    self.keytype = keytype
    self.hashtype = hashtype
    self.keypath = keypath
    self.random = RandomPool(keylength, hash=eval(hashtype))
    self.key = self.getKey()
    if isinstance(self.key, basestring):
      log('warn', 'getting key-pair failed: ' + self.key)
      log('info', 'generating new key-pair')
      self.key = self.genKey()
      if isinstance(self.key, basestring):
        die('generating key-pair failed: ' + self.key)
      log('info', 'putting key-pair')
      self.putKey()

  def getRandom(self, bytes=256):
    start = time.time()
    random = self.random.get_bytes(bytes)
    time.sleep(0.9999)
    stop = str(int(re.sub("^[^.]*\.", "", str(time.time() - start))))
    self.random.stir_n(int(stop[0]))
    self.random.add_event(stop)
    return random

  def encrypt(self, data, key=False):
    retval = ''
    if isinstance(key, bool):
      key = self.key
    while len(data) > 0:
      length = key.size() / 8
      chunk = ''
      if isinstance(key, ElGamal.ElGamalobj):
        pieces = key.encrypt(data[:length], self.getRandom())
      else:
        pieces = key.encrypt(data[:length], '')
      for piece in pieces:
        chunk += binascii.b2a_base64(piece) + '$'
      retval += binascii.b2a_base64(chunk[:-1])
      data = data[length:]
    return retval[:-1]

  def decrypt(self, data, key=False):
    retval = ''
    if isinstance(key, bool):
      key = self.key
    chunks = data.split('\n')
    for chunk in chunks:
      base64pieces = binascii.a2b_base64(chunk).split('$')
      pieces = []
      for piece in base64pieces:
        pieces.append(binascii.a2b_base64(piece))
      retval += key.decrypt(tuple(pieces))
    return retval

  def genKey(self):
    keyobj = self.keytypes[self.keytype]
    try:
      key = keyobj.generate(self.keylength, self.getRandom)
    except:
      return '"' + self.keytype + '" is not a supported key type'
    return key

  def getKey(self, keypath=''):
    if len(keypath) == 0:
      keypath = self.keypath
    if len(keypath) == 0:
      return 'no keypath specified'
    passphrase = ''
    mech, path = keypath.split(':', 1)
    if path[:2] == '//':
      path = path[2:]
    pos = path.rfind('*')
    if pos >= 0:
      passphrase = path[pos+1:]
      path = path[:pos]
    del(pos)
    data = ''
    if mech == 'file':
      if path[0] == '~':
        path = os.path.expanduser(path)
      else:
        path = os.path.abspath(path)
      if not os.path.isfile(path):
        return '"' + path + '" does not exist'
      if not os.access(path, os.R_OK):
        return 'read permission denied to "' + path + '"'
      kf = open(path, 'r')
      data = kf.read()
      kf.close()
      del(kf)
    elif mech == 'string':
      data = path
    elif mech == 'mysql':
      print '',
      # parse path as user:pass*passphrase@host/db/table/col/wherecol/whereval
      # and retrieve data
    else:
      return '"' + mech + '" is not a supported key storage mechanism'
    key = self.unpackKey(data, passphrase)
    if isinstance(key, basestring):
      return 'unpacking key-pair failed: ' + key
    else:
      return key

  def putKey(self, keypath=''):
    if len(keypath) == 0:
      keypath = self.keypath
    if len(keypath) == 0:
      return False
    mech, path = keypath.split(':', 1)
    passphrase = ''
    pos = path.rfind('*')
    if pos >= 0:
      passphrase = path[pos+1:]
      path = path[:pos]
    del(pos)
    data = self.packKey(self.key, passphrase)
    if len(data) <= 0:
      log('err', 'packing key-pair failed')
      return False
    if mech == 'file':
      if path[:2] == '//':
        path = path[2:]
      if path[0] == '~':
        path = os.path.expanduser(path)
      else:
        path = os.path.abspath(path)
      if not os.path.isdir(os.path.dirname(path)):
        log('err', '"' + os.path.dirname(path) + '" does not exist')
        return False
      if os.path.isfile(path) and not os.access(path, os.W_OK):
        log('err', 'write permission denied to "' + path + '"')
        return False
      if not os.path.isfile(path):
        if os.access(os.path.dirname(path), os.W_OK):
          kf = open(path, 'w')
          kf.write('')
          kf.close()
          del(kf)
          os.chmod(path, 0600)
        else:
          log('err', 'write permission denied to "' + os.path.dirname(path) + '"')
          return False
      kf = open(path, 'w')
      kf.write(data)
      kf.close()
      del(kf)
      return True
    elif mech == 'mysql':
      print '',
      # parse path as user:pass*passphrase@host/db/table/col/wherecol/whereval
      # and store data
    else:
      log('err', '"' + mech + '" is not a supported key storage mechanism')
      return False

  def unpackKeyBlob(self, blob):
    fields = []
    while blob:
      type = ord(blob[0])
      if (type & 0xc0) != 0:
        return False
      length = ord(blob[1])
      if blob == 0x80:
        return False
      if length & 0x80:
        longlength = length & 0x7f
        length = CryptoNumber.bytes_to_long(blob[2:2+longlength])
        size = 2 + longlength
      else:
        size = 2
      body, blob = blob[size:size+length], blob[size+length:]
      type = type & (~0x20)
      if type == 0x10:
        result = self.unpackKeyBlob(body)
        if not isinstance(result, bool):
          fields.append(result)
      elif type == 0x02:
        fields.append(CryptoNumber.bytes_to_long(body))
    if len(fields) == 1:
      return fields[0]
    return fields

  def packKeyBlob(self, fields):
    blob = ''
    for field in fields:
      if isinstance(field, tuple) or isinstance(field, types.ListType):
        data = self.packKeyBlob(field)
        type = 0x10|0x20
      elif isinstance(field, int) or isinstance(field, long):
        data = CryptoNumber.long_to_bytes(field)
        if ord(data[0])&(0x80):
          data = '\x00' + data
        type = 0x02
      blob += chr(type)
      if len(data) > 127:
        length = CryptoNumber.long_to_bytes(len(data))
        blob += chr(len(length)|0x80) + length
      else:
        blob += chr(len(data))
      blob += data
    return blob

  def unpackKey(self, data, passphrase=''):
    parsing = False
    keyobj = None
    key = {'type': '', 'encrypted': False, 'cipher': '', 'iv': '', 'headers': [], 'blob': '', 'comment': ''}
    for line in data.split('\n'):
      if line[:8] == '-----END' and line[-16:] == 'PRIVATE KEY-----':
        break
      if len(line.split(':', 1)) == 2:
        if parsing:
          parsing = False
        header, value = line.split(':', 1)
        header = header.strip()
        value = value.strip()
        key['headers'].append({'header': header, 'value': value})
        if header.lower() == 'proc-type' and value.lower() == '4,encrypted':
          key['encrypted'] = True
        if header.lower() == 'dek-info':
          key['cipher'], key['iv'] = value.split(',', 1)
          key['iv'] = binascii.a2b_hex(key['iv'])
        continue
      if parsing:
        key['blob'] = key['blob'] + line
      if line[:10] == '-----BEGIN' and line[-16:] == 'PRIVATE KEY-----':
        key['type'] = line[11:-17]
        parsing = True
      if len(key['headers']) > 0 and line == '':
        parsing = True
    del(parsing)
    if len(key['blob']) > 0:
      # Private key
      if not self.keytypes.has_key(key['type']):
        return '"' + key['type'] + '" is not a supported key type'
      blob = binascii.a2b_base64(key['blob'])
      if key['encrypted']:
        if len(blob) % 8 != 0:
          return 'invalid encrypted key blob size'
        blocka = MD5.new(passphrase + key['iv']).digest()
        blockb = MD5.new(blocka + passphrase + key['iv']).digest()
        cipher = DES3.new(blocka + blockb[:8], DES3.MODE_CBC, key['iv'])
        del(blocka)
        del(blockb)
        blob = cipher.decrypt(blob)
        del(cipher)
      fields = self.unpackKeyBlob(blob)
      if isinstance(fields, bool):
        return 'invalid passphrase'
      if self.keytypes[key['type']] == RSA:
        n, e, d, p, q = fields[1:6]
        keyobj = RSA.construct((n, e, d, p, q))
      elif self.keytypes[key['type']] == ElGamal:
        p, g, y, x = fields[1:5]
        keyobj = ElGamal.construct((p, g, y, x))
    else:
      # Public key
      for line in data.split('\n'):
        fields = line.split(' ')
        if len(fields) == 3:
          key['type'], key['blob'], key['comment'] = fields[:3]
          break
        if len(fields) == 2:
          key['type'], key['blob'] = fields[:2]
          break
      if not self.keytypes.has_key(key['type']):
        return '"' + key['type'] + '" is not a supported key type'
      blob = binascii.a2b_base64(key['blob'])
      (length,) = struct.unpack('>I', blob[:4])
      type = blob[4:4+length]
      blob = blob[4+length:]
      if not self.keytypes.has_key(type):
        return '"' + key['type'] + '" is not a supported key type'
      (length,) = struct.unpack('>I', blob[:4])
      bytes = blob[4:4+length]
      e = 0L
      for byte in bytes:
        e = e * 256 + ord(byte)
      blob = blob[4+length:]
      (length,) = struct.unpack('>I', blob[:4])
      bytes = blob[4:4+length]
      n = 0L
      for byte in bytes:
        n = n * 256 + ord(byte)
      blob = blob[4+length:]
      if self.keytypes[type] == ElGamal:
        (length,) = struct.unpack('>I', blob[:4])
        bytes = blob[4:4+length]
        y = 0L
        for byte in bytes:
          y = y * 256 + ord(byte)
        blob = blob[4+length:]
        keyobj = ElGamal.construct((e, n, y))
      elif self.keytypes[type] == RSA:
        keyobj = RSA.construct((n, e))
    keyobj.metadata = key
    return keyobj

  def packKey(self, key, passphrase=''):
    data = ''
    keytype = ''
    blob = ''
    if key.has_private():
      # Private key
      if isinstance(key, RSA.RSAobj):
        keytype = 'RSA'
        dmq1 = key.d % (key.q-1)
        dmp1 = key.d % (key.p-1)
        impq = CryptoNumber.inverse(key.p, key.q)
        blob = self.packKeyBlob([0, key.n, key.e, key.d, key.q, key.p, dmq1, dmp1, impq])
        del(dmq1)
        del(dmp1)
        del(impq)
      elif isinstance(key, ElGamal.ElGamalobj):
        keytype = 'ELGAMAL'
        blob = self.packKeyBlob((0, key.p, key.g, key.y, key.x))
      else:
        log('err', 'packing key-pair: no key type matched')
      if len(blob) <= 0:
        return ''
      data += '-----BEGIN ' + keytype + ' PRIVATE KEY-----\n'
      if len(passphrase) > 0:
        iv = self.getRandom(8)
        blocka = MD5.new(passphrase + iv).digest()
        blockb = MD5.new(blocka + passphrase + iv).digest()
        cipher = DES3.new(blocka + blockb[:8], DES3.MODE_CBC, iv)
        del(blocka)
        del(blockb)
        while len(blob) % 8:
          blob += '='
        blob = cipher.encrypt(blob)
        del(cipher)
        data += 'Proc-Type: 4,ENCRYPTED\n'
        data += 'DEK-Info: DES-EDE3-CBC,' + binascii.b2a_hex(iv).upper() + '\n\n'
        del(iv)
      blob = binascii.b2a_base64(blob)
      if len(blob) <= 0:
        return ''
      while blob:
        data += blob[:64] + '\n'
        blob = blob[64:]
      data = data.rstrip('\n') + '\n-----END ' + keytype + ' PRIVATE KEY-----\n'
    else:
      # Public key
      e = 0
      n = 0
      y = 0
      if isinstance(key, ElGamal.ElGamalobj):
        try:
          keytype = key.metadata['type']
        except:
          keytype = 'ssh-elgamal'
        e = key.p
        n = key.g
        y = key.y
      elif isinstance(key, RSA.RSAobj):
        try:
          keytype = key.metadata['type']
        except:
          keytype = 'ssh-rsa'
        e = key.e
        n = key.n
      blob += struct.pack('>I', len(keytype))
      blob += struct.pack('>' + str(len(keytype)) + 's', keytype)
      val = ''
      while 1:
        r = e % 256
        d = (e - r) / 256
        val = chr(r) + val
        if d >= 256:
          e = d
          continue
        elif d != 0:
          val = chr(d) + val
        break
      del(e)
      if ord(val[0]) & 0x80:
        val = '\0' + val
      blob += struct.pack('>I', len(val))
      blob += struct.pack('>' + str(len(val)) + 's', val)
      val = ''
      while 1:
        r = n % 256
        d = (n - r) / 256
        val = chr(r) + val
        if d >= 256:
          n = d
          continue
        elif d != 0:
          val = chr(d) + val
        break
      del(n)
      if ord(val[0]) & 0x80:
        val = '\0' + val
      blob += struct.pack('>I', len(val))
      blob += struct.pack('>' + str(len(val)) + 's', val)
      if y != 0:
        val = ''
        while 1:
          r = y % 256
          d = (y - r) / 256
          val = chr(r) + val
          if d >= 256:
            y = d
            continue
          elif d != 0:
            val = chr(d) + val
          break
        del(y)
        if ord(val[0]) & 0x80:
          val = '\0' + val
        blob += struct.pack('>I', len(val))
        blob += struct.pack('>' + str(len(val)) + 's', val)
      blob = binascii.b2a_base64(blob)
      try:
        data = keytype + ' ' + blob.rstrip('\n') + ' ' + key.metadata['comment'] + '\n'
      except:
        data = keytype + ' ' + blob.rstrip('\n') + '\n'
    return data