/mandos/trunk

To get this branch, use:
bzr branch http://bzr.recompile.se/loggerhead/mandos/trunk

« back to all changes in this revision

Viewing changes to mandos

  • Committer: Teddy Hogeborn
  • Date: 2011-10-11 20:04:57 UTC
  • mfrom: (505.1.14 teddy)
  • Revision ID: teddy@recompile.se-20111011200457-gscdhu4raq6tgn4x
* Makefile (DOCBOOKTOMAN): Also check manual pages for warnings.
* debian/control (Build-Depends): Added "man".

Show diffs side-by-side

added added

removed removed

Lines of Context:
63
63
import cPickle as pickle
64
64
import multiprocessing
65
65
import types
66
 
import binascii
67
 
import tempfile
68
66
 
69
67
import dbus
70
68
import dbus.service
75
73
import ctypes.util
76
74
import xml.dom.minidom
77
75
import inspect
78
 
import GnuPGInterface
79
76
 
80
77
try:
81
78
    SO_BINDTODEVICE = socket.SO_BINDTODEVICE
86
83
        SO_BINDTODEVICE = None
87
84
 
88
85
 
89
 
version = "1.4.1"
90
 
stored_state_file = "clients.pickle"
 
86
version = "1.4.0"
91
87
 
92
 
logger = logging.getLogger()
 
88
#logger = logging.getLogger('mandos')
 
89
logger = logging.Logger('mandos')
93
90
syslogger = (logging.handlers.SysLogHandler
94
91
             (facility = logging.handlers.SysLogHandler.LOG_DAEMON,
95
92
              address = str("/dev/log")))
96
 
 
97
 
try:
98
 
    if_nametoindex = (ctypes.cdll.LoadLibrary
99
 
                      (ctypes.util.find_library("c"))
100
 
                      .if_nametoindex)
101
 
except (OSError, AttributeError):
102
 
    def if_nametoindex(interface):
103
 
        "Get an interface index the hard way, i.e. using fcntl()"
104
 
        SIOCGIFINDEX = 0x8933  # From /usr/include/linux/sockios.h
105
 
        with contextlib.closing(socket.socket()) as s:
106
 
            ifreq = fcntl.ioctl(s, SIOCGIFINDEX,
107
 
                                struct.pack(str("16s16x"),
108
 
                                            interface))
109
 
        interface_index = struct.unpack(str("I"),
110
 
                                        ifreq[16:20])[0]
111
 
        return interface_index
112
 
 
113
 
 
114
 
def initlogger(level=logging.WARNING):
115
 
    """init logger and add loglevel"""
116
 
    
117
 
    syslogger.setFormatter(logging.Formatter
118
 
                           ('Mandos [%(process)d]: %(levelname)s:'
119
 
                            ' %(message)s'))
120
 
    logger.addHandler(syslogger)
121
 
    
122
 
    console = logging.StreamHandler()
123
 
    console.setFormatter(logging.Formatter('%(asctime)s %(name)s'
124
 
                                           ' [%(process)d]:'
125
 
                                           ' %(levelname)s:'
126
 
                                           ' %(message)s'))
127
 
    logger.addHandler(console)
128
 
    logger.setLevel(level)
129
 
 
130
 
 
131
 
class CryptoError(Exception):
132
 
    pass
133
 
 
134
 
 
135
 
class Crypto(object):
136
 
    """A simple class for OpenPGP symmetric encryption & decryption"""
137
 
    def __init__(self):
138
 
        self.gnupg = GnuPGInterface.GnuPG()
139
 
        self.tempdir = tempfile.mkdtemp(prefix="mandos-")
140
 
        self.gnupg = GnuPGInterface.GnuPG()
141
 
        self.gnupg.options.meta_interactive = False
142
 
        self.gnupg.options.homedir = self.tempdir
143
 
        self.gnupg.options.extra_args.extend(['--force-mdc',
144
 
                                              '--quiet'])
145
 
    
146
 
    def __enter__(self):
147
 
        return self
148
 
    
149
 
    def __exit__ (self, exc_type, exc_value, traceback):
150
 
        self._cleanup()
151
 
        return False
152
 
    
153
 
    def __del__(self):
154
 
        self._cleanup()
155
 
    
156
 
    def _cleanup(self):
157
 
        if self.tempdir is not None:
158
 
            # Delete contents of tempdir
159
 
            for root, dirs, files in os.walk(self.tempdir,
160
 
                                             topdown = False):
161
 
                for filename in files:
162
 
                    os.remove(os.path.join(root, filename))
163
 
                for dirname in dirs:
164
 
                    os.rmdir(os.path.join(root, dirname))
165
 
            # Remove tempdir
166
 
            os.rmdir(self.tempdir)
167
 
            self.tempdir = None
168
 
    
169
 
    def password_encode(self, password):
170
 
        # Passphrase can not be empty and can not contain newlines or
171
 
        # NUL bytes.  So we prefix it and hex encode it.
172
 
        return b"mandos" + binascii.hexlify(password)
173
 
    
174
 
    def encrypt(self, data, password):
175
 
        self.gnupg.passphrase = self.password_encode(password)
176
 
        with open(os.devnull) as devnull:
177
 
            try:
178
 
                proc = self.gnupg.run(['--symmetric'],
179
 
                                      create_fhs=['stdin', 'stdout'],
180
 
                                      attach_fhs={'stderr': devnull})
181
 
                with contextlib.closing(proc.handles['stdin']) as f:
182
 
                    f.write(data)
183
 
                with contextlib.closing(proc.handles['stdout']) as f:
184
 
                    ciphertext = f.read()
185
 
                proc.wait()
186
 
            except IOError as e:
187
 
                raise CryptoError(e)
188
 
        self.gnupg.passphrase = None
189
 
        return ciphertext
190
 
    
191
 
    def decrypt(self, data, password):
