2 # Generates samba network traffic
4 # Copyright (C) Catalyst IT Ltd. 2017
6 # This program is free software; you can redistribute it and/or modify
7 # it under the terms of the GNU General Public License as published by
8 # the Free Software Foundation; either version 3 of the License, or
9 # (at your option) any later version.
11 # This program is distributed in the hope that it will be useful,
12 # but WITHOUT ANY WARRANTY; without even the implied warranty of
13 # MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
14 # GNU General Public License for more details.
16 # You should have received a copy of the GNU General Public License
17 # along with this program. If not, see <http://www.gnu.org/licenses/>.
19 from __future__ import print_function
27 sys.path.insert(0, "bin/python")
29 from samba import gensec, get_debug_level
30 from samba.emulate import traffic
31 import samba.getopt as options
32 from samba.logger import get_samba_logger
33 from samba.samdb import SamDB
34 from samba.auth import system_session
37 def print_err(*args, **kwargs):
38 print(*args, file=sys.stderr, **kwargs)
43 desc = ("Generates network traffic 'conversations' based on a model generated"
44 " by script/traffic_learner. This traffic is sent to <dns-hostname>,"
45 " which is the full DNS hostname of the DC being tested.")
47 parser = optparse.OptionParser(
48 "%prog [--help|options] <model-file> <dns-hostname>",
51 parser.add_option('--dns-rate', type='float', default=0,
52 help='fire extra DNS packets at this rate')
53 parser.add_option('-B', '--badpassword-frequency',
54 type='float', default=0.0,
55 help='frequency of connections with bad passwords')
56 parser.add_option('-K', '--prefer-kerberos',
58 help='prefer kerberos when authenticating test users')
59 parser.add_option('-I', '--instance-id', type='int', default=0,
60 help='Instance number, when running multiple instances')
61 parser.add_option('-t', '--timing-data',
62 help=('write individual message timing data here '
64 parser.add_option('--preserve-tempdir', default=False, action="store_true",
65 help='do not delete temporary files')
66 parser.add_option('-F', '--fixed-password',
67 type='string', default=None,
68 help=('Password used for the test users created. '
70 parser.add_option('-c', '--clean-up',
72 help='Clean up the generated groups and user accounts')
73 parser.add_option('--random-seed', type='int', default=None,
74 help='Use to keep randomness consistent across multiple runs')
75 parser.add_option('--stop-on-any-error',
77 help='abort the whole thing if a child fails')
78 model_group = optparse.OptionGroup(parser, 'Traffic Model Options',
79 'These options alter the traffic '
80 'generated by the model')
81 model_group.add_option('-S', '--scale-traffic', type='float', default=1.0,
82 help='Increase the number of conversations by '
84 model_group.add_option('-D', '--duration', type='float', default=60.0,
85 help=('Run model for this long (approx). '
86 'Default 60s for models'))
87 model_group.add_option('--latency-timeout', type='float', default=None,
88 help=('Wait this long for last packet to finish'))
89 model_group.add_option('-r', '--replay-rate', type='float', default=1.0,
90 help='Replay the traffic faster by this factor')
91 model_group.add_option('--traffic-summary',
92 help=('Generate a traffic summary file and write '
93 'it here (- for stdout)'))
94 parser.add_option_group(model_group)
96 user_gen_group = optparse.OptionGroup(parser, 'Generate User Options',
97 "Add extra user/groups on the DC to "
98 "increase the DB size. These extra "
99 "users aren't used for traffic "
101 user_gen_group.add_option('-G', '--generate-users-only',
103 help='Generate the users, but do not replay '
105 user_gen_group.add_option('-n', '--number-of-users', type='int', default=0,
106 help='Total number of test users to create')
107 user_gen_group.add_option('--number-of-groups', type='int', default=0,
108 help='Create this many groups')
109 user_gen_group.add_option('--average-groups-per-user',
110 type='int', default=0,
111 help='Assign the test users to this '
112 'many groups on average')
113 user_gen_group.add_option('--group-memberships', type='int', default=0,
114 help='Total memberships to assign across all '
115 'test users and all groups')
116 user_gen_group.add_option('--max-members', type='int', default=None,
117 help='Max users to add to any one group')
118 parser.add_option_group(user_gen_group)
120 sambaopts = options.SambaOptions(parser)
121 parser.add_option_group(sambaopts)
122 parser.add_option_group(options.VersionOptions(parser))
123 credopts = options.CredentialsOptions(parser)
124 parser.add_option_group(credopts)
126 # the --no-password credential doesn't make sense for this tool
127 if parser.has_option('-N'):
128 parser.remove_option('-N')
130 opts, args = parser.parse_args()
132 # First ensure we have reasonable arguments
138 model_file, host = args
143 lp = sambaopts.get_loadparm()
144 debuglevel = get_debug_level()
145 logger = get_samba_logger(name=__name__,
146 verbose=debuglevel > 3,
147 quiet=debuglevel < 1)
149 traffic.DEBUG_LEVEL = debuglevel
150 # pass log level down to traffic module to make sure level is controlled
151 traffic.LOGGER.setLevel(logger.getEffectiveLevel())
154 logger.info("Removing user and machine accounts")
155 lp = sambaopts.get_loadparm()
156 creds = credopts.get_credentials(lp)
157 creds.set_gensec_features(creds.get_gensec_features() | gensec.FEATURE_SEAL)
158 ldb = traffic.openLdb(host, creds, lp)
159 traffic.clean_up_accounts(ldb, opts.instance_id)
163 if not os.path.exists(model_file):
164 logger.error("Model file %s doesn't exist" % model_file)
166 # the model-file can be ommitted for --generate-users-only and
167 # --cleanup-up, but it should be specified in all other cases
168 elif not opts.generate_users_only:
169 logger.error("No model file specified to replay traffic from")
172 if not opts.fixed_password:
173 logger.error(("Please use --fixed-password to specify a password"
174 " for the users created as part of this test"))
177 if opts.random_seed is not None:
178 random.seed(opts.random_seed)
180 creds = credopts.get_credentials(lp)
181 creds.set_gensec_features(creds.get_gensec_features() | gensec.FEATURE_SEAL)
183 domain = creds.get_domain()
185 lp.set("workgroup", domain)
187 domain = lp.get("workgroup")
188 if domain == "WORKGROUP":
189 logger.error(("NETBIOS domain does not appear to be "
190 "specified, use the --workgroup option"))
193 if not opts.realm and not lp.get('realm'):
194 logger.error("Realm not specified, use the --realm option")
197 if opts.generate_users_only and not (opts.number_of_users or
198 opts.number_of_groups):
199 logger.error(("Please specify the number of users and/or groups "
203 if opts.group_memberships and opts.average_groups_per_user:
204 logger.error(("--group-memberships and --average-groups-per-user"
205 " are incompatible options - use one or the other"))
208 if not opts.number_of_groups and opts.average_groups_per_user:
209 logger.error(("--average-groups-per-user requires "
210 "--number-of-groups"))
213 if opts.number_of_groups and opts.average_groups_per_user:
214 if opts.number_of_groups < opts.average_groups_per_user:
215 logger.error(("--average-groups-per-user can not be more than "
216 "--number-of-groups"))
219 if not opts.number_of_groups and opts.group_memberships:
220 logger.error("--group-memberships requires --number-of-groups")
223 if opts.timing_data not in ('-', None):
225 open(opts.timing_data, 'w').close()
227 # exception info will be added to log automatically
228 logger.exception(("the supplied timing data destination "
229 "(%s) is not writable" % opts.timing_data))
232 if opts.traffic_summary not in ('-', None):
234 open(opts.traffic_summary, 'w').close()
236 # exception info will be added to log automatically
239 traceback.print_exc()
240 logger.exception(("the supplied traffic summary destination "
241 "(%s) is not writable" % opts.traffic_summary))
245 if model_file and not opts.generate_users_only:
246 model = traffic.TrafficModel()
248 model.load(model_file)
252 traceback.print_exc()
253 logger.error(("Could not parse %s, which does not seem to be "
254 "a model generated by script/traffic_learner."
258 logger.info(("Using the specified model file to "
259 "generate conversations"))
262 model.generate_conversation_sequences(
269 if opts.number_of_users and opts.number_of_users < len(conversations):
270 logger.error(("--number-of-users (%d) is less than the "
271 "number of conversations to replay (%d)"
272 % (opts.number_of_users, len(conversations))))
275 number_of_users = max(opts.number_of_users, len(conversations))
276 max_memberships = number_of_users * opts.number_of_groups
278 if not opts.group_memberships and opts.average_groups_per_user:
279 opts.group_memberships = opts.average_groups_per_user * number_of_users
280 logger.info(("Using %d group-memberships based on %u average "
281 "memberships for %d users"
282 % (opts.group_memberships,
283 opts.average_groups_per_user, number_of_users)))
285 if opts.group_memberships > max_memberships:
286 logger.error(("The group memberships specified (%d) exceeds "
287 "the total users (%d) * total groups (%d)"
288 % (opts.group_memberships, number_of_users,
289 opts.number_of_groups)))
292 # Get an LDB connection.
294 # if we're only adding users, then it's OK to pass a sam.ldb filepath
295 # as the host, which creates the users much faster. In all other cases
296 # we should be connecting to a remote DC
297 if opts.generate_users_only and os.path.isfile(host):
298 ldb = SamDB(url="ldb://{0}".format(host),
299 session_info=system_session(), lp=lp)
301 ldb = traffic.openLdb(host, creds, lp)
303 logger.error(("\nInitial LDAP connection failed! Did you supply "
304 "a DNS host name and the correct credentials?"))
307 if opts.generate_users_only:
308 # generate computer accounts for added realism. Assume there will be
309 # some overhang with more computer accounts than users
310 computer_accounts = int(1.25 * number_of_users)
311 traffic.generate_users_and_groups(ldb,
314 opts.number_of_users,
315 opts.number_of_groups,
316 opts.group_memberships,
318 machine_accounts=computer_accounts,
319 traffic_accounts=False)
322 tempdir = tempfile.mkdtemp(prefix="samba_tg_")
323 logger.info("Using temp dir %s" % tempdir)
325 traffic.generate_users_and_groups(ldb,
329 opts.number_of_groups,
330 opts.group_memberships,
332 machine_accounts=len(conversations),
333 traffic_accounts=True)
335 accounts = traffic.generate_replay_accounts(ldb,
340 statsdir = traffic.mk_masked_dir(tempdir, 'stats')
342 if opts.traffic_summary:
343 if opts.traffic_summary == '-':
344 summary_dest = sys.stdout
346 summary_dest = open(opts.traffic_summary, 'w')
348 logger.info("Writing traffic summary")
350 for c in traffic.seq_to_conversations(conversations):
351 summaries += c.replay_as_summary_lines()
354 for (time, line) in summaries:
355 print(line, file=summary_dest)
359 traffic.replay(conversations,
364 dns_rate=opts.dns_rate,
365 duration=opts.duration,
366 latency_timeout=opts.latency_timeout,
367 badpassword_frequency=opts.badpassword_frequency,
368 prefer_kerberos=opts.prefer_kerberos,
371 base_dn=ldb.domain_dn(),
372 ou=traffic.ou_name(ldb, opts.instance_id),
374 stop_on_any_error=opts.stop_on_any_error,
375 domain_sid=ldb.get_domain_sid())
377 if opts.timing_data == '-':
378 timing_dest = sys.stdout
379 elif opts.timing_data is None:
382 timing_dest = open(opts.timing_data, 'w')
384 logger.info("Generating statistics")
385 traffic.generate_stats(statsdir, timing_dest)
387 if not opts.preserve_tempdir:
388 logger.info("Removing temporary directory")
389 shutil.rmtree(tempdir)
391 # delete the empty directories anyway. There are thousands of
392 # them and they're EMPTY.
393 for d in os.listdir(tempdir):
394 if d.startswith('conversation-'):
395 path = os.path.join(tempdir, d)
399 logger.info("not removing %s (%s)" % (path, e))