samba-tool/testparm: Fix traceback when checking client name/ip against hosts allowed.
[mat/samba.git] / source4 / scripting / python / samba / netcmd / testparm.py
1 #!/usr/bin/env python
2 # vim: expandtab ft=python
3 #
4 #   Unix SMB/CIFS implementation.
5 #   Test validity of smb.conf
6 #   Copyright (C) 2010-2011 Jelmer Vernooij <jelmer@samba.org>
7 #   Copyright (C) Giampaolo Lauria 2011 <lauria2@yahoo.com>
8 #
9 # Based on the original in C:
10 #   Copyright (C) Karl Auer 1993, 1994-1998
11 #   Extensively modified by Andrew Tridgell, 1995
12 #   Converted to popt by Jelmer Vernooij (jelmer@nl.linux.org), 2002
13 #   Updated for Samba4 by Andrew Bartlett <abartlet@samba.org> 2006
14 #
15 # This program is free software; you can redistribute it and/or modify
16 # it under the terms of the GNU General Public License as published by
17 # the Free Software Foundation; either version 3 of the License, or
18 # (at your option) any later version.
19 #
20 # This program is distributed in the hope that it will be useful,
21 # but WITHOUT ANY WARRANTY; without even the implied warranty of
22 # MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE.  See the
23 # GNU General Public License for more details.
24 #
25 # You should have received a copy of the GNU General Public License
26 # along with this program.  If not, see <http://www.gnu.org/licenses/>.
27 #
28 # Testbed for loadparm.c/params.c
29 #
30 # This module simply loads a specified configuration file and
31 # if successful, dumps it's contents to stdout. Note that the
32 # operation is performed with DEBUGLEVEL at 3.
33 #
34 # Useful for a quick 'syntax check' of a configuration file.
35 #
36
37 import os
38 import sys
39 import logging
40
41 import samba
42 import samba.getopt as options
43 from samba.netcmd import Command, CommandError, Option
44
45 class cmd_testparm(Command):
46     """Syntax check the configuration file"""
47
48     synopsis = "%prog testparm [options]"
49
50     takes_optiongroups = {
51         "sambaopts" : options.SambaOptions,
52         "versionopts": options.VersionOptions
53     }
54
55     takes_options = [
56         Option("--section-name", type=str,
57                help="Limit testparm to a named section"),
58         Option("--parameter-name", type=str,
59                help="Limit testparm to a named parameter"),
60         Option("--client-name", type=str,
61                help="Client DNS name for 'hosts allow' checking "
62                     "(should match reverse lookup)"),
63         Option("--client-ip", type=str,
64                help="Client IP address for 'hosts allow' checking"),
65         Option("--suppress-prompt", action="store_true", default=False,
66                help="Suppress prompt for enter"),
67         Option("-v", "--verbose", action="store_true",
68                default=False, help="Show default options too"),
69         # We need support for smb.conf macros before this will work again
70         Option("--server", type=str, help="Set %%L macro to servername"),
71         # These are harder to do with the new code structure
72         Option("--show-all-parameters", action="store_true", default=False,
73                help="Show the parameters, type, possible values")
74         ]
75
76     takes_args = []
77
78     def run(self, sambaopts, versionopts, 
79             section_name=None, parameter_name=None,
80             client_ip=None, client_name=None, verbose=False,
81             suppress_prompt=None,
82             show_all_parameters=False, server=None):
83         if server:
84             raise NotImplementedError("--server not yet implemented")
85         if show_all_parameters:
86             raise NotImplementedError("--show-all-parameters not yet implemented")
87         if client_name is not None and client_ip is None:
88             raise CommandError("Both a DNS name and an IP address are "
89                                "required for the host access check")
90
91         lp = sambaopts.get_loadparm()
92
93         # We need this to force the output
94         samba.set_debug_level(2)
95
96         logger = logging.getLogger("testparm")
97         logger.addHandler(logging.StreamHandler(sys.stdout))
98
99         logger.info("Loaded smb config files from %s", lp.configfile)
100         logger.info("Loaded services file OK.")
101
102         valid = self.do_global_checks(lp, logger)
103         valid = valid and self.do_share_checks(lp, logger)
104         if client_name is not None and client_ip is not None:
105             self.check_client_access(lp, logger, client_name, client_ip)
106         else:
107             if section_name is not None or parameter_name is not None:
108                 if parameter_name is None:
109                     lp[section_name].dump(sys.stdout, lp.default_service, verbose)
110                 else:
111                     print lp.get(parameter_name, section_name)
112             else:
113                 if not suppress_prompt:
114                     print "Press enter to see a dump of your service definitions"
115                     sys.stdin.readline()
116                 lp.dump(sys.stdout, verbose)
117         if valid:
118             return
119         else:
120             raise CommandError("Invalid smb.conf")
121
122     def do_global_checks(self, lp, logger):
123         valid = True
124
125         netbios_name = lp.get("netbios name")
126         if not samba.valid_netbios_name(netbios_name):
127             logger.error("netbios name %s is not a valid netbios name",
128                          netbios_name)
129             valid = False
130
131         workgroup = lp.get("workgroup")
132         if not samba.valid_netbios_name(workgroup):
133             logger.error("workgroup name %s is not a valid netbios name",
134                          workgroup)
135             valid = False
136
137         lockdir = lp.get("lockdir")
138
139         if not os.path.isdir(lockdir):
140             logger.error("lock directory %s does not exist", lockdir)
141             valid = False
142
143         piddir = lp.get("pid directory")
144
145         if not os.path.isdir(piddir):
146             logger.error("pid directory %s does not exist", piddir)
147             valid = False
148
149         winbind_separator = lp.get("winbind separator")
150
151         if len(winbind_separator) != 1:
152             logger.error("the 'winbind separator' parameter must be a single "
153                          "character.")
154             valid = False
155
156         if winbind_separator == '+':
157             logger.error("'winbind separator = +' might cause problems with group "
158                          "membership.")
159             valid = False
160
161         return valid
162
163     def allow_access(self, deny_list, allow_list, cname, caddr):
164         raise NotImplementedError(self.allow_access)
165
166     def do_share_checks(self, lp, logger):
167         valid = True
168         for s in lp.services():
169             if len(s) > 12:
170                 logger.warning("You have some share names that are longer than 12 "
171                     "characters. These may not be accessible to some older "
172                     "clients. (Eg. Windows9x, WindowsMe, and not listed in "
173                     "smbclient in Samba 3.0.)")
174                 break
175
176         for s in lp.services():
177             deny_list = lp.get("hosts deny", s)
178             allow_list = lp.get("hosts allow", s)
179             if deny_list:
180                 for entry in deny_list:
181                     if "*" in entry or "?" in entry:
182                         logger.error("Invalid character (* or ?) in hosts deny "
183                                      "list (%s) for service %s.", entry, s)
184                         valid = False
185
186             if allow_list:
187                 for entry in allow_list:
188                     if "*" in entry or "?" in entry:
189                         logger.error("Invalid character (* or ?) in hosts allow "
190                                      "list (%s) for service %s.", entry, s)
191                         valid = False
192         return valid
193
194     def check_client_access(self, lp, logger, cname, caddr):
195         # this is totally ugly, a real `quick' hack
196         for s in lp.services():
197             if (self.allow_access(lp.get("hosts deny"), lp.get("hosts allow"), cname,
198                              caddr) and
199                 self.allow_access(lp.get("hosts deny", s), lp.get("hosts allow", s),
200                              cname, caddr)):
201                 logger.info("Allow connection from %s (%s) to %s", cname, caddr, s)
202             else:
203                 logger.info("Deny connection from %s (%s) to %s", cname, caddr, s)
204
205 ##   FIXME: We need support for smb.conf macros before this will work again
206 ##
207 ##    if (new_local_machine) {
208 ##        set_local_machine_name(new_local_machine, True)
209 ##    }
210 #