192
 
        self.gnupg.passphrase = self.password_encode(password)
193
 
        with open(os.devnull) as devnull:
194
 
            try:
195
 
                proc = self.gnupg.run(['--decrypt'],
196
 
                                      create_fhs=['stdin', 'stdout'],
197
 
                                      attach_fhs={'stderr': devnull})
198
 
                with contextlib.closing(proc.handles['stdin'] ) as f:
199
 
                    f.write(data)
200
 
                with contextlib.closing(proc.handles['stdout']) as f:
201
 
                    decrypted_plaintext = f.read()
202
 
                proc.wait()
203
 
            except IOError as e:
204
 
                raise CryptoError(e)
205
 
        self.gnupg.passphrase = None
206
 
        return decrypted_plaintext
207
 
 
208
 
 
 
93
syslogger.setFormatter(logging.Formatter
 
94
                       ('Mandos [%(process)d]: %(levelname)s:'
 
95
                        ' %(message)s'))
 
96
logger.addHandler(syslogger)
 
97
 
 
98
console = logging.StreamHandler()
 
99
console.setFormatter(logging.Formatter('%(name)s [%(process)d]:'
 
100
                                       ' %(levelname)s:'
 
101
                                       ' %(message)s'))
 
102
logger.addHandler(console)
209
103
 
210
104
class AvahiError(Exception):
211
105
    def __init__(self, value, *args, **kwargs):
270
164
                            .GetAlternativeServiceName(self.name))
271
165
        logger.info("Changing Zeroconf service name to %r ...",
272
166
                    self.name)
 
167
        syslogger.setFormatter(logging.Formatter
 
168
                               ('Mandos (%s) [%%(process)d]:'
 
169
                                ' %%(levelname)s: %%(message)s'
 
170
                                % self.name))
273
171
        self.remove()
274
172
        try:
275
173
            self.add()
295
193
                avahi.DBUS_INTERFACE_ENTRY_GROUP)
296
194
        self.entry_group_state_changed_match = (
297
195
            self.group.connect_to_signal(
298
 
                'StateChanged', self.entry_group_state_changed))
 
196
                'StateChanged', self .entry_group_state_changed))
299
197
        logger.debug("Adding Zeroconf service '%s' of type '%s' ...",
300
198
                     self.name, self.type)
301
199
        self.group.AddService(
327
225
            try:
328
226
                self.group.Free()
329
227
            except (dbus.exceptions.UnknownMethodException,
330
 
                    dbus.exceptions.DBusException):
 
228
                    dbus.exceptions.DBusException) as e:
331
229
                pass
332
230
            self.group = None
333
231
        self.remove()
367
265
                                 self.server_state_changed)
368
266
        self.server_state_changed(self.server.GetState())
369
267
 
370
 
class AvahiServiceToSyslog(AvahiService):
371
 
    def rename(self):
372
 
        """Add the new name to the syslog messages"""
373
 
        ret = AvahiService.rename(self)
374
 
        syslogger.setFormatter(logging.Formatter
375
 
                               ('Mandos (%s) [%%(process)d]:'
376
 
                                ' %%(levelname)s: %%(message)s'
377
 
                                % self.name))
378
 
        return ret
379
268
 
380
 
def timedelta_to_milliseconds(td):
 
269
def _timedelta_to_milliseconds(td):
381
270
    "Convert a datetime.timedelta() to milliseconds"
