aboutsummaryrefslogtreecommitdiffstats
path: root/phpBB/phpbb/db/driver/postgres.php
blob: 44476612c36ceff92da76e2866db36fb4418e745 (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
399
400
401
402
403
404
405
406
407
408
409
410
411
412
413
414
415
416
417
418
419
420
421
422
423
424
425
426
427
428
429
430
431
432
433
434
435
436
437
438
439
440
441
442
443
444
445
446
447
448
449
450
451
452
453
454
455
456
457
458
459
460
461
462
463
464
465
466
467
468
469
470
471
472
473
474
475
476
477
478
479
480
481
482
483
484
485
486
487
488
489
490
491
492
493
494
495
496
497
498
499
500
501
<?php
/**
*
* This file is part of the phpBB Forum Software package.
*
* @copyright (c) phpBB Limited <https://www.phpbb.com>
* @license GNU General Public License, version 2 (GPL-2.0)
*
* For full copyright and license information, please see
* the docs/CREDITS.txt file.
*
*/

namespace phpbb\db\driver;

/**
* PostgreSQL Database Abstraction Layer
* Minimum Requirement is Version 8.3+
*/
class postgres extends \phpbb\db\driver\driver
{
	var $multi_insert = true;
	var $last_query_text = '';
	var $connect_error = '';

	/**
	* {@inheritDoc}
	*/
	function sql_connect($sqlserver, $sqluser, $sqlpassword, $database, $port = false, $persistency = false, $new_link = false)
	{
		$connect_string = '';

		if ($sqluser)
		{
			$connect_string .= "user=$sqluser ";
		}

		if ($sqlpassword)
		{
			$connect_string .= "password=$sqlpassword ";
		}

		if ($sqlserver)
		{
			// $sqlserver can carry a port separated by : for compatibility reasons
			// If $sqlserver has more than one : it's probably an IPv6 address.
			// In this case we only allow passing a port via the $port variable.
			if (substr_count($sqlserver, ':') === 1)
			{
				list($sqlserver, $port) = explode(':', $sqlserver);
			}

			if ($sqlserver !== 'localhost')
			{
				$connect_string .= "host=$sqlserver ";
			}

			if ($port)
			{
				$connect_string .= "port=$port ";
			}
		}

		$schema = '';

		if ($database)
		{
			$this->dbname = $database;
			if (strpos($database, '.') !== false)
			{
				list($database, $schema) = explode('.', $database);
			}
			$connect_string .= "dbname=$database";
		}

		$this->persistency = $persistency;

		if ($this->persistency)
		{
			if (!function_exists('pg_pconnect'))
			{
				$this->connect_error = 'pg_pconnect function does not exist, is pgsql extension installed?';
				return $this->sql_error('');
			}
			$collector = new \phpbb\error_collector;
			$collector->install();
			$this->db_connect_id = (!$new_link) ? @pg_pconnect($connect_string) : @pg_pconnect($connect_string, PGSQL_CONNECT_FORCE_NEW);
		}
		else
		{
			if (!function_exists('pg_connect'))
			{
				$this->connect_error = 'pg_connect function does not exist, is pgsql extension installed?';
				return $this->sql_error('');
			}
			$collector = new \phpbb\error_collector;
			$collector->install();
			$this->db_connect_id = (!$new_link) ? @pg_connect($connect_string) : @pg_connect($connect_string, PGSQL_CONNECT_FORCE_NEW);
		}

		$collector->uninstall();

		if ($this->db_connect_id)
		{
			if ($schema !== '')
			{
				@pg_query($this->db_connect_id, 'SET search_path TO ' . $schema);
			}
			return $this->db_connect_id;
		}

		$this->connect_error = $collector->format_errors();
		return $this->sql_error('');
	}

	/**
	* {@inheritDoc}
	*/
	function sql_server_info($raw = false, $use_cache = true)
	{
		global $cache;

		if (!$use_cache || empty($cache) || ($this->sql_server_version = $cache->get('pgsql_version')) === false)
		{
			$query_id = @pg_query($this->db_connect_id, 'SELECT VERSION() AS version');
			if ($query_id)
			{
				$row = pg_fetch_assoc($query_id, null);
				pg_free_result($query_id);

				$this->sql_server_version = (!empty($row['version'])) ? trim(substr($row['version'], 10)) : 0;

				if (!empty($cache) && $use_cache)
				{
					$cache->put('pgsql_version', $this->sql_server_version);
				}
			}
		}

		return ($raw) ? $this->sql_server_version : 'PostgreSQL ' . $this->sql_server_version;
	}

	/**
	* SQL Transaction
	* @access private
	*/
	function _sql_transaction($status = 'begin')
	{
		switch ($status)
		{
			case 'begin':
				return @pg_query($this->db_connect_id, 'BEGIN');
			break;

			case 'commit':
				return @pg_query($this->db_connect_id, 'COMMIT');
			break;

			case 'rollback':
				return @pg_query($this->db_connect_id, 'ROLLBACK');
			break;
		}

		return true;
	}

	/**
	* {@inheritDoc}
	*/
	function sql_query($query = '', $cache_ttl = 0)
	{
		if ($query != '')
		{
			global $cache;

			// EXPLAIN only in extra debug mode
			if (defined('DEBUG'))
			{
				$this->sql_report('start', $query);
			}
			else if (defined('PHPBB_DISPLAY_LOAD_TIME'))
			{
				$this->curtime = microtime(true);
			}

			$this->last_query_text = $query;
			$this->query_result = ($cache && $cache_ttl) ? $cache->sql_load($query) : false;
			$this->sql_add_num_queries($this->query_result);

			if ($this->query_result === false)
			{
				if (($this->query_result = @pg_query($this->db_connect_id, $query)) === false)
				{
					$this->sql_error($query);
				}

				if (defined('DEBUG'))
				{
					$this->sql_report('stop', $query);
				}
				else if (defined('PHPBB_DISPLAY_LOAD_TIME'))
				{
					$this->sql_time += microtime(true) - $this->curtime;
				}

				if (!$this->query_result)
				{
					return false;
				}

				if ($cache && $cache_ttl)
				{
					$this->open_queries[(int) $this->query_result] = $this->query_result;
					$this->query_result = $cache->sql_save($this, $query, $this->query_result, $cache_ttl);
				}
				else if (strpos($query, 'SELECT') === 0)
				{
					$this->open_queries[(int) $this->query_result] = $this->query_result;
				}
			}
			else if (defined('DEBUG'))
			{
				$this->sql_report('fromcache', $query);
			}
		}
		else
		{
			return false;
		}

		return $this->query_result;
	}

	/**
	* Build db-specific query data
	* @access private
	*/
	function _sql_custom_build($stage, $data)
	{
		return $data;
	}

	/**
	* Build LIMIT query
	*/
	function _sql_query_limit($query, $total, $offset = 0, $cache_ttl = 0)
	{
		$this->query_result = false;

		// if $total is set to 0 we do not want to limit the number of rows
		if ($total == 0)
		{
			$total = 'ALL';
		}

		$query .= "\n LIMIT $total OFFSET $offset";

		return $this->sql_query($query, $cache_ttl);
	}

	/**
	* {@inheritDoc}
	*/
	function sql_affectedrows()
	{
		return ($this->query_result) ? @pg_affected_rows($this->query_result) : false;
	}

	/**
	* {@inheritDoc}
	*/
	function sql_fetchrow($query_id = false)
	{
		global $cache;

		if ($query_id === false)
		{
			$query_id = $this->query_result;
		}

		if ($cache && $cache->sql_exists($query_id))
		{
			return $cache->sql_fetchrow($query_id);
		}

		return ($query_id) ? pg_fetch_assoc($query_id, null) : false;
	}

	/**
	* {@inheritDoc}
	*/
	function sql_rowseek($rownum, &$query_id)
	{
		global $cache;

		if ($query_id === false)
		{
			$query_id = $this->query_result;
		}

		if ($cache && $cache->sql_exists($query_id))
		{
			return $cache->sql_rowseek($rownum, $query_id);
		}

		return ($query_id) ? @pg_result_seek($query_id, $rownum) : false;
	}

	/**
	* {@inheritDoc}
	*/
	function sql_nextid()
	{
		$query_id = $this->query_result;

		if ($query_id !== false && $this->last_query_text != '')
		{
			if (preg_match("/^INSERT[\t\n ]+INTO[\t\n ]+([a-z0-9\_\-]+)/is", $this->last_query_text, $tablename))
			{
				$query = "SELECT currval('" . $tablename[1] . "_seq') AS last_value";
				$temp_q_id = @pg_query($this->db_connect_id, $query);

				if (!$temp_q_id)
				{
					return false;
				}

				$temp_result = pg_fetch_assoc($temp_q_id, null);
				pg_free_result($query_id);

				return ($temp_result) ? $temp_result['last_value'] : false;
			}
		}

		return false;
	}

	/**
	* {@inheritDoc}
	*/
	function sql_freeresult($query_id = false)
	{
		global $cache;

		if ($query_id === false)
		{
			$query_id = $this->query_result;
		}

		if ($cache && !is_object($query_id) && $cache->sql_exists($query_id))
		{
			return $cache->sql_freeresult($query_id);
		}

		if (isset($this->open_queries[(int) $query_id]))
		{
			unset($this->open_queries[(int) $query_id]);
			return pg_free_result($query_id);
		}

		return false;
	}

	/**
	* {@inheritDoc}
	*/
	function sql_escape($msg)
	{
		return @pg_escape_string($msg);
	}

	/**
	* Build LIKE expression
	* @access private
	*/
	function _sql_like_expression($expression)
	{
		return $expression;
	}

	/**
	* Build NOT LIKE expression
	* @access private
	*/
	function _sql_not_like_expression($expression)
	{
		return $expression;
	}

	/**
	* {@inheritDoc}
	*/
	function cast_expr_to_bigint($expression)
	{
		return 'CAST(' . $expression . ' as DECIMAL(255, 0))';
	}

	/**
	* {@inheritDoc}
	*/
	function cast_expr_to_string($expression)
	{
		return 'CAST(' . $expression . ' as VARCHAR(255))';
	}

	/**
	* return sql error array
	* @access private
	*/
	function _sql_error()
	{
		// pg_last_error only works when there is an established connection.
		// Connection errors have to be tracked by us manually.
		if ($this->db_connect_id)
		{
			$message = @pg_last_error($this->db_connect_id);
		}
		else
		{
			$message = $this->connect_error;
		}

		return array(
			'message'	=> $message,
			'code'		=> ''
		);
	}

	/**
	* Close sql connection
	* @access private
	*/
	function _sql_close()
	{
		return @pg_close($this->db_connect_id);
	}

	/**
	* Build db-specific report
	* @access private
	*/
	function _sql_report($mode, $query = '')
	{
		switch ($mode)
		{
			case 'start':

				$explain_query = $query;
				if (preg_match('/UPDATE ([a-z0-9_]+).*?WHERE(.*)/s', $query, $m))
				{
					$explain_query = 'SELECT * FROM ' . $m[1] . ' WHERE ' . $m[2];
				}
				else if (preg_match('/DELETE FROM ([a-z0-9_]+).*?WHERE(.*)/s', $query, $m))
				{
					$explain_query = 'SELECT * FROM ' . $m[1] . ' WHERE ' . $m[2];
				}

				if (preg_match('/^SELECT/', $explain_query))
				{
					$html_table = false;

					if ($result = @pg_query($this->db_connect_id, "EXPLAIN $explain_query"))
					{
						while ($row = pg_fetch_assoc($result, null))
						{
							$html_table = $this->sql_report('add_select_row', $query, $html_table, $row);
						}
						pg_free_result($result);
					}

					if ($html_table)
					{
						$this->html_hold .= '</table>';
					}
				}

			break;

			case 'fromcache':
				$endtime = explode(' ', microtime());
				$endtime = $endtime[0] + $endtime[1];

				$result = @pg_query($this->db_connect_id, $query);
				if ($result)
				{
					while ($void = pg_fetch_assoc($result, null))
					{
						// Take the time spent on parsing rows into account
					}
					pg_free_result($result);
				}

				$splittime = explode(' ', microtime());
				$splittime = $splittime[0] + $splittime[1];

				$this->sql_report('record_fromcache', $query, $endtime, $splittime);

			break;
		}
	}
}
t; 1 }, { label => N("Password (again)"), val => \$superuser->{password2}, hidden => 1 }, { label => N("Authentication"), val => \$kind, type => 'list', list => \@kinds, format => \&kind2name, advanced => 1 }, ]) or delete $superuser->{password}; ask_parameters($in, $net, $authentication, $kind) or goto &ask_root_password_and_authentication; } sub check_given_password { my ($in, $u, $min_length) = @_; if ($u->{password} ne $u->{password2}) { $in->ask_warn('', [ N("The passwords do not match"), N("Please try again") ]); 0; } elsif (length $u->{password} < $min_length) { $in->ask_warn('', N("This password is too short (it must be at least %d characters long)", $min_length)); 0; } else { 1; } } sub get() { my $system_auth = cat_("/etc/pam.d/system-auth"); my $authentication = { md5 => $system_auth =~ /md5/, shadow => $system_auth =~ /shadow/, }; my @pam_kinds = get_pam_authentication_kinds(); if (my $kind = find { intersection(\@pam_kinds, $kind2pam_kind{$_}) } keys %kind2pam_kind) { $authentication->{$kind} = ''; } else { #- we can't use pam to detect NIS if (my $yp_conf = read_yp_conf()) { $authentication->{NIS} = 1; map_each { $authentication->{"NIS_$::a"} = $::b } %$yp_conf; } } $authentication; } sub install_needed_packages { my ($do_pkgs, $kind) = @_; if (my $pkgs = $kind2packages{$kind}) { #- automatic during install $do_pkgs->ensure_are_installed($pkgs, $::isInstall) or return; } else { log::l("ERROR: $kind not listed in kind2packages"); } 1; } sub set { my ($in, $net, $authentication, $o_when_network_is_up) = @_; install_needed_packages($in->do_pkgs, to_kind($authentication)) or return; set_raw($net, $authentication, $o_when_network_is_up); } sub set_raw { my ($net, $authentication, $o_when_network_is_up) = @_; my $when_network_is_up = $o_when_network_is_up || sub { my ($f) = @_; $f->() }; enable_shadow() if $authentication->{shadow}; my $kind = to_kind($authentication); log::l("authentication::set $kind"); my $pam_modules = $kind2pam_kind{$kind} or log::l("kind2pam_kind does not know $kind"); $pam_modules ||= []; sshd_config_UsePAM(@$pam_modules > 0); set_pam_authentication(@$pam_modules); my $nsswitch = $kind2nsswitch{$kind} or log::l("kind2nsswitch does not know $kind"); $nsswitch ||= []; set_nsswitch_priority(@$nsswitch); if ($kind eq 'local') { } elsif ($kind eq 'SmartCard') { } elsif ($kind eq 'LDAP') { my $domain = $authentication->{LDAPDOMAIN} || do { my $s = run_program::rooted_get_stdout($::prefix, 'ldapsearch', '-x', '-h', $authentication->{LDAP_server}, '-b', '', '-s', 'base', '+'); first($s =~ /namingContexts: (.+)/); } or log::l("no ldap domain found on server $authentication->{LDAP_server}"), return; update_ldap_conf( host => $authentication->{LDAP_server}, base => $domain, nss_base_shadow => $domain . "?sub", nss_base_passwd => $domain . "?sub", nss_base_group => $domain . "?sub", ); } elsif ($kind eq 'AD') { my $port = "389"; my $ssl = { anonymous => 'off', simple => 'off', tls => 'start_tls', ssl => 'on', kerberos => 'off', }->{$authentication->{sub_kind}}; if ($ssl eq 'on') { $port = '636'; } update_ldap_conf( host => $authentication->{AD_server}, base => domain_to_ldap_domain($authentication->{AD_domain}), nss_base_shadow => "$authentication->{AD_users_db}?sub", nss_base_passwd => "$authentication->{AD_users_db}?sub", nss_base_group => "$authentication->{AD_users_db}?sub", ssl => $ssl, sasl_mech => $authentication->{sub_kind} eq 'kerberos' ? 'GSSAPI' : '', port => $port, binddn => $authentication->{AD_user}, bindpw => $authentication->{AD_password}, (map_each { "nss_map_objectclass_$::a" => $::b } posixAccount => 'User', shadowAccount => 'User', posixGroup => 'Group', ), scope => 'sub', pam_login_attribute => 'sAMAccountName', pam_filter => 'objectclass=User', pam_password => 'ad', (map_each { "nss_map_attribute_$::a" => $::b } uid => 'sAMAccountName', uidNumber => 'msSFU30UidNumber', gidNumber => 'msSFU30GidNumber', cn => 'sAMAccountName', uniqueMember => 'member', userPassword => 'msSFU30Password', homeDirectory => 'msSFU30HomeDirectory', loginShell => 'msSFU30LoginShell', gecos => 'name', ), ); configure_krb5_for_AD($authentication); } elsif ($kind eq 'NIS') { my $domain = $net->{network}{NISDOMAIN}; my $NIS_server = $authentication->{NIS_server}; $domain || $NIS_server ne "broadcast" or die N("Can not use broadcast with no NIS domain"); my $t = $domain ? ($NIS_server eq 'broadcast' ? "domain $domain broadcast" : "domain $domain server $NIS_server") : "server $NIS_server"; substInFile { if (/^#/) { $_ = '' if /^#\Q[PREVIOUS]/; } else { $_ = "#[PREVIOUS] $_"; } $_ .= "$t\n" if eof; } "$::prefix/etc/yp.conf"; #- no need to modify system-auth for nis $when_network_is_up->(sub { run_program::rooted($::prefix, 'nisdomainname', $domain); run_program::rooted($::prefix, 'service', 'ypbind', 'restart'); }); # } elsif ($kind eq 'winbind' || $kind eq 'AD' && $authentication->{subkind} eq 'winbind') { } elsif ($kind eq 'winbind') { my $domain = uc $authentication->{WINDOMAIN}; require fs::remote::smb; fs::remote::smb::write_smb_conf($domain); run_program::rooted($::prefix, "chkconfig", "--level", "35", "winbind", "on"); mkdir_p("$::prefix/home/$domain"); run_program::rooted($::prefix, 'service', 'smb', 'restart'); run_program::rooted($::prefix, 'service', 'winbind', 'restart'); #- defer running smbpassword until the network is up $when_network_is_up->(sub { run_program::raw({ root => $::prefix, sensitive_arguments => 1 }, 'net', 'join', $domain, '-U', $authentication->{winuser} . '%' . $authentication->{winpass}); }); } elsif ($kind eq 'SMBKRB') { $authentication->{AD_server} ||= 'ads.' . $authentication->{AD_domain}; my $domain = uc $authentication->{WINDOMAIN}; my $realm = $authentication->{AD_domain}; configure_krb5_for_AD($authentication); require fs::remote::smb; fs::remote::smb::write_smb_ads_conf($domain,$realm); run_program::rooted($::prefix, "chkconfig", "--level", "35", "winbind", "on"); mkdir_p("$::prefix/home/$domain"); run_program::rooted($::prefix, 'net', 'time', 'set', '-S', $authentication->{AD_server}); run_program::rooted($::prefix, 'service', 'smb', 'restart'); run_program::rooted($::prefix, 'service', 'winbind', 'restart'); $when_network_is_up->(sub { run_program::raw({ root => $::prefix, sensitive_arguments => 1 }, 'net', 'ads', 'join', '-U', $authentication->{winuser} . '%' . $authentication->{winpass}); }); } 1; } sub pam_modules() { 'pam_ldap', 'pam_castella', 'pam_winbind', 'pam_krb5', 'pam_mkhomedir'; } sub pam_module_from_path { $_[0] && $_[0] =~ m|(/lib/security/)?(pam_.*)\.so| && $2; } sub pam_module_to_path { "$_[0].so"; } sub pam_format_line { my ($type, $control, $module, @para) = @_; sprintf("%-11s %-13s %s\n", $type, $control, join(' ', pam_module_to_path($module), @para)); } sub get_raw_pam_authentication() { my %before_deny; foreach (cat_("$::prefix/etc/pam.d/system-auth")) { my ($type, $control, $module, @para) = split; if ($module = pam_module_from_path($module)) { $before_deny{$type}{$module} = \@para if $control eq 'sufficient' && member($module, pam_modules()); } } \%before_deny; } sub get_pam_authentication_kinds() { my $before_deny = get_raw_pam_authentication(); map { s/pam_//; $_ } keys %{$before_deny->{auth}}; } sub set_pam_authentication { my (@authentication_kinds) = @_; my %special = ( auth => [ difference2(\@authentication_kinds,, [ 'mount' ]) ], account => [ difference2(\@authentication_kinds, [ 'castella', 'mount' ]) ], password => [ intersection(\@authentication_kinds, [ 'ldap', 'krb5' ]) ], ); my %before_first = ( auth => member('mount', @authentication_kinds) ? pam_format_line('auth', 'required', 'pam_mount') : '', session => intersection(\@authentication_kinds, [ 'winbind', 'krb5', 'ldap' ]) ? pam_format_line('session', 'optional', 'pam_mkhomedir', 'skel=/etc/skel/', 'umask=0022') : member('castella', @authentication_kinds) ? pam_format_line('session', 'optional', 'pam_castella') : '', ); my %after_deny = ( session => member('krb5', @authentication_kinds) ? pam_format_line('session', 'optional', 'pam_krb5') : member('mount', @authentication_kinds) ? pam_format_line('session', 'optional', 'pam_mount') : '', ); substInFile { my ($type, $control, $module, @para) = split; if ($module = pam_module_from_path($module)) { if (member($module, pam_modules())) { #- first removing previous config $_ = ''; } if ($module eq 'pam_unix' && $special{$type}) { my @para_for_last = member($type, 'auth', 'account') ? qw(use_first_pass) : @{[]}; @para = difference2(\@para, \@para_for_last); my ($before_noask, $ask) = partition { $_ eq 'castella' } @{$special{$type}}; my ($before, $after) = partition { $_ eq 'krb5' } @$ask; if (!@$ask) { @para_for_last = grep { $_ ne 'use_first_pass' } @para_for_last; } my @l = ((map { [ "pam_$_" ] } @$before_noask, @$before), [ 'pam_unix', @para ], (map { [ "pam_$_" ] } @$after), ); push @{$l[-1]}, @para_for_last; $_ = join('', map { pam_format_line($type, 'sufficient', @$_) } @l); if ($control eq 'required') { #- ensure a pam_deny line is there ($control, $module, @para) = ('required', 'pam_deny'); $_ .= pam_format_line($type, $control, $module); } } if (my $s = delete $before_first{$type}) { $_ = $s . $_; } if ($control eq 'required' && member($module, 'pam_deny', 'pam_unix')) { if (my $s = delete $after_deny{$type}) { $_ .= $s; } } } } "$::prefix/etc/pam.d/system-auth"; } sub set_nsswitch_priority { my (@kinds) = @_; my @known = qw(nis ldap winbind); substInFile { if (my ($database, $l) = /^(\s*(?:passwd|shadow|group|automount):\s*)(.*)/) { my @l = difference2([ split(' ', $l) ], \@known); $_ = $database . join(' ', uniq('files', @kinds, @l)) . "\n"; } } "$::prefix/etc/nsswitch.conf"; } sub read_yp_conf() { my $yp_conf = cat_("$::prefix/etc/yp.conf"); if ($yp_conf =~ /^domain\s+(\S+)\s+(\S+)\s*(.*)/m) { { domain => $1, server => $2 eq 'broadcast' ? 'broadcast' : $3 }; } elsif ($yp_conf =~ /^server\s+(.*)/m) { { server => $1 }; } else { undef; } } my $special_ldap_cmds = join('|', 'nss_map_attribute', 'nss_map_objectclass'); sub _after_read_ldap_line { my ($s) = @_; $s =~ s/\b($special_ldap_cmds)\s*/$1 . '_'/e; $s; } sub _pre_write_ldap_line { my ($s) = @_; $s =~ s/\b($special_ldap_cmds)_/$1 . ' '/e; $s; } sub read_ldap_conf() { my %conf = map { s/^\s*#.*//; if_(_after_read_ldap_line($_) =~ /(\S+)\s+(.*)/, $1 => $2); } cat_("$::prefix/etc/ldap.conf"); \%conf; } sub update_ldap_conf { my (%conf) = @_; substInFile { my ($cmd) = _after_read_ldap_line($_) =~ /^\s*#?\s*(\w+)\s/; if ($cmd && exists $conf{$cmd}) { my $val = $conf{$cmd}; $conf{$cmd} = ''; $_ = $val ? _pre_write_ldap_line("$cmd $val\n") : /^\s*#/ ? $_ : "#$_"; } if (eof) { foreach my $cmd (keys %conf) { my $val = $conf{$cmd} or next; $_ .= _pre_write_ldap_line("$cmd $val\n"); } } } "$::prefix/etc/ldap.conf"; } sub configure_krb5_for_AD { my ($authentication) = @_; my $uc_domain = uc $authentication->{AD_domain}; my $krb5_conf_file = "$::prefix/etc/krb5.conf"; krb5_conf_update($krb5_conf_file, libdefaults => ( default_realm => $uc_domain, dns_lookup_realm => $authentication->{AD_server} ? 'false' : 'true', dns_lookup_kdc => $authentication->{AD_server} ? 'false' : 'true', default_tgs_enctypes => undef, default_tkt_enctypes => undef, permitted_enctypes => undef, )); my @sections = ( realms => <<EOF, $uc_domain = { kdc = $authentication->{AD_server}:88 admin_server = $authentication->{AD_server}:749 default_domain = $authentication->{AD_domain} } EOF domain_realm => <<EOF, .$authentication->{AD_domain} = $uc_domain EOF kdc => <<'EOF', profile = /etc/kerberos/krb5kdc/kdc.conf EOF pam => <<'EOF', debug = false ticket_lifetime = 36000 renew_lifetime = 36000 forwardable = true krb4_convert = false EOF login => <<'EOF', krb4_convert = false krb4_get_tickets = false EOF ); foreach (group_by2(@sections)) { my ($section, $txt) = @$_; krb5_conf_overwrite_category($krb5_conf_file, $section => $authentication->{AD_server} ? $txt : ''); } } sub krb5_conf_overwrite_category { my ($file, $category, $new_val) = @_; my $done; substInFile { if (my $i = /^\s*\[\Q$category\E\]/i ... /^\[/) { if ($new_val) { if ($i == 1) { $_ .= $new_val; $done = 1; } elsif ($i =~ /E/) { $_ = "\n$_"; } else { $_ = ''; } } else { $_ = '' if $i !~ /E/; } } #- if category has not been found above. if (eof && $new_val && !$done) { $_ .= "\n[$category]\n$new_val"; } } $file; } #- same as update_gnomekderc(), but allow spaces around "=" sub krb5_conf_update { my ($file, $category, %subst_) = @_; my %subst = map { lc($_) => [ $_, $subst_{$_} ] } keys %subst_; my $s; foreach (MDK::Common::File::cat_($file), "[NOCATEGORY]\n") { if (my $i = /^\s*\[\Q$category\E\]/i ... /^\[/) { if ($i =~ /E/) { #- for last line of category chomp $s; $s .= "\n"; $s .= " $_->[0] = $_->[1]\n" foreach grep { defined($_->[1]) } values %subst; %subst = (); } elsif (/^\s*([^=]*?)\s*=/) { if (my $e = delete $subst{lc($1)}) { $_ = defined($e->[1]) ? " $1 = $e->[1]\n" : ''; } } } $s .= $_ if !/^\Q[NOCATEGORY]/; } #- if category has not been found above. if (keys %subst) { chomp $s; $s .= "\n[$category]\n"; $s .= " $_->[0] = $_->[1]\n" foreach grep { defined($_->[1]) } values %subst; } MDK::Common::File::output($file, $s); } sub sshd_config_UsePAM { my ($UsePAM) = @_; my $sshd = "$::prefix/etc/ssh/sshd_config"; -e $sshd or return; my $val = "UsePAM " . bool2yesno($UsePAM); substInFile { $val = '' if s/^#?UsePAM.*/$val/; $_ .= "$val\n" if eof && $val; } $sshd; } sub query_srv_names { my ($domain) = @_; eval { require Net::DNS; 1 } or return; my $res = Net::DNS::Resolver->new; my $query = $res->query("_ldap._tcp.$domain", 'srv') or return; map { $_->target } $query->answer; } sub enable_shadow() { run_program::rooted($::prefix, "pwconv") or log::l("pwconv failed"); run_program::rooted($::prefix, "grpconv") or log::l("grpconv failed"); } sub salt { my ($nb) = @_; require devices; open(my $F, devices::make("random")) or die "missing random"; my $s; read $F, $s, $nb; $s = pack("b8" x $nb, unpack "b6" x $nb, $s); $s =~ tr|\0-\x3f|0-9a-zA-Z./|; $s; } sub user_crypted_passwd { my ($u, $isMD5) = @_; if ($u->{password}) { crypt($u->{password}, $isMD5 ? '$1$' . salt(8) : salt(2)); } else { $u->{pw} || ''; } } sub set_root_passwd { my ($superuser, $authentication) = @_; $superuser->{name} = 'root'; write_passwd_user($superuser, $authentication->{md5}); delete $superuser->{name}; } sub write_passwd_user { my ($u, $isMD5) = @_; $u->{pw} = user_crypted_passwd($u, $isMD5); $u->{shell} ||= '/bin/bash'; substInFile { my $l = unpack_passwd($_); if ($l->{name} eq $u->{name}) { add2hash_($u, $l); $_ = pack_passwd($u); $u = {}; } if (eof && $u->{name}) { $_ .= pack_passwd($u); } } "$::prefix/etc/passwd"; } my @etc_pass_fields = qw(name pw uid gid realname home shell); sub unpack_passwd { my ($l) = @_; my %l; @l{@etc_pass_fields} = split ':', chomp_($l); \%l; } sub pack_passwd { my ($l) = @_; join(':', @$l{@etc_pass_fields}) . "\n"; } 1;