summaryrefslogtreecommitdiffstats
path: root/src/sbin/bcfg2
blob: 62f2e177589539768243b8d342143ceb0e6726e7 (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
#!/usr/bin/env python

'''Bcfg2 Client'''
__revision__ = '$Revision$'

import getopt
import logging
import os
import signal
import socket
import sys
import tempfile
import time
import xmlrpclib
import Bcfg2.Options
import Bcfg2.Client.XML
import Bcfg2.Client.Frame
import Bcfg2.Client.Tools
import Bcfg2.Daemon
from Bcfg2.Component import *
from Bcfg2.tlslite.Checker import Checker
from Bcfg2.tlslite.errors import *

try:
    import Bcfg2.Client.Proxy
    import Bcfg2.Logging
except KeyError:
    print "Could not read options from configuration file"
    raise SystemExit(1)


def cb_sigint_handler(signum, frame):
    '''Exit upon CTRL-C'''
    os._exit(1)

class Client:
    ''' The main bcfg2 client class '''

    def __init__(self):
        self.toolset = None
        self.config = None

        optinfo = {
            # 'optname': (('-a', argdesc, optdesc),
            #                  env, cfpath, default, boolean)),
            'verbose': (('-v', False, "enable verbose output"),
                        False, False, False, True),
            'extra': (('-e', False, "enable extra entry output"),
                      False, False, False, True),
            'quick': (('-q', False, "disable some checksum verification"),
                      False, False, False, True),
            'debug': (('-d', False, "enable debugging output"),
                      False, False, False, True),
            'drivers': (('-D', '<driver1>,<driver2>', "Specify tool driver set"),
                        False, ('client', 'drivers'), False, False),
            'fingerprint': (('-F', '<server fingerprint>', "Server Fingerprint"),
                            False, ('communication', 'fingerprint'), False, False),
            'dryrun': (('-n', False, "do not actually change the system"),
                       False, False, False, True),
            'build': (('-B', False, "run in build mode"),
                      False, False, False, True),
            'paranoid': (('-P', False, "make automatic backups of config files"),
                         False, False, False, True),
            'bundle': (('-b', '<bundle>', "only configure the given bundle"),
                       False, False, False, False),
            'file': (('-f', "<configspec>", "configure from a file rather than querying the server"),
                     False, False, False, False),
            'interactive': (('-I', False, "prompt the user for each change"),
                      False, False, False, True),
            'cache': (('-c', "<configspec>", "store the configuration in a file"),
                      False, False, False, False),
            'profile': (('-p', '<profile>', "assert the given profile for the host"),
                        False, False, False, False),
            'remove': (('-r', '(packages|services|all)', "force removal of additional configuration items"),
                       False, False, False, False),
            'help': (('-h', False, "print this help message"),
                     False, False, False, True),
            'setup': (('-C', '<configfile>', "use given config file (default /etc/bcfg2.conf)"),
                      False, False, '/etc/bcfg2.conf', False),
            'server': (('-S', '<server url>', 'the server hostname to connect to'),
                       False, ('components', 'bcfg2'), False, False),
            'user': (('-u', '<user>', 'the user to provide for authentication'),
                     False, ('communication', 'user'), False, False),
            'password': (('-x', '<password>', 'the password to provide for authentication'),
                         False, ('communication', 'password'), False, False),
            'retries': (('-R', '<numretries>', 'the number of times to retry network communication'),
                        False, ('communication', 'retries'), '3', False),
            'kevlar': (('-k', False, "run in kevlar (bulletproof) mode"),
                       False, False, False, True),
            'agent': (('-A', False, "run in agent (continuous) mode, wait for reconfigure command from server"),
                       False, False, False, True),
            'agent-port': (('-g', '<agent tcp port>', 'the port on which to bind for agent mode'),
                       False, ('communication', 'agent-port'), '6789', False),
            'agent-background': (('-i', '<pidfile name>', "Daemonize the agent"),
                                 False, False, False, False),
            'key': (('-K', '<client key file>', 'ssl cert + private key for agent mode xmlrpc server'),
                           False, ('communication', 'key'), False, False),
            }

        optparser = Bcfg2.Options.OptionParser('bcfg2', optinfo)
        self.setup = optparser.parse()

        # override default settings
        settings.read_config_file(self.setup['setup'])

        if getopt.getopt(sys.argv[1:],
                         optparser.shortopt, optparser.longopt)[1]:
            print "Bcfg2 takes no arguments, only options"
            print optparser.helpmsg
            raise SystemExit(1)
        level = 30
        if self.setup['verbose']:
            level = 20
        if self.setup['debug']:
            level = 0
        Bcfg2.Logging.setup_logging('bcfg2', to_syslog=False, level=level)
        self.logger = logging.getLogger('bcfg2')
        self.logger.debug(self.setup)
        if 'drivers' in self.setup and self.setup['drivers'] == 'help':
            self.logger.info("The following drivers are available:")
            self.logger.info(Bcfg2.Client.Tools.drivers)
            raise SystemExit(0)
        if self.setup['remove'] and 'services' in self.setup['remove']:
            self.logger.error("Service removal is nonsensical, disable services to get former behavior")
        if self.setup['remove'] not in [False, 'all', 'services', 'packages']:
            self.logger.error("Got unknown argument %s for -r" % (self.setup['remove']))
        if (self.setup["file"] != False) and (self.setup["cache"] != False):
            print "cannot use -f and -c together"
            raise SystemExit(1)
        if (self.setup["agent"] != False) and (self.setup["interactive"] != False):
            print "cannot use -A and -I together"
            raise SystemExit(1)
        if (self.setup["agent"] and not self.setup["fingerprint"]):
            print "Agent mode requires specification of x509 fingerprint"
            raise SystemExit(1)
        if (self.setup["agent"] and not self.setup["key"]):
            print "Agent mode requires specification of ssl cert + key file"
            raise SystemExit(1)

    def run_probe(self, probe):
        '''Execute probe'''
        name = probe.get('name')
        self.logger.info("Running probe %s" % name)
        ret = Bcfg2.Client.XML.Element("probe-data", name=name, source=probe.get('source'))
        try:
            script = open(tempfile.mktemp(), 'w+')
            try:
                script.write("#!%s\n" %
                             (probe.attrib.get('interpreter', '/bin/sh')))
                script.write(probe.text)
                script.close()
                os.chmod(script.name, 0755)
                ret.text = os.popen(script.name).read().strip()
                self.logger.info("Probe %s has result:\n%s" % (name, ret.text))
            finally:
                os.unlink(script.name)
        except:
            self.logger.error("Failed to execute probe: %s" % (name), exc_info=1)
            raise SystemExit(1)
        return ret

    def fatal_error(self, message):
        '''Signal a fatal error'''
        self.logger.error("Fatal error: %s" % (message))
        if not self.setup["agent"]:
            raise SystemExit(1)
        else:
            self.logger.error("Continuing...")
        
    def run(self):
        ''' Perform client execution phase '''
        times = {}

        # begin configuration
        times['start'] = time.time()

        if self.setup['file']:
            # read config from file
            try:
                self.logger.debug("reading cached configuration from %s" %
                                  (self.setup['file']))
                configfile = open(self.setup['file'], 'r')
                rawconfig = configfile.read()
                configfile.close()
            except IOError:
                self.fatal_error("failed to read cached configuration from: %s"
                                 % (self.setup['file']))
                return(1)
        else:
            # retrieve config from server
            try:
                proxy = Bcfg2.Client.Proxy.bcfg2(self.setup)
            except:
                self.fatal_error("failed to instantiate proxy to server")
                return(1)

            if self.setup['profile']:
                try:
                    proxy.AssertProfile(self.setup['profile'])
                except xmlrpclib.Fault:
                    self.fatal_error("Failed to set client profile")
                    return(1)

            try:
                probe_data = proxy.GetProbes()
            except xmlrpclib.Fault, flt:
                self.logger.error("Failed to download probes from bcfg2")
                self.logger.error(flt.faultString)
                raise SystemExit(1)

            times['probe_download'] = time.time()

            try:
                probes = Bcfg2.Client.XML.XML(probe_data)
            except Bcfg2.Client.XML.ParseError, syntax_error:
                self.fatal_error(
                    "server returned invalid probe requests: %s" %
                    (syntax_error))
                return(1)

            # execute probes
            try:
                probedata = Bcfg2.Client.XML.Element("ProbeData")
                [probedata.append(self.run_probe(probe))
                 for probe in probes.findall(".//probe")]
            except:
                self.logger.error("Failed to Execute probes")
                raise SystemExit(1)

            if len(probes.findall(".//probe")) > 0:
                try:
                    # upload probe responses
                    proxy.RecvProbeData(Bcfg2.Client.XML.tostring(probedata))
                except:
                    self.logger.error("Failed to upload probe data", exc_info=1)
                    raise SystemExit(1)

            times['probe_upload'] = time.time()

            try:
                rawconfig = proxy.GetConfig()
            except xmlrpclib.Fault:
                self.logger.error("Failed to download configuration from bcfg2")
                raise SystemExit(2)

            times['config_download'] = time.time()

        if self.setup['cache']:
            try:
                open(self.setup['cache'], 'w').write(rawconfig)
                os.chmod(self.setup['cache'], 33152)
            except IOError:
                self.logger.warning("failed to write config cache file %s" %
                                    (self.setup['cache']))
            times['caching'] = time.time()

        try:
            self.config = Bcfg2.Client.XML.XML(rawconfig)
        except Bcfg2.Client.XML.ParseError, syntax_error:
            self.fatal_error("the configuration could not be parsed: %s" %
                             (syntax_error))
            return(1)            

        times['config_parse'] = time.time()

        if self.config.tag == 'error':
            self.fatal_error("server error: %s" % (self.config.text))
            return(1)

        self.tools = Bcfg2.Client.Frame.Frame(self.config,
                                              self.setup,
                                              times)

        self.tools.Execute()

        if not self.setup['file']:
            # upload statistics
            feedback = self.tools.GenerateStats()

            try:
                proxy.RecvStats(Bcfg2.Client.XML.tostring(feedback))
            except xmlrpclib.Fault:
                self.logger.error("Failed to upload configuration statistics")
                raise SystemExit(2)

class FingerCheck(object):
    def __init__(self, fprint):
        self.fingerprint = fprint
        self.logger = logging.getLogger('checker')

    def __call__(self, connection):
        if connection._client:
            chain = connection.session.serverCertChain
        else:
            chain = connection.session.clientCertChain

        if chain == None:
            self.logger.error("Fingerprint authentication error")
            raise TLSNoAuthenticationError()
        if chain.getFingerprint() != self.fingerprint:
            self.logger.error("Got connection with bad fingerprint %s" \
                              % (chain.getFingerprint()))
            raise TLSFingerprintError(\
                    "X.509 fingerprint mismatch: %s, %s" % \
                    (chain.getFingerprint(), self.fingerprint))

class Agent(Bcfg2.Component.Component):
        """The Bcfg2 Agent component providing XML-RPC access to 'run'"""
        __name__ = 'bcfg2-agent'
        __implementation__ = 'bcfg2-agent'
            
        def __init__(self, client):
            # need to get addr
            self.setup = client.setup
            self.shut = False
            signal.signal(signal.SIGINT, self.start_shutdown)
            signal.signal(signal.SIGTERM, self.start_shutdown)
            self.logger = logging.getLogger('Agent')

            self.static = True
                
            if self.setup["agent-port"]:
                port = int(self.setup["agent-port"])
            elif self.setup["server"]:
                port = int(self.setup["server"].split(':')[1])
            else:
                print "port or server URL not specified"
                raise SystemExit, 1

            location = (socket.gethostname(), port)

            keyfile = self.setup["key"]
            self.password = self.setup["password"]
            
            try:
                TLSServer.__init__(self,
                                   location,
                                   keyfile,
                                   CobaltXMLRPCRequestHandler,
                                   FingerCheck(self.setup["fingerprint"]),
                                   reqCert=True)
            except socket.error:
                self.logger.error("Failed to bind to socket")
                raise ComponentInitError
            except ComponentKeyError:
                self.logger.error("Failed to parse key" % (keyfile))
                raise ComponentInitError
            except:
                self.logger.error("Failed to load ssl key %s" % (keyfile), exc_info=1)
                raise ComponentInitError
            try:
                SimpleXMLRPCServer.SimpleXMLRPCDispatcher.__init__(self)
            except TypeError:
                SimpleXMLRPCServer.SimpleXMLRPCDispatcher.__init__(self, False, None)
            self.logRequests = 0
            self.port = self.socket.getsockname()[1]
            self.url = "https://%s:%s" % (socket.gethostname(), self.port)
            self.logger.info("Bound to port %s" % self.port)
            self.funcs.update({'system.listMethods':self.addr_system_listMethods})
            self.atime = 0
            self.client = client
            self.funcs.update({
                "run": self.run,
                })

        def run(self, address):
            try:
                os.waitpid(-1, os.WNOHANG)
            except:
                pass
            self.logger.info("Got run request from %s" % (address[0]))
            if os.fork():
                return True
            else:
                try:
                    self.client.run()
                except SystemExit:
                    self.logger.error("Client failed to execute")
                self.shut = True
                return False
            
if __name__ == '__main__':
    signal.signal(signal.SIGINT, cb_sigint_handler)
    client = Client()
    spid = os.getpid()
    if client.setup["agent"]:
        agent = Agent(client)
        if client.setup["agent-background"]:
            Bcfg2.Daemon.daemonize(client.setup["agent-background"])
        while not agent.shut:
            try:
                agent.serve_forever()
            except:
                critical_error('error in service loop')
        if os.getpid() == spid:
            print("Shutting down")
    else:
        client.run()