382
271
    return ((td.days * 24 * 60 * 60 * 1000)
383
272
            + (td.seconds * 1000)
387
276
    """A representation of a client host served by this server.
388
277
    
389
278
    Attributes:
390
 
    approved:   bool(); 'None' if not yet approved/disapproved
 
279
    _approved:   bool(); 'None' if not yet approved/disapproved
391
280
    approval_delay: datetime.timedelta(); Time to wait for approval
392
281
    approval_duration: datetime.timedelta(); Duration of one approval
393
282
    checker:    subprocess.Popen(); a running checker process used
400
289
                     instance %(name)s can be used in the command.
401
290
    checker_initiator_tag: a gobject event source tag, or None
402
291
    created:    datetime.datetime(); (UTC) object creation
403
 
    client_structure: Object describing what attributes a client has
404
 
                      and is used for storing the client at exit
405
292
    current_checker_command: string; current running checker_command
 
293
    disable_hook:  If set, called by disable() as disable_hook(self)
406
294
    disable_initiator_tag: a gobject event source tag, or None
407
295
    enabled:    bool()
408
296
    fingerprint: string (40 or 32 hexadecimal digits); used to
411
299
    interval:   datetime.timedelta(); How often to start a new checker
412
300
    last_approval_request: datetime.datetime(); (UTC) or None
413
301
    last_checked_ok: datetime.datetime(); (UTC) or None
414
 
 
415
 
    last_checker_status: integer between 0 and 255 reflecting exit
416
 
                         status of last checker. -1 reflects crashed
417
 
                         checker, or None.
418
 
    last_enabled: datetime.datetime(); (UTC) or None
 
302
    last_enabled: datetime.datetime(); (UTC)
419
303
    name:       string; from the config file, used in log messages and
420
304
                        D-Bus identifiers
421
305
    secret:     bytestring; sent verbatim (over TLS) to client
434
318
    
435
319
    def timeout_milliseconds(self):
436
320
        "Return the 'timeout' attribute in milliseconds"
437
 
        return timedelta_to_milliseconds(self.timeout)
 
321
        return _timedelta_to_milliseconds(self.timeout)
438
322
    
439
323
    def extended_timeout_milliseconds(self):
440
324
        "Return the 'extended_timeout' attribute in milliseconds"
441
 
        return timedelta_to_milliseconds(self.extended_timeout)
 
325
        return _timedelta_to_milliseconds(self.extended_timeout)
442
326
    
443
327
    def interval_milliseconds(self):
444
328
        "Return the 'interval' attribute in milliseconds"
445
 
        return timedelta_to_milliseconds(self.interval)
 
329
        return _timedelta_to_milliseconds(self.interval)
446
330
    
447
331
    def approval_delay_milliseconds(self):
448
 
        return timedelta_to_milliseconds(self.approval_delay)
 
332
        return _timedelta_to_milliseconds(self.approval_delay)
449
333
    
450
 
    def __init__(self, name = None, config=None):
 
334
    def __init__(self, name = None, disable_hook=None, config=None):
451
335
        """Note: the 'checker' key in 'config' sets the
452
336
        'checker_command' attribute and *not* the 'checker'
453
337
        attribute."""
473
357
                            % self.name)
474
358
        self.host = config.get("host", "")
475
359
        self.created = datetime.datetime.utcnow()
476
 
        self.enabled = config.get("enabled", True)
 
360
        self.enabled = False
477
361
        self.last_approval_request = None
478
 
        if self.enabled:
479
 
            self.last_enabled = datetime.datetime.utcnow()
480
 
        else:
481
 
            self.last_enabled = None
 
362
        self.last_enabled = None
482
363
        self.last_checked_ok = None
483
 
        self.last_checker_status = None
484
364
        self.timeout = string_to_delta(config["timeout"])
485
365
        self.extended_timeout = string_to_delta(config
486
366
                                                ["extended_timeout"])
487
367
        self.interval = string_to_delta(config["interval"])
 
368
        self.disable_hook = disable_hook
488
369
        self.checker = None
489
370
        self.checker_initiator_tag = None
490
371
        self.disable_initiator_tag = None
491
 
        if self.enabled:
492
 
            self.expires = datetime.datetime.utcnow() + self.timeout
493
 
        else:
494
 
            self.expires = None
 
372
        self.expires = None
495
373
        self.checker_callback_tag = None
496
374
        self.checker_command = config["checker"]
497
375
        self.current_checker_command = None
498
 
        self.approved = None
 
376
        self.last_connect = None
 
377
        self._approved = None
499
378
        self.approved_by_default = config.get("approved_by_default",
500
379
                                              True)
501
380
        self.approvals_pending = 0
506
385
        self.changedstate = (multiprocessing_manager
507
386
                             .Condition(multiprocessing_manager
508
387
                                        .Lock()))
509
 
        self.client_structure = [attr for attr in
510
 
                                 self.__dict__.iterkeys()
511
 
                                 if not attr.startswith("_")]
512
 
        self.client_structure.append("client_structure")
513
 
        
514
 
        for name, t in inspect.getmembers(type(self),
515
 
                                          lambda obj:
516
 
                                              isinstance(obj,
517
 
                                                         property)):
518
 
            if not name.startswith("_"):
519
 
                self.client_structure.append(name)
520
388
    
521
 
    # Send notice to process children that client state has changed
522
389
    def send_changedstate(self):
523
 
        with self.changedstate:
524
 
            self.changedstate.notify_all()
 
390
        self.changedstate.acquire()
 
391
        self.changedstate.notify_all()
 
392
        self.changedstate.release()
525
393
    
526
394
    def enable(self):
527
395
        """Start this client's checker and timeout hooks"""
529
397
            # Already enabled
530
398
            return
531
399
        self.send_changedstate()
 
400
        # Schedule a new checker to be started an 'interval' from now,
 
401
        # and every interval from then on.
 
402
        self.checker_initiator_tag = (gobject.timeout_add
 
403
                                      (self.interval_milliseconds(),
 
404
                                       self.start_checker))
 
405
        # Schedule a disable() when 'timeout' has passed
532
406
        self.expires = datetime.datetime.utcnow() + self.timeout
 
407
        self.disable_initiator_tag = (gobject.timeout_add
 
408
                                   (self.timeout_milliseconds(),
 
409
                                    self.disable))
533
410
        self.enabled = True
534
411
        self.last_enabled = datetime.datetime.utcnow()
535
 
        self.init_checker()
 
412
        # Also start a new checker *right now*.
 
413
        self.start_checker()
536
414
    
537
415
    def disable(self, quiet=True):
538
416
        """Disable this client."""
550
428
            gobject.source_remove(self.checker_initiator_tag)
551
429
            self.checker_initiator_tag = None
552
430
        self.stop_checker()
 
431
        if self.disable_hook:
 
432
            self.disable_hook(self)
553
433
        self.enabled = False
554
434
        # Do not run this again if called by a gobject.timeout_add
555
435
        return False
556
436
    
557
437
    def __del__(self):
 
438
        self.disable_hook = None
558
439
        self.disable()
559
440
    
560
 
    def init_checker(self):
561
 
        # Schedule a new checker to be started an 'interval' from now,
562
 
        # and every interval from then on.
563
 
        self.checker_initiator_tag = (gobject.timeout_add
564
 
                                      (self.interval_milliseconds(),
565
 
                                       self.start_checker))
566
 
        # Schedule a disable() when 'timeout' has passed
567
 
        self.disable_initiator_tag = (gobject.timeout_add
568
 
                                   (self.timeout_milliseconds(),
569
 
                                    self.disable))
570
 
        # Also start a new checker *right now*.
571
 
        self.start_checker()
572
 
    
573
441
    def checker_callback(self, pid, condition, command):
574
442
        """The checker has completed, so take appropriate actions."""
575
443
        self.checker_callback_tag = None
576
444
        self.checker = None
577
445
        if os.WIFEXITED(condition):
578
 
            self.last_checker_status =  os.WEXITSTATUS(condition)
579
 
            if self.last_checker_status == 0:
 
446
            exitstatus = os.WEXITSTATUS(condition)
 
447
            if exitstatus == 0:
580
448
                logger.info("Checker for %(name)s succeeded",
581
449
                            vars(self))
582
450
                self.checked_ok()
584
452
                logger.info("Checker for %(name)s failed",
585
453
                            vars(self))
586
454
        else:
587
 
            self.last_checker_status = -1
588
455
            logger.warning("Checker for %(name)s crashed?",
589
456
                           vars(self))
590
457
    
597
464
        if timeout is None:
598
465
            timeout = self.timeout
599
466
        self.last_checked_ok = datetime.datetime.utcnow()
600
 
        if self.disable_initiator_tag is not None:
601
 
            gobject.source_remove(self.disable_initiator_tag)
602
 
        if getattr(self, "enabled", False):
603
 
            self.disable_initiator_tag = (gobject.timeout_add
604
 
                                          (timedelta_to_milliseconds
605
 
                                           (timeout), self.disable))
606
 
            self.expires = datetime.datetime.utcnow() + timeout
 
467
        gobject.source_remove(self.disable_initiator_tag)
 
468
        self.disable_initiator_tag = (gobject.timeout_add
 
469
                                      (_timedelta_to_milliseconds
 
470
                                       (timeout), self.disable))
 
471
        self.expires = datetime.datetime.utcnow() + timeout
607
472
    
608
473
    def need_approval(self):
609
474
        self.last_approval_request = datetime.datetime.utcnow()
824
689
        
825
690
        Note: Will not include properties with access="write".
826
691
        """
827
 
        properties = {}
 
692
        all = {}
828
693
        for name, prop in self._get_all_dbus_properties():
829
694
            if (interface_name
830
695
                and interface_name != prop._dbus_interface):
835
700
                continue
836
701
            value = prop()
837
702
            if not hasattr(value, "variant_level"):
838
 
                properties[name] = value
 
703
                all[name] = value
839
704
                continue
840
 
            properties[name] = type(value)(value, variant_level=
841
 
                                           value.variant_level+1)
842
 
        return dbus.Dictionary(properties, signature="sv")
 
705
            all[name] = type(value)(value, variant_level=
 
706
                                    value.variant_level+1)
 
707
        return dbus.Dictionary(all, signature="sv")
843
708
    
844
709
    @dbus.service.method(dbus.INTROSPECTABLE_IFACE,
845
710
                         out_signature="s",
896
761
    return dbus.String(dt.isoformat(),
897
762
                       variant_level=variant_level)
898
763
 
899
 
 
900
764
class AlternateDBusNamesMetaclass(DBusObjectWithProperties
901
765
                                  .__metaclass__):
902
766
    """Applied to an empty subclass of a D-Bus object, this metaclass
994
858
                                        attribute.func_closure)))
