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
237 logger.exception(("the supplied traffic summary destination "
238 "(%s) is not writable" % opts.traffic_summary))
242 if model_file and not opts.generate_users_only:
244 model = traffic.TrafficModel()
247 model.load(model_file)
249 logger.error(("Could not parse %s. The model file "
250 "should be generated by the "
251 "traffic_learner script.") % model_file)
254 logger.info(("Using the specified model file to "
255 "generate conversations"))
257 conversations = model.generate_conversation_sequences(opts.scale_traffic,
261 logger.error(("Could not parse %s, which does not seem to be "
262 "a model generated by script/traffic_learner."
270 for c in traffic.seq_to_conversations(conversations):
272 print(" ", p, file=sys.stderr)
274 print('=' * 72, file=sys.stderr)
276 if opts.number_of_users and opts.number_of_users < len(conversations):
277 logger.error(("--number-of-users (%d) is less than the "
278 "number of conversations to replay (%d)"
279 % (opts.number_of_users, len(conversations))))
282 number_of_users = max(opts.number_of_users, len(conversations))
283 max_memberships = number_of_users * opts.number_of_groups
285 if not opts.group_memberships and opts.average_groups_per_user:
286 opts.group_memberships = opts.average_groups_per_user * number_of_users
287 logger.info(("Using %d group-memberships based on %u average "
288 "memberships for %d users"
289 % (opts.group_memberships,
290 opts.average_groups_per_user, number_of_users)))
292 if opts.group_memberships > max_memberships:
293 logger.error(("The group memberships specified (%d) exceeds "
294 "the total users (%d) * total groups (%d)"
295 % (opts.group_memberships, number_of_users,
296 opts.number_of_groups)))
299 # Get an LDB connection.
301 # if we're only adding users, then it's OK to pass a sam.ldb filepath
302 # as the host, which creates the users much faster. In all other cases
303 # we should be connecting to a remote DC
304 if opts.generate_users_only and os.path.isfile(host):
305 ldb = SamDB(url="ldb://{0}".format(host),
306 session_info=system_session(), lp=lp)
308 ldb = traffic.openLdb(host, creds, lp)
310 logger.error(("\nInitial LDAP connection failed! Did you supply "
311 "a DNS host name and the correct credentials?"))
314 if opts.generate_users_only:
315 # generate computer accounts for added realism. Assume there will be
316 # some overhang with more computer accounts than users
317 computer_accounts = int(1.25 * number_of_users)
318 traffic.generate_users_and_groups(ldb,
321 opts.number_of_users,
322 opts.number_of_groups,
323 opts.group_memberships,
325 machine_accounts=computer_accounts,
326 traffic_accounts=False)
329 tempdir = tempfile.mkdtemp(prefix="samba_tg_")
330 logger.info("Using temp dir %s" % tempdir)
332 traffic.generate_users_and_groups(ldb,
336 opts.number_of_groups,
337 opts.group_memberships,
339 machine_accounts=len(conversations),
340 traffic_accounts=True)
342 accounts = traffic.generate_replay_accounts(ldb,
347 statsdir = traffic.mk_masked_dir(tempdir, 'stats')
349 if opts.traffic_summary:
350 if opts.traffic_summary == '-':
351 summary_dest = sys.stdout
353 summary_dest = open(opts.traffic_summary, 'w')
355 logger.info("Writing traffic summary")
357 for c in traffic.seq_to_conversations(conversations):
358 summaries += c.replay_as_summary_lines()
361 for (time, line) in summaries:
362 print(line, file=summary_dest)
366 traffic.replay(conversations,
371 dns_rate=opts.dns_rate,
372 duration=opts.duration,
373 latency_timeout=opts.latency_timeout,
374 badpassword_frequency=opts.badpassword_frequency,
375 prefer_kerberos=opts.prefer_kerberos,
378 base_dn=ldb.domain_dn(),
379 ou=traffic.ou_name(ldb, opts.instance_id),
381 stop_on_any_error=opts.stop_on_any_error,
382 domain_sid=ldb.get_domain_sid())
384 if opts.timing_data == '-':
385 timing_dest = sys.stdout
386 elif opts.timing_data is None:
389 timing_dest = open(opts.timing_data, 'w')
391 logger.info("Generating statistics")
392 traffic.generate_stats(statsdir, timing_dest)
394 if not opts.preserve_tempdir:
395 logger.info("Removing temporary directory")
396 shutil.rmtree(tempdir)
398 # delete the empty directories anyway. There are thousands of
399 # them and they're EMPTY.
400 for d in os.listdir(tempdir):
401 if d.startswith('conversation-'):
402 path = os.path.join(tempdir, d)
406 logger.info("not removing %s (%s)" % (path, e))