995
859
        return type.__new__(mcs, name, bases, attr)
996
860
 
997
 
 
998
861
class ClientDBus(Client, DBusObjectWithProperties):
999
862
    """A Client class using D-Bus
1000
863
    
1009
872
    # dbus.service.Object doesn't use super(), so we can't either.
1010
873
    
1011
874
    def __init__(self, bus = None, *args, **kwargs):
 
875
        self._approvals_pending = 0
1012
876
        self.bus = bus
1013
877
        Client.__init__(self, *args, **kwargs)
1014
 
        
1015
 
        self._approvals_pending = 0
1016
878
        # Only now, when this client is initialized, can it show up on
1017
879
        # the D-Bus
1018
880
        client_object_name = unicode(self.name).translate(
1028
890
                             variant_level=1):
1029
891
        """ Modify a variable so that it's a property which announces
1030
892
        its changes to DBus.
1031
 
        
1032
 
        transform_fun: Function that takes a value and a variant_level
1033
 
                       and transforms it to a D-Bus type.
 
893
 
 
894
        transform_fun: Function that takes a value and transforms it
 
895
                       to a D-Bus type.
1034
896
        dbus_name: D-Bus name of the variable
1035
897
        type_func: Function that transform the value before sending it
1036
898
                   to the D-Bus.  Default: no transform
1043
905
                    type_func(getattr(self, attrname, None))
1044
906
                    != type_func(value)):
1045
907
                    dbus_value = transform_func(type_func(value),
1046
 
                                                variant_level
1047
 
                                                =variant_level)
 
908
                                                variant_level)
1048
909
                    self.PropertyChanged(dbus.String(dbus_name),
1049
910
                                         dbus_value)
1050
911
            setattr(self, attrname, value)
1071
932
    approval_delay = notifychangeproperty(dbus.UInt16,
1072
933
                                          "ApprovalDelay",
1073
934
                                          type_func =
1074
 
                                          timedelta_to_milliseconds)
 
935
                                          _timedelta_to_milliseconds)
1075
936
    approval_duration = notifychangeproperty(
1076
937
        dbus.UInt16, "ApprovalDuration",
1077
 
        type_func = timedelta_to_milliseconds)
 
938
        type_func = _timedelta_to_milliseconds)
1078
939
    host = notifychangeproperty(dbus.String, "Host")
1079
940
    timeout = notifychangeproperty(dbus.UInt16, "Timeout",
1080
941
                                   type_func =
1081
 
                                   timedelta_to_milliseconds)
 
942
                                   _timedelta_to_milliseconds)
1082
943
    extended_timeout = notifychangeproperty(
1083
944
        dbus.UInt16, "ExtendedTimeout",
1084
 
        type_func = timedelta_to_milliseconds)
 
945
        type_func = _timedelta_to_milliseconds)
1085
946
    interval = notifychangeproperty(dbus.UInt16,
1086
947
                                    "Interval",
1087
948
                                    type_func =
1088
 
                                    timedelta_to_milliseconds)
 
949
                                    _timedelta_to_milliseconds)
1089
950
    checker_command = notifychangeproperty(dbus.String, "Checker")
1090
951
    
1091
952
    del notifychangeproperty
1133
994
        return r
1134
995
    
1135
996
    def _reset_approved(self):
1136
 
        self.approved = None
 
997
        self._approved = None
1137
998
        return False
1138
999
    
1139
1000
    def approve(self, value=True):
1140
1001
        self.send_changedstate()
1141
 
        self.approved = value
1142
 
        gobject.timeout_add(timedelta_to_milliseconds
 
1002
        self._approved = value
 
1003
        gobject.timeout_add(_timedelta_to_milliseconds
1143
1004
                            (self.approval_duration),
1144
1005
                            self._reset_approved)
1145
1006
    
1188
1049
        "D-Bus signal"
1189
1050
        return self.need_approval()
1190
1051
    
1191
 
    # NeRwequest - signal
1192
 
    @dbus.service.signal(_interface, signature="s")
1193
 
    def NewRequest(self, ip):
1194
 
        """D-Bus signal
1195
 
        Is sent after a client request a password.
1196
 
        """
1197
 
        pass
1198
 
    
1199
1052
    ## Methods
1200
1053
    
1201
1054
    # Approve - method
1259
1112
                           access="readwrite")
1260
1113
    def ApprovalDuration_dbus_property(self, value=None):
1261
1114
        if value is None:       # get
1262
 
            return dbus.UInt64(timedelta_to_milliseconds(
 
1115
            return dbus.UInt64(_timedelta_to_milliseconds(
1263
1116
                    self.approval_duration))
1264
1117
        self.approval_duration = datetime.timedelta(0, 0, 0, value)
1265
1118
    
1284
1137
    # Created - property
1285
1138
    @dbus_service_property(_interface, signature="s", access="read")
1286
1139
    def Created_dbus_property(self):
1287
 
        return datetime_to_dbus(self.created)
 
1140
        return dbus.String(datetime_to_dbus(self.created))
1288
1141
    
1289
1142
    # LastEnabled - property
1290
1143
    @dbus_service_property(_interface, signature="s", access="read")
1334
1187
        gobject.source_remove(self.disable_initiator_tag)
1335
1188
        self.disable_initiator_tag = None
1336
1189
        self.expires = None
1337
 
        time_to_die = timedelta_to_milliseconds((self
1338
 
                                                 .last_checked_ok
1339
 
                                                 + self.timeout)
1340
 
                                                - datetime.datetime
1341
 
                                                .utcnow())
 
1190
        time_to_die = (self.
 
1191
                       _timedelta_to_milliseconds((self
 
1192
                                                   .last_checked_ok
 
1193
                                                   + self.timeout)
 
1194
                                                  - datetime.datetime
 
1195
                                                  .utcnow()))
1342
1196
        if time_to_die <= 0:
1343
1197
            # The timeout has passed
1344
1198
            self.disable()
1366
1220
        self.interval = datetime.timedelta(0, 0, 0, value)
1367
1221
        if getattr(self, "checker_initiator_tag", None) is None:
1368
1222
            return
1369
 
        if self.enabled:
1370
 
            # Reschedule checker run
1371
 
            gobject.source_remove(self.checker_initiator_tag)
1372
 
            self.checker_initiator_tag = (gobject.timeout_add
1373
 
                                          (value, self.start_checker))
1374
 
            self.start_checker()    # Start one now, too
 
1223
        # Reschedule checker run
 
1224
        gobject.source_remove(self.checker_initiator_tag)
 
1225
        self.checker_initiator_tag = (gobject.timeout_add
 
1226
                                      (value, self.start_checker))
 
1227
        self.start_checker()    # Start one now, too
1375
1228
    
1376
1229
    # Checker - property
1377
1230
    @dbus_service_property(_interface, signature="s",
1414
1267
            raise KeyError()
1415
1268
    
1416
1269
    def __getattribute__(self, name):
1417
 
        if name == '_pipe':
 
1270
        if(name == '_pipe'):
1418
1271
            return super(ProxyClient, self).__getattribute__(name)
1419
1272
        self._pipe.send(('getattr', name))
1420
1273
        data = self._pipe.recv()
1427
1280
            return func
1428
1281
    
1429
1282
    def __setattr__(self, name, value):
1430
 
        if name == '_pipe':
 
1283
        if(name == '_pipe'):
1431
1284
            return super(ProxyClient, self).__setattr__(name, value)
1432
1285
        self._pipe.send(('setattr', name, value))
1433
1286
 
1434
 
 
1435
1287
class ClientDBusTransitional(ClientDBus):
1436
1288
    __metaclass__ = AlternateDBusNamesMetaclass
1437
1289
 
1438
 
 
1439
1290
class ClientHandler(socketserver.BaseRequestHandler, object):
1440
1291
    """A class to handle client connections.
1441
1292
    
1509
1360
                except KeyError:
1510
1361
                    return
1511
1362
                
1512
 
                if self.server.use_dbus:
1513
 
                    # Emit D-Bus signal
1514
 
                    client.NewRequest(str(self.client_address))
1515
 
                
1516
1363
                if client.approval_delay:
1517
1364
                    delay = client.approval_delay
1518
1365
                    client.approvals_pending += 1
1527
1374
                            client.Rejected("Disabled")
1528
1375
                        return
1529
1376
                    
1530
 
                    if client.approved or not client.approval_delay:
 
1377
                    if client._approved or not client.approval_delay:
1531
1378
                        #We are approved or approval is disabled
1532
1379
                        break
1533
 
                    elif client.approved is None:
 
1380
                    elif client._approved is None:
1534
1381
                        logger.info("Client %s needs approval",
1535
1382
                                    client.name)
1536
1383
                        if self.server.use_dbus:
1550
1397
                    time = datetime.datetime.now()
1551
1398
                    client.changedstate.acquire()
1552
1399
                    (client.changedstate.wait
1553
 
                     (float(client.timedelta_to_milliseconds(delay)
 
1400
                     (float(client._timedelta_to_milliseconds(delay)
1554
1401
                            / 1000)))
1555
1402
                    client.changedstate.release()
1556
1403
                    time2 = datetime.datetime.now()
1655
1502
        # Convert the buffer to a Python bytestring
1656
1503
        fpr = ctypes.string_at(buf, buf_len.value)
1657
1504
        # Convert the bytestring to hexadecimal notation
1658
 
        hex_fpr = binascii.hexlify(fpr).upper()
 
1505
        hex_fpr = ''.join("%02X" % ord(char) for char in fpr)
1659
1506
        return hex_fpr
1660
1507
 
1661
1508
 
1775
1622
        self.enabled = False
1776
1623
        self.clients = clients
1777
1624
        if self.clients is None:
1778
 
            self.clients = {}
 
1625
            self.clients = set()
1779
1626
        self.use_dbus = use_dbus
1780
1627
        self.gnutls_priority = gnutls_priority
1781
1628
        IPv6_TCPServer.__init__(self, server_address,
1828
1675
            fpr = request[1]
1829
1676
            address = request[2]
1830
1677
            
1831
 
            for c in self.clients.itervalues():
 
1678
            for c in self.clients:
1832
1679
                if c.fingerprint == fpr:
1833
1680
                    client = c
1834
1681
                    break
1918
1765
    return timevalue
1919
1766
 
1920
1767
 
 
1768
def if_nametoindex(interface):
 
1769
    """Call the C function if_nametoindex(), or equivalent
 
1770
    
 
1771
    Note: This function cannot accept a unicode string."""
 
1772
    global if_nametoindex
 
1773
    try:
 
1774
        if_nametoindex = (ctypes.cdll.LoadLibrary
 
1775
                          (ctypes.util.find_library("c"))
 
1776
                          .if_nametoindex)
 
1777
    except (OSError, AttributeError):
 
1778
        logger.warning("Doing if_nametoindex the hard way")
 
1779
        def if_nametoindex(interface):
 
1780
            "Get an interface index the hard way, i.e. using fcntl()"
 
1781
            SIOCGIFINDEX = 0x8933  # From /usr/include/linux/sockios.h
 
1782
            with contextlib.closing(socket.socket()) as s:
 
1783
                ifreq = fcntl.ioctl(s, SIOCGIFINDEX,
 
1784
                                    struct.pack(str("16s16x"),
 
1785
                                                interface))
 
1786
            interface_index = struct.unpack(str("I"),
 
1787
                                            ifreq[16:20])[0]
 
1788
            return interface_index
 
1789
    return if_nametoindex(interface)
 
1790
 
 
1791
 
1921
1792
def daemon(nochdir = False, noclose = False):
1922
1793
    """See daemon(3).  Standard BSD Unix function.
1923
1794
    
1978
1849
                        " system bus interface")
1979
1850
    parser.add_argument("--no-ipv6", action="store_false",
1980
1851
                        dest="use_ipv6", help="Do not use IPv6")
1981
 
    parser.add_argument("--no-restore", action="store_false",
1982
 
                        dest="restore", help="Do not restore stored"
1983
 
                        " state")
1984
 
    parser.add_argument("--statedir", metavar="DIR",
1985
 
                        help="Directory to save/restore state in")
1986
 
    
1987
1852
    options = parser.parse_args()
1988
1853
    
1989
1854
    if options.check:
2002
1867
                        "use_dbus": "True",
2003
1868
                        "use_ipv6": "True",
2004
1869
                        "debuglevel": "",
2005
 
                        "restore": "True",
2006
 
                        "statedir": "/var/lib/mandos"
2007
1870
                        }
2008
1871
    
2009
1872
    # Parse config file for server-global settings
2026
1889
    # options, if set.
2027
1890
    for option in ("interface", "address", "port", "debug",
2028
1891
                   "priority", "servicename", "configdir",
2029
 
                   "use_dbus", "use_ipv6", "debuglevel", "restore",
2030
 
                   "statedir"):
 
1892
                   "use_dbus", "use_ipv6", "debuglevel"):
2031
1893
        value = getattr(options, option)
2032
1894
        if value is not None:
2033
1895
            server_settings[option] = value
2045
1907
    debuglevel = server_settings["debuglevel"]
2046
1908
    use_dbus = server_settings["use_dbus"]
2047
1909
    use_ipv6 = server_settings["use_ipv6"]
2048
 
    stored_state_path = os.path.join(server_settings["statedir"],
2049
 
                                     stored_state_file)
2050
 
    
2051
 
    if debug:
2052
 
        initlogger(logging.DEBUG)
2053
 
    else:
2054
 
        if not debuglevel:
2055
 
            initlogger()
2056
 
        else:
2057
 
            level = getattr(logging, debuglevel.upper())
2058
 
            initlogger(level)
2059
1910
    
2060
1911
    if server_settings["servicename"] != "Mandos":
2061
1912
        syslogger.setFormatter(logging.Formatter
2116
1967
        if error[0] != errno.EPERM:
2117
1968
            raise error
2118
1969
    
 
1970
    if not debug and not debuglevel:
 
1971
        syslogger.setLevel(logging.WARNING)
 
1972
        console.setLevel(logging.WARNING)
 
1973
    if debuglevel:
 
1974
        level = getattr(logging, debuglevel.upper())
 
1975
        syslogger.setLevel(level)
 
1976
        console.setLevel(level)
 
1977
    
2119
1978
    if debug:
2120
1979
        # Enable all possible GnuTLS debugging
2121
1980
        
2163
2022
            server_settings["use_dbus"] = False
2164
2023
            tcp_server.use_dbus = False
2165
2024
    protocol = avahi.PROTO_INET6 if use_ipv6 else avahi.PROTO_INET
2166
 
    service = AvahiServiceToSyslog(name =
2167
 
                                   server_settings["servicename"],
2168
 
                                   servicetype = "_mandos._tcp",
2169
 
                                   protocol = protocol, bus = bus)
 
2025
    service = AvahiService(name = server_settings["servicename"],
 
2026
                           servicetype = "_mandos._tcp",
 
2027
                           protocol = protocol, bus = bus)
2170
2028
    if server_settings["interface"]:
2171
2029
        service.interface = (if_nametoindex
2172
2030
                             (str(server_settings["interface"])))
2178
2036
    if use_dbus:
2179
2037
        client_class = functools.partial(ClientDBusTransitional,
2180
2038
                                         bus = bus)
2181
 
    
2182
 
    special_settings = {
2183
 
        # Some settings need to be accessd by special methods;
2184
 
        # booleans need .getboolean(), etc.  Here is a list of them:
2185
 
        "approved_by_default":
2186
 
            lambda section:
2187
 
            client_config.getboolean(section, "approved_by_default"),
2188
 
        "enabled":
2189
 
            lambda section:
2190
 
            client_config.getboolean(section, "enabled"),
2191
 
        }
2192
 
    # Construct a new dict of client settings of this form:
2193
 
    # { client_name: {setting_name: value, ...}, ...}
2194
 
    # with exceptions for any special settings as defined above
2195
 
    client_settings = dict((clientname,
2196
 
                           dict((setting,
2197
 
                                 (value
2198
 
                                  if setting not in special_settings
2199
 
                                  else special_settings[setting]
2200
 
                                  (clientname)))
2201
 
                                for setting, value in
2202
 
                                client_config.items(clientname)))
2203
 
                          for clientname in client_config.sections())
2204
 
    
2205
 
    old_client_settings = {}
2206
 
    clients_data = []
2207
 
    
2208
 
    # Get client data and settings from last running state.
2209
 
    if server_settings["restore"]:
2210
 
        try:
2211
 
            with open(stored_state_path, "rb") as stored_state:
2212
 
                clients_data, old_client_settings = (pickle.load
2213
 
                                                     (stored_state))
2214
 
            os.remove(stored_state_path)
2215
 
        except IOError as e:
2216
 
            logger.warning("Could not load persistent state: {0}"
2217
 
                           .format(e))
2218
 
            if e.errno != errno.ENOENT:
2219
 
                raise
2220
 
    
2221
 
    with Crypto() as crypt:
2222
 
        for client in clients_data:
2223
 
            client_name = client["name"]
2224
 
            
2225
 
            # Decide which value to use after restoring saved state.
2226
 
            # We have three different values: Old config file,
2227
 
            # new config file, and saved state.
2228
 
            # New config value takes precedence if it differs from old
2229
 
            # config value, otherwise use saved state.
2230
 
            for name, value in client_settings[client_name].items():
2231
 
                try:
2232
 
                    # For each value in new config, check if it
2233
 
                    # differs from the old config value (Except for
2234
 
                    # the "secret" attribute)
2235
 
                    if (name != "secret" and
2236
 
                        value != old_client_settings[client_name]
2237
 
                        [name]):
2238
 
                        setattr(client, name, value)
2239
 
                except KeyError:
2240
 
                    pass
2241
 
            
2242
 
            # Clients who has passed its expire date can still be
2243
 
            # enabled if its last checker was sucessful.  Clients
2244
 
            # whose checker failed before we stored its state is
2245
 
            # assumed to have failed all checkers during downtime.
2246
 
            if client["enabled"] and client["last_checked_ok"]:
2247
 
                if ((datetime.datetime.utcnow()
2248
 
                     - client["last_checked_ok"])
2249
 
                    > client["interval"]):
2250
 
                    if client["last_checker_status"] != 0:
2251
 
                        client["enabled"] = False
2252
 
                    else:
2253
 
                        client["expires"] = (datetime.datetime
2254
 
                                             .utcnow()
2255
 
                                             + client["timeout"])
2256
 
            
2257
 
            client["changedstate"] = (multiprocessing_manager
2258
 
                                      .Condition
2259
 
                                      (multiprocessing_manager
2260
 
                                       .Lock()))
2261
 
            if use_dbus:
2262
 
                new_client = (ClientDBusTransitional.__new__
2263
 
                              (ClientDBusTransitional))
2264
 
                tcp_server.clients[client_name] = new_client
2265
 
                new_client.bus = bus
2266
 
                for name, value in client.iteritems():
2267
 
                    setattr(new_client, name, value)
2268
 
                client_object_name = unicode(client_name).translate(
2269
 
                    {ord("."): ord("_"),
2270
 
                     ord("-"): ord("_")})
2271
 
                new_client.dbus_object_path = (dbus.ObjectPath
2272
 
                                               ("/clients/"
2273
 
                                                + client_object_name))
2274
 
                DBusObjectWithProperties.__init__(new_client,
2275
 
                                                  new_client.bus,
2276
 
                                                  new_client
2277
 
                                                  .dbus_object_path)
2278
 
            else:
2279
 
                tcp_server.clients[client_name] = (Client.__new__
2280
 
                                                   (Client))
2281
 
                for name, value in client.iteritems():
2282
 
                    setattr(tcp_server.clients[client_name],
2283
 
                            name, value)
2284
 
            
 
2039
    def client_config_items(config, section):
 
2040
        special_settings = {
 
2041
            "approved_by_default":
 
2042
                lambda: config.getboolean(section,
 
2043
                                          "approved_by_default"),
 
2044
            }
 
2045
        for name, value in config.items(section):
2285
2046
            try:
2286
 
                tcp_server.clients[client_name].secret = (
2287
 
                    crypt.decrypt(tcp_server.clients[client_name]
2288
 
                                  .encrypted_secret,
2289
 
                                  client_settings[client_name]
2290
 
                                  ["secret"]))
2291
 
            except CryptoError:
2292
 
                # If decryption fails, we use secret from new settings
2293
 
                tcp_server.clients[client_name].secret = (
2294
 
                    client_settings[client_name]["secret"])
2295
 
    
2296
 
    # Create/remove clients based on new changes made to config
2297
 
    for clientname in set(old_client_settings) - set(client_settings):
2298
 
        del tcp_server.clients[clientname]
2299
 
    for clientname in set(client_settings) - set(old_client_settings):
2300
 
        tcp_server.clients[clientname] = (client_class(name
2301
 
                                                       = clientname,
2302
 
                                                       config =
2303
 
                                                       client_settings
2304
 
                                                       [clientname]))
2305
 
    
 
2047
                yield (name, special_settings[name]())
 
2048
            except KeyError:
 
2049
                yield (name, value)
 
2050
    
 
2051
    tcp_server.clients.update(set(
 
2052
            client_class(name = section,
 
2053
                         config= dict(client_config_items(
 
2054
                        client_config, section)))
 
2055
            for section in client_config.sections()))
2306
2056
    if not tcp_server.clients:
2307
2057
        logger.warning("No clients defined")
2308
2058
        
2351
2101
            def GetAllClients(self):
2352
2102
                "D-Bus method"
2353
2103
                return dbus.Array(c.dbus_object_path
2354
 
                                  for c in
2355
 
                                  tcp_server.clients.itervalues())
 
2104
                                  for c in tcp_server.clients)
2356
2105
            
2357
2106
            @dbus.service.method(_interface,
2358
2107
                                 out_signature="a{oa{sv}}")
2360
2109
                "D-Bus method"
2361
2110
                return dbus.Dictionary(
2362
2111
                    ((c.dbus_object_path, c.GetAll(""))
2363
 
                     for c in tcp_server.clients.itervalues()),
 
2112
                     for c in tcp_server.clients),
2364
2113
                    signature="oa{sv}")
2365
2114
            
2366
2115
            @dbus.service.method(_interface, in_signature="o")
2367
2116
            def RemoveClient(self, object_path):
2368
2117
                "D-Bus method"
2369
 
                for c in tcp_server.clients.itervalues():
 
2118
                for c in tcp_server.clients:
2370
2119
                    if c.dbus_object_path == object_path:
2371
 
                        del tcp_server.clients[c.name]
 
2120
                        tcp_server.clients.remove(c)
2372
2121
                        c.remove_from_connection()
2373
2122
                        # Don't signal anything except ClientRemoved
2374
2123
                        c.disable(quiet=True)
2388
2137
        service.cleanup()
2389
2138
        
2390
2139
        multiprocessing.active_children()
2391
 
        if not (tcp_server.clients or client_settings):
2392
 
            return
2393
 
        
2394
 
        # Store client before exiting. Secrets are encrypted with key
2395
 
        # based on what config file has. If config file is
2396
 
        # removed/edited, old secret will thus be unrecovable.
2397
 
        clients = []
2398
 
        with Crypto() as crypt:
2399
 
            for client in tcp_server.clients.itervalues():
2400
 
                key = client_settings[client.name]["secret"]
2401
 
                client.encrypted_secret = crypt.encrypt(client.secret,
2402
 
                                                        key)
2403
 
                client_dict = {}
2404
 
                
2405
 
                # A list of attributes that will not be stored when
2406
 
                # shutting down.
2407
 
                exclude = set(("bus", "changedstate", "secret"))
2408
 
                for name, typ in (inspect.getmembers
2409
 
                                  (dbus.service.Object)):
2410
 
                    exclude.add(name)
2411
 
                
2412
 
                client_dict["encrypted_secret"] = (client
2413
 
                                                   .encrypted_secret)
2414
 
                for attr in client.client_structure:
2415
 
                    if attr not in exclude:
2416
 
                        client_dict[attr] = getattr(client, attr)
2417
 
                
2418
 
                clients.append(client_dict)
2419
 
                del client_settings[client.name]["secret"]
2420
 
        
2421
 
        try:
2422
 
            with os.fdopen(os.open(stored_state_path,
2423
 
                                   os.O_CREAT|os.O_WRONLY|os.O_TRUNC,
2424
 
                                   0600), "wb") as stored_state:
2425
 
                pickle.dump((clients, client_settings), stored_state)
2426
 
        except (IOError, OSError) as e:
2427
 
            logger.warning("Could not save persistent state: {0}"
2428
 
                           .format(e))
2429
 
            if e.errno not in (errno.ENOENT, errno.EACCES):
2430
 
                raise
2431
 
        
2432
 
        # Delete all clients, and settings from config
2433
2140
        while tcp_server.clients:
2434
 
            name, client = tcp_server.clients.popitem()
 
2141
            client = tcp_server.clients.pop()
2435
2142
            if use_dbus:
2436
2143
                client.remove_from_connection()
 
2144
            client.disable_hook = None
2437
2145
            # Don't signal anything except ClientRemoved
2438
2146
            client.disable(quiet=True)
2439
2147
            if use_dbus:
2441
2149
                mandos_dbus_service.ClientRemoved(client
2442
2150
                                                  .dbus_object_path,
2443
2151
                                                  client.name)
2444
 
        client_settings.clear()
2445
2152
    
2446
2153
    atexit.register(cleanup)
2447
2154
    
2448
 
    for client in tcp_server.clients.itervalues():
 
2155
    for client in tcp_server.clients:
2449
2156
        if use_dbus:
2450
2157
            # Emit D-Bus signal
2451
2158
            mandos_dbus_service.ClientAdded(client.dbus_object_path)
2452
 
        # Need to initiate checking of clients
2453
 
        if client.enabled:
2454
 
            client.init_checker()
 
2159
        client.enable()
2455
2160
    
2456
2161
    tcp_server.enable()
2457
2162
    tcp_server.server_activate()