/** * Construct an IP address representation. * @param string $address The textual representation of an IP address or CIDR range. */ public function __construct($address) { // analyze address format $this->is_valid = IP::isIPAddress($address); if (!$this->is_valid) { return; } $this->is_ipv4 = IP::isIPv4($address); $this->is_ipv6 = !$this->is_ipv4 && IP::isIPv6($address); // analyze address range $this->is_range = IP::isValidBlock($address); $this->encoded_range = IP::parseRange($address); $this->range = array(IP::prettifyIP(IP::formatHex($this->encoded_range[self::START])), IP::prettifyIP(IP::formatHex($this->encoded_range[self::END]))); }
function fnGetGeoIP($ip_address = null) { if (!isset($ip_address)) { $ip_address = IP::sanitizeIP(wfGetIP()); } if (isset($_GET['ip'])) { $ip_address = IP::sanitizeIP($_GET['ip']); } if (!IP::isIPv4($ip_address)) { throw new UnsupportedGeoIP('Only IPv4 addresses are supported.'); } $dbr = wfGetDB(DB_SLAVE); $long_ip = IP::toUnsigned($ip_address); $conditions = array('begin_ip_long <= ' . $long_ip, $long_ip . ' <= end_ip_long'); $country_code = $dbr->selectField('geoip', 'country_code', $conditions, __METHOD__); if (!$country_code) { throw new NotFoundGeoIP('Could not identify the country for the provided IP address.'); } return $country_code; }
/** * @param string $info In the format of "udp://host:port/prefix" * @return UDPTransport * @throws InvalidArgumentException */ public static function newFromString($info) { if (preg_match('!^udp:(?://)?\\[([0-9a-fA-F:]+)\\]:(\\d+)(?:/(.*))?$!', $info, $m)) { // IPv6 bracketed host $host = $m[1]; $port = intval($m[2]); $prefix = isset($m[3]) ? $m[3] : false; $domain = AF_INET6; } elseif (preg_match('!^udp:(?://)?([a-zA-Z0-9.-]+):(\\d+)(?:/(.*))?$!', $info, $m)) { $host = $m[1]; if (!IP::isIPv4($host)) { $host = gethostbyname($host); } $port = intval($m[2]); $prefix = isset($m[3]) ? $m[3] : false; $domain = AF_INET; } else { throw new InvalidArgumentException(__METHOD__ . ': Invalid UDP specification'); } return new self($host, $port, $domain, $prefix); }
/** * Whether the given IP is in a given DNS blacklist. * * @param $ip String IP to check * @param $bases String|Array of Strings: URL of the DNS blacklist * @return Bool True if blacklisted. */ public function inDnsBlacklist($ip, $bases) { wfProfileIn(__METHOD__); $found = false; // @todo FIXME: IPv6 ??? (http://bugs.php.net/bug.php?id=33170) if (IP::isIPv4($ip)) { # Reverse IP, bug 21255 $ipReversed = implode('.', array_reverse(explode('.', $ip))); foreach ((array) $bases as $base) { # Make hostname $host = "{$ipReversed}.{$base}"; # Send query $ipList = gethostbynamel($host); if ($ipList) { wfDebug("Hostname {$host} is {$ipList[0]}, it's a proxy says {$base}!\n"); $found = true; break; } else { wfDebug("Requested {$host}, not found in {$base}.\n"); } } } wfProfileOut(__METHOD__); return $found; }
/** * Backend block code. * $userID and $expiry will be filled accordingly * @return array(message key, arguments) on failure, empty array on success */ function doBlock(&$userId = null, &$expiry = null) { global $wgUser, $wgSysopUserBans, $wgSysopRangeBans, $wgBlockAllowsUTEdit, $wgBlockCIDRLimit; $userId = 0; # Expand valid IPv6 addresses, usernames are left as is $this->BlockAddress = IP::sanitizeIP($this->BlockAddress); # isIPv4() and IPv6() are used for final validation $rxIP4 = '\\d{1,3}\\.\\d{1,3}\\.\\d{1,3}\\.\\d{1,3}'; $rxIP6 = '\\w{1,4}:\\w{1,4}:\\w{1,4}:\\w{1,4}:\\w{1,4}:\\w{1,4}:\\w{1,4}:\\w{1,4}'; $rxIP = "({$rxIP4}|{$rxIP6})"; # Check for invalid specifications if (!preg_match("/^{$rxIP}\$/", $this->BlockAddress)) { $matches = array(); if (preg_match("/^({$rxIP4})\\/(\\d{1,2})\$/", $this->BlockAddress, $matches)) { # IPv4 if ($wgSysopRangeBans) { if (!IP::isIPv4($this->BlockAddress) || $matches[2] > 32) { return array('ip_range_invalid'); } elseif ($matches[2] < $wgBlockCIDRLimit['IPv4']) { return array('ip_range_toolarge', $wgBlockCIDRLimit['IPv4']); } $this->BlockAddress = Block::normaliseRange($this->BlockAddress); } else { # Range block illegal return array('range_block_disabled'); } } elseif (preg_match("/^({$rxIP6})\\/(\\d{1,3})\$/", $this->BlockAddress, $matches)) { # IPv6 if ($wgSysopRangeBans) { if (!IP::isIPv6($this->BlockAddress) || $matches[2] > 128) { return array('ip_range_invalid'); } elseif ($matches[2] < $wgBlockCIDRLimit['IPv6']) { return array('ip_range_toolarge', $wgBlockCIDRLimit['IPv6']); } $this->BlockAddress = Block::normaliseRange($this->BlockAddress); } else { # Range block illegal return array('range_block_disabled'); } } else { # Username block if ($wgSysopUserBans) { $user = User::newFromName($this->BlockAddress); if (!is_null($user) && $user->getId()) { # Use canonical name $userId = $user->getId(); $this->BlockAddress = $user->getName(); } else { return array('nosuchusershort', htmlspecialchars($user ? $user->getName() : $this->BlockAddress)); } } else { return array('badipaddress'); } } } if ($wgUser->isBlocked() && $wgUser->getId() !== $userId) { return array('cant-block-while-blocked'); } $reasonstr = $this->BlockReasonList; if ($reasonstr != 'other' && $this->BlockReason != '') { // Entry from drop down menu + additional comment $reasonstr .= wfMsgForContent('colon-separator') . $this->BlockReason; } elseif ($reasonstr == 'other') { $reasonstr = $this->BlockReason; } $expirestr = $this->BlockExpiry; if ($expirestr == 'other') { $expirestr = $this->BlockOther; } if (strlen($expirestr) == 0 || strlen($expirestr) > 50) { return array('ipb_expiry_invalid'); } if (false === ($expiry = Block::parseExpiryInput($expirestr))) { // Bad expiry. return array('ipb_expiry_invalid'); } if ($this->BlockHideName) { // Recheck params here... if (!$userId || !$wgUser->isAllowed('hideuser')) { $this->BlockHideName = false; // IP users should not be hidden } elseif ($expiry !== 'infinity') { // Bad expiry. return array('ipb_expiry_temp'); } elseif (User::edits($userId) > self::HIDEUSER_CONTRIBLIMIT) { // Typically, the user should have a handful of edits. // Disallow hiding users with many edits for performance. return array('ipb_hide_invalid'); } } # Create block object # Note: for a user block, ipb_address is only for display purposes $block = new Block($this->BlockAddress, $userId, $wgUser->getId(), $reasonstr, wfTimestampNow(), 0, $expiry, $this->BlockAnonOnly, $this->BlockCreateAccount, $this->BlockEnableAutoblock, $this->BlockHideName, $this->BlockEmail, isset($this->BlockAllowUsertalk) ? $this->BlockAllowUsertalk : $wgBlockAllowsUTEdit); # Should this be privately logged? $suppressLog = (bool) $this->BlockHideName; if (wfRunHooks('BlockIp', array(&$block, &$wgUser))) { # Try to insert block. Is there a conflicting block? if (!$block->insert()) { # Show form unless the user is already aware of this... if (!$this->BlockReblock) { return array('ipb_already_blocked'); # Otherwise, try to update the block... } else { # This returns direct blocks before autoblocks/rangeblocks, since we should # be sure the user is blocked by now it should work for our purposes $currentBlock = Block::newFromDB($this->BlockAddress, $userId); if ($block->equals($currentBlock)) { return array('ipb_already_blocked'); } # If the name was hidden and the blocking user cannot hide # names, then don't allow any block changes... if ($currentBlock->mHideName && !$wgUser->isAllowed('hideuser')) { return array('cant-see-hidden-user'); } $currentBlock->delete(); $block->insert(); # If hiding/unhiding a name, this should go in the private logs $suppressLog = $suppressLog || (bool) $currentBlock->mHideName; $log_action = 'reblock'; # Unset _deleted fields if requested if ($currentBlock->mHideName && !$this->BlockHideName) { self::unsuppressUserName($this->BlockAddress, $userId); } } } else { $log_action = 'block'; } wfRunHooks('BlockIpComplete', array($block, $wgUser)); # Set *_deleted fields if requested if ($this->BlockHideName) { self::suppressUserName($this->BlockAddress, $userId); } # Only show watch link when this is no range block if ($this->BlockWatchUser && $block->mRangeStart == $block->mRangeEnd) { $wgUser->addWatch(Title::makeTitle(NS_USER, $this->BlockAddress)); } # Block constructor sanitizes certain block options on insert $this->BlockEmail = $block->mBlockEmail; $this->BlockEnableAutoblock = $block->mEnableAutoblock; # Prepare log parameters $logParams = array(); $logParams[] = $expirestr; $logParams[] = $this->blockLogFlags(); # Make log entry, if the name is hidden, put it in the oversight log $log_type = $suppressLog ? 'suppress' : 'block'; $log = new LogPage($log_type); $log->addEntry($log_action, Title::makeTitle(NS_USER, $this->BlockAddress), $reasonstr, $logParams); # Report to the user return array(); } else { return array('hookaborted'); } }
/** * Whether the given IP is in a given DNS blacklist. * * @param string $ip IP to check * @param string|array $bases Array of Strings: URL of the DNS blacklist * @return bool True if blacklisted. */ public function inDnsBlacklist($ip, $bases) { $found = false; // @todo FIXME: IPv6 ??? (http://bugs.php.net/bug.php?id=33170) if (IP::isIPv4($ip)) { // Reverse IP, bug 21255 $ipReversed = implode('.', array_reverse(explode('.', $ip))); foreach ((array) $bases as $base) { // Make hostname // If we have an access key, use that too (ProjectHoneypot, etc.) $basename = $base; if (is_array($base)) { if (count($base) >= 2) { // Access key is 1, base URL is 0 $host = "{$base[1]}.{$ipReversed}.{$base[0]}"; } else { $host = "{$ipReversed}.{$base[0]}"; } $basename = $base[0]; } else { $host = "{$ipReversed}.{$base}"; } // Send query $ipList = gethostbynamel($host); if ($ipList) { wfDebugLog('dnsblacklist', "Hostname {$host} is {$ipList[0]}, it's a proxy says {$basename}!"); $found = true; break; } else { wfDebugLog('dnsblacklist', "Requested {$host}, not found in {$basename}."); } } } return $found; }
/** * Log to a file without getting "file size exceeded" signals. * * Can also log to TCP or UDP with the syntax udp://host:port/prefix. This will * send lines to the specified port, prefixed by the specified prefix and a space. * * @param string $text * @param string $file Filename * @throws MWException */ function wfErrorLog($text, $file) { if (substr($file, 0, 4) == 'udp:') { # Needs the sockets extension if (preg_match('!^(tcp|udp):(?://)?\\[([0-9a-fA-F:]+)\\]:(\\d+)(?:/(.*))?$!', $file, $m)) { // IPv6 bracketed host $host = $m[2]; $port = intval($m[3]); $prefix = isset($m[4]) ? $m[4] : false; $domain = AF_INET6; } elseif (preg_match('!^(tcp|udp):(?://)?([a-zA-Z0-9.-]+):(\\d+)(?:/(.*))?$!', $file, $m)) { $host = $m[2]; if (!IP::isIPv4($host)) { $host = gethostbyname($host); } $port = intval($m[3]); $prefix = isset($m[4]) ? $m[4] : false; $domain = AF_INET; } else { throw new MWException(__METHOD__ . ': Invalid UDP specification'); } // Clean it up for the multiplexer if (strval($prefix) !== '') { $text = preg_replace('/^/m', $prefix . ' ', $text); // Limit to 64KB if (strlen($text) > 65506) { $text = substr($text, 0, 65506); } if (substr($text, -1) != "\n") { $text .= "\n"; } } elseif (strlen($text) > 65507) { $text = substr($text, 0, 65507); } $sock = socket_create($domain, SOCK_DGRAM, SOL_UDP); if (!$sock) { return; } socket_sendto($sock, $text, strlen($text), 0, $host, $port); socket_close($sock); } else { wfSuppressWarnings(); $exists = file_exists($file); $size = $exists ? filesize($file) : false; if (!$exists || $size !== false && $size + strlen($text) < 0x7fffffff) { file_put_contents($file, $text, FILE_APPEND); } wfRestoreWarnings(); } }
/** * Whether the given IP is in a given DNS blacklist. * * @param $ip String IP to check * @param $bases String|Array of Strings: URL of the DNS blacklist * @return Bool True if blacklisted. */ public function inDnsBlacklist($ip, $bases) { wfProfileIn(__METHOD__); $found = false; // @todo FIXME: IPv6 ??? (http://bugs.php.net/bug.php?id=33170) if (IP::isIPv4($ip)) { # Reverse IP, bug 21255 $ipReversed = implode('.', array_reverse(explode('.', $ip))); foreach ((array) $bases as $base) { # Make hostname # If we have an access key, use that too (ProjectHoneypot, etc.) if (is_array($base)) { if (count($base) >= 2) { # Access key is 1, base URL is 0 $host = "{$base[1]}.{$ipReversed}.{$base[0]}"; } else { $host = "{$ipReversed}.{$base[0]}"; } } else { $host = "{$ipReversed}.{$base}"; } # Send query $ipList = gethostbynamel($host); if ($ipList) { wfDebug("Hostname {$host} is {$ipList[0]}, it's a proxy says {$base}!\n"); $found = true; break; } else { wfDebug("Requested {$host}, not found in {$base}.\n"); } } } wfProfileOut(__METHOD__); return $found; }
public function execute() { global $wgContLang; $db = $this->getDB(); $params = $this->extractRequestParams(); $this->requireMaxOneParameter($params, 'users', 'ip'); $prop = array_flip($params['prop']); $fld_id = isset($prop['id']); $fld_user = isset($prop['user']); $fld_userid = isset($prop['userid']); $fld_by = isset($prop['by']); $fld_byid = isset($prop['byid']); $fld_timestamp = isset($prop['timestamp']); $fld_expiry = isset($prop['expiry']); $fld_reason = isset($prop['reason']); $fld_range = isset($prop['range']); $fld_flags = isset($prop['flags']); $result = $this->getResult(); $this->addTables('ipblocks'); $this->addFields(array('ipb_auto', 'ipb_id', 'ipb_timestamp')); $this->addFieldsIf(array('ipb_address', 'ipb_user'), $fld_user || $fld_userid); $this->addFieldsIf('ipb_by_text', $fld_by); $this->addFieldsIf('ipb_by', $fld_byid); $this->addFieldsIf('ipb_expiry', $fld_expiry); $this->addFieldsIf('ipb_reason', $fld_reason); $this->addFieldsIf(array('ipb_range_start', 'ipb_range_end'), $fld_range); $this->addFieldsIf(array('ipb_anon_only', 'ipb_create_account', 'ipb_enable_autoblock', 'ipb_block_email', 'ipb_deleted', 'ipb_allow_usertalk'), $fld_flags); $this->addOption('LIMIT', $params['limit'] + 1); $this->addTimestampWhereRange('ipb_timestamp', $params['dir'], $params['start'], $params['end']); // Include in ORDER BY for uniqueness $this->addWhereRange('ipb_id', $params['dir'], null, null); if (!is_null($params['continue'])) { $cont = explode('|', $params['continue']); $this->dieContinueUsageIf(count($cont) != 2); $op = $params['dir'] == 'newer' ? '>' : '<'; $continueTimestamp = $db->addQuotes($db->timestamp($cont[0])); $continueId = (int) $cont[1]; $this->dieContinueUsageIf($continueId != $cont[1]); $this->addWhere("ipb_timestamp {$op} {$continueTimestamp} OR " . "(ipb_timestamp = {$continueTimestamp} AND " . "ipb_id {$op}= {$continueId})"); } if (isset($params['ids'])) { $this->addWhereFld('ipb_id', $params['ids']); } if (isset($params['users'])) { $usernames = array(); foreach ((array) $params['users'] as $u) { $usernames[] = $this->prepareUsername($u); } $this->addWhereFld('ipb_address', $usernames); $this->addWhereFld('ipb_auto', 0); } if (isset($params['ip'])) { $blockCIDRLimit = $this->getConfig()->get('BlockCIDRLimit'); if (IP::isIPv4($params['ip'])) { $type = 'IPv4'; $cidrLimit = $blockCIDRLimit['IPv4']; $prefixLen = 0; } elseif (IP::isIPv6($params['ip'])) { $type = 'IPv6'; $cidrLimit = $blockCIDRLimit['IPv6']; $prefixLen = 3; // IP::toHex output is prefixed with "v6-" } else { $this->dieUsage('IP parameter is not valid', 'param_ip'); } # Check range validity, if it's a CIDR list($ip, $range) = IP::parseCIDR($params['ip']); if ($ip !== false && $range !== false && $range < $cidrLimit) { $this->dieUsage("{$type} CIDR ranges broader than /{$cidrLimit} are not accepted", 'cidrtoobroad'); } # Let IP::parseRange handle calculating $upper, instead of duplicating the logic here. list($lower, $upper) = IP::parseRange($params['ip']); # Extract the common prefix to any rangeblock affecting this IP/CIDR $prefix = substr($lower, 0, $prefixLen + floor($cidrLimit / 4)); # Fairly hard to make a malicious SQL statement out of hex characters, # but it is good practice to add quotes $lower = $db->addQuotes($lower); $upper = $db->addQuotes($upper); $this->addWhere(array('ipb_range_start' . $db->buildLike($prefix, $db->anyString()), 'ipb_range_start <= ' . $lower, 'ipb_range_end >= ' . $upper, 'ipb_auto' => 0)); } if (!is_null($params['show'])) { $show = array_flip($params['show']); /* Check for conflicting parameters. */ if (isset($show['account']) && isset($show['!account']) || isset($show['ip']) && isset($show['!ip']) || isset($show['range']) && isset($show['!range']) || isset($show['temp']) && isset($show['!temp'])) { $this->dieUsageMsg('show'); } $this->addWhereIf('ipb_user = 0', isset($show['!account'])); $this->addWhereIf('ipb_user != 0', isset($show['account'])); $this->addWhereIf('ipb_user != 0 OR ipb_range_end > ipb_range_start', isset($show['!ip'])); $this->addWhereIf('ipb_user = 0 AND ipb_range_end = ipb_range_start', isset($show['ip'])); $this->addWhereIf('ipb_expiry = ' . $db->addQuotes($db->getInfinity()), isset($show['!temp'])); $this->addWhereIf('ipb_expiry != ' . $db->addQuotes($db->getInfinity()), isset($show['temp'])); $this->addWhereIf('ipb_range_end = ipb_range_start', isset($show['!range'])); $this->addWhereIf('ipb_range_end > ipb_range_start', isset($show['range'])); } if (!$this->getUser()->isAllowed('hideuser')) { $this->addWhereFld('ipb_deleted', 0); } // Purge expired entries on one in every 10 queries if (!mt_rand(0, 10)) { Block::purgeExpired(); } $res = $this->select(__METHOD__); $count = 0; foreach ($res as $row) { if (++$count > $params['limit']) { // We've had enough $this->setContinueEnumParameter('continue', "{$row->ipb_timestamp}|{$row->ipb_id}"); break; } $block = array(ApiResult::META_TYPE => 'assoc'); if ($fld_id) { $block['id'] = (int) $row->ipb_id; } if ($fld_user && !$row->ipb_auto) { $block['user'] = $row->ipb_address; } if ($fld_userid && !$row->ipb_auto) { $block['userid'] = (int) $row->ipb_user; } if ($fld_by) { $block['by'] = $row->ipb_by_text; } if ($fld_byid) { $block['byid'] = (int) $row->ipb_by; } if ($fld_timestamp) { $block['timestamp'] = wfTimestamp(TS_ISO_8601, $row->ipb_timestamp); } if ($fld_expiry) { $block['expiry'] = $wgContLang->formatExpiry($row->ipb_expiry, TS_ISO_8601); } if ($fld_reason) { $block['reason'] = $row->ipb_reason; } if ($fld_range && !$row->ipb_auto) { $block['rangestart'] = IP::formatHex($row->ipb_range_start); $block['rangeend'] = IP::formatHex($row->ipb_range_end); } if ($fld_flags) { // For clarity, these flags use the same names as their action=block counterparts $block['automatic'] = (bool) $row->ipb_auto; $block['anononly'] = (bool) $row->ipb_anon_only; $block['nocreate'] = (bool) $row->ipb_create_account; $block['autoblock'] = (bool) $row->ipb_enable_autoblock; $block['noemail'] = (bool) $row->ipb_block_email; $block['hidden'] = (bool) $row->ipb_deleted; $block['allowusertalk'] = (bool) $row->ipb_allow_usertalk; } $fit = $result->addValue(array('query', $this->getModuleName()), null, $block); if (!$fit) { $this->setContinueEnumParameter('continue', "{$row->ipb_timestamp}|{$row->ipb_id}"); break; } } $result->addIndexedTagName(array('query', $this->getModuleName()), 'block'); }
/** * Whether the given IP is in a given DNS blacklist. * * @param $ip \string IP to check * @param $base \string URL of the DNS blacklist * @return \bool True if blacklisted. */ function inDnsBlacklist($ip, $base) { wfProfileIn(__METHOD__); $found = false; $host = ''; // FIXME: IPv6 ??? (http://bugs.php.net/bug.php?id=33170) if (IP::isIPv4($ip)) { # Make hostname $host = "{$ip}.{$base}"; # Send query $ipList = gethostbynamel($host); if ($ipList) { wfDebug("Hostname {$host} is {$ipList[0]}, it's a proxy says {$base}!\n"); $found = true; } else { wfDebug("Requested {$host}, not found in {$base}.\n"); } } wfProfileOut(__METHOD__); return $found; }
/** * Gets rid of uneeded numbers in quad-dotted/octet IP strings * For example, 127.111.113.151/24 -> 127.111.113.0/24 */ static function normaliseRange($range) { $parts = explode('/', $range); if (count($parts) == 2) { // IPv6 if (IP::isIPv6($range) && $parts[1] >= 64 && $parts[1] <= 128) { $bits = $parts[1]; $ipint = IP::toUnsigned6($parts[0]); # Native 32 bit functions WONT work here!!! # Convert to a padded binary number $network = wfBaseConvert($ipint, 10, 2, 128); # Truncate the last (128-$bits) bits and replace them with zeros $network = str_pad(substr($network, 0, $bits), 128, 0, STR_PAD_RIGHT); # Convert back to an integer $network = wfBaseConvert($network, 2, 10); # Reform octet address $newip = IP::toOctet($network); $range = "{$newip}/{$parts[1]}"; } else { if (IP::isIPv4($range) && $parts[1] >= 16 && $parts[1] <= 32) { $shift = 32 - $parts[1]; $ipint = IP::toUnsigned($parts[0]); $ipint = $ipint >> $shift << $shift; $newip = long2ip($ipint); $range = "{$newip}/{$parts[1]}"; } } } return $range; }
function GetGoogleWebsitesList($g) { $sock = new sockets(); $DisableGoogleSSL = $sock->GET_INFO("DisableGoogleSSL"); if (!is_numeric($DisableGoogleSSL)) { $DisableGoogleSSL = 0; } if ($DisableGoogleSSL == 0) { if ($GLOBALS["OUTPUT"]) { echo "Starting......: " . date("H:i:s") . " [INIT]: {$GLOBALS["TITLENAME"]} Goolge SSL is allowed\n"; } return $g; } $q = new mysql_squid_builder(); $arrayDN = $q->GetFamilySitestt(null, true); while (list($table, $fff) = each($arrayDN)) { if (preg_match("#\\.(gov|gouv|gor|org|net|web|ac)\\.#", "google.{$table}")) { continue; } $array[] = "www.google.{$table}"; $array[] = "google.{$table}"; } $ipaddr = gethostbyname("nosslsearch.google.com"); $ip = new IP(); $unix = new unix(); $php5 = $unix->LOCATE_PHP5_BIN(); $OK = true; if (!$ip->isIPv4($ipaddr)) { $OK = false; } if (!$OK) { if ($ip->isIPv6($ipaddr)) { $OK = true; } } if (!$OK) { if ($GLOBALS["OUTPUT"]) { echo "Starting......: " . date("H:i:s") . " [INIT]: {$GLOBALS["TITLENAME"]}, Unable to resolve nosslsearch.google.com\n"; } return $g; } while (list($a, $googlesite) = each($array)) { $g[] = "--address=/{$googlesite}/{$ipaddr}"; $g[] = "--cname={$googlesite},nosslsearch.google.com"; } return $g; }
function ipv4_add() { $ip = new IP(); if (!$ip->isIPv4($_POST["RemoteAddAddr"])) { echo "No an IPv4 address...\n"; return; } $sock = new sockets(); $datas = explode("\n", $sock->GET_INFO("PowerDNSListenAddr")); while (list($index, $ipmask) = each($datas)) { $array[$ipmask] = $ipmask; } $array[$_POST["RemoteAddAddr"]] = $_POST["RemoteAddAddr"]; while (list($index, $ipmask) = each($array)) { $f[] = $ipmask; } $sock->SaveConfigFile(@implode("\n", $f), "PowerDNSListenAddr"); $sock->getFrameWork("cmd.php?pdns-restart=yes"); }
function dump() { $ipaddr = gethostbyname("nosslsearch.google.com"); $ip = new IP(); $OK = true; if (!$ip->isIPv4($ipaddr)) { $OK = false; } if (!$OK) { if ($ip->isIPv6($ipaddr)) { $OK = true; } } if (!$OK) { echo "Failed nosslsearch.google.com `{$ipaddr}` not an IP address...!!!\n"; return; } $array = GetWebsitesList(); if (count($array) == 0) { echo "Failed!!! -> GetWebsitesList();\n"; return; } while (list($table, $fff) = each($array)) { echo "{$fff}\t{$ipaddr}\n"; } }
/** * Backend block code. * $userID and $expiry will be filled accordingly * @return array(message key, arguments) on failure, empty array on success */ function doBlock(&$userId = null, &$expiry = null) { global $wgUser, $wgSysopUserBans, $wgSysopRangeBans, $wgBlockAllowsUTEdit; $userId = 0; # Expand valid IPv6 addresses, usernames are left as is $this->BlockAddress = IP::sanitizeIP($this->BlockAddress); # isIPv4() and IPv6() are used for final validation $rxIP4 = '\\d{1,3}\\.\\d{1,3}\\.\\d{1,3}\\.\\d{1,3}'; $rxIP6 = '\\w{1,4}:\\w{1,4}:\\w{1,4}:\\w{1,4}:\\w{1,4}:\\w{1,4}:\\w{1,4}:\\w{1,4}'; $rxIP = "({$rxIP4}|{$rxIP6})"; # Check for invalid specifications if (!preg_match("/^{$rxIP}\$/", $this->BlockAddress)) { $matches = array(); if (preg_match("/^({$rxIP4})\\/(\\d{1,2})\$/", $this->BlockAddress, $matches)) { # IPv4 if ($wgSysopRangeBans) { if (!IP::isIPv4($this->BlockAddress) || $matches[2] < 16 || $matches[2] > 32) { return array('ip_range_invalid'); } $this->BlockAddress = Block::normaliseRange($this->BlockAddress); } else { # Range block illegal return array('range_block_disabled'); } } else { if (preg_match("/^({$rxIP6})\\/(\\d{1,3})\$/", $this->BlockAddress, $matches)) { # IPv6 if ($wgSysopRangeBans) { if (!IP::isIPv6($this->BlockAddress) || $matches[2] < 64 || $matches[2] > 128) { return array('ip_range_invalid'); } $this->BlockAddress = Block::normaliseRange($this->BlockAddress); } else { # Range block illegal return array('range_block_disabled'); } } else { # Username block if ($wgSysopUserBans) { $user = User::newFromName($this->BlockAddress); if (!is_null($user) && $user->getId()) { # Use canonical name $userId = $user->getId(); $this->BlockAddress = $user->getName(); } else { return array('nosuchusershort', htmlspecialchars($user ? $user->getName() : $this->BlockAddress)); } } else { return array('badipaddress'); } } } } if ($wgUser->isBlocked() && $wgUser->getId() !== $userId) { return array('cant-block-while-blocked'); } $reasonstr = $this->BlockReasonList; if ($reasonstr != 'other' && $this->BlockReason != '') { // Entry from drop down menu + additional comment $reasonstr .= ': ' . $this->BlockReason; } elseif ($reasonstr == 'other') { $reasonstr = $this->BlockReason; } $expirestr = $this->BlockExpiry; if ($expirestr == 'other') { $expirestr = $this->BlockOther; } if (strlen($expirestr) == 0 || strlen($expirestr) > 50) { return array('ipb_expiry_invalid'); } if (false === ($expiry = Block::parseExpiryInput($expirestr))) { // Bad expiry. return array('ipb_expiry_invalid'); } if ($this->BlockHideName && $expiry != 'infinity') { // Bad expiry. return array('ipb_expiry_temp'); } # Create block # Note: for a user block, ipb_address is only for display purposes $block = new Block($this->BlockAddress, $userId, $wgUser->getId(), $reasonstr, wfTimestampNow(), 0, $expiry, $this->BlockAnonOnly, $this->BlockCreateAccount, $this->BlockEnableAutoblock, $this->BlockHideName, $this->BlockEmail, isset($this->BlockAllowUsertalk) ? $this->BlockAllowUsertalk : $wgBlockAllowsUTEdit); if (wfRunHooks('BlockIp', array(&$block, &$wgUser))) { if (!$block->insert()) { if (!$this->BlockReblock) { return array('ipb_already_blocked'); } else { # This returns direct blocks before autoblocks/rangeblocks, since we should # be sure the user is blocked by now it should work for our purposes $currentBlock = Block::newFromDB($this->BlockAddress, $userId); if ($block->equals($currentBlock)) { return array('ipb_already_blocked'); } $currentBlock->delete(); $block->insert(); $log_action = 'reblock'; } } else { $log_action = 'block'; } wfRunHooks('BlockIpComplete', array($block, $wgUser)); if ($this->BlockWatchUser) { $wgUser->addWatch(Title::makeTitle(NS_USER, $this->BlockAddress)); } # Prepare log parameters $logParams = array(); $logParams[] = $expirestr; $logParams[] = $this->blockLogFlags(); # Make log entry, if the name is hidden, put it in the oversight log $log_type = $this->BlockHideName ? 'suppress' : 'block'; $log = new LogPage($log_type); $log->addEntry($log_action, Title::makeTitle(NS_USER, $this->BlockAddress), $reasonstr, $logParams); # Report to the user return array(); } else { return array('hookaborted'); } }
/** * HTMLForm field validation-callback for Target field. * @since 1.18 * @param $value String * @param $alldata Array * @param $form HTMLForm * @return Message */ public static function validateTargetField($value, $alldata, $form) { global $wgBlockCIDRLimit; list($target, $type) = self::getTargetAndType($value); if ($type == Block::TYPE_USER) { # TODO: why do we not have a User->exists() method? if (!$target->getId()) { return $form->msg('nosuchusershort', wfEscapeWikiText($target->getName())); } $status = self::checkUnblockSelf($target, $form->getUser()); if ($status !== true) { return $form->msg('badaccess', $status); } } elseif ($type == Block::TYPE_RANGE) { list($ip, $range) = explode('/', $target, 2); if (IP::isIPv4($ip) && $wgBlockCIDRLimit['IPv4'] == 32 || IP::isIPv6($ip) && $wgBlockCIDRLimit['IPv6'] == 128) { # Range block effectively disabled return $form->msg('range_block_disabled'); } if (IP::isIPv4($ip) && $range > 32 || IP::isIPv6($ip) && $range > 128) { # Dodgy range return $form->msg('ip_range_invalid'); } if (IP::isIPv4($ip) && $range < $wgBlockCIDRLimit['IPv4']) { return $form->msg('ip_range_toolarge', $wgBlockCIDRLimit['IPv4']); } if (IP::isIPv6($ip) && $range < $wgBlockCIDRLimit['IPv6']) { return $form->msg('ip_range_toolarge', $wgBlockCIDRLimit['IPv6']); } } elseif ($type == Block::TYPE_IP) { # All is well } else { return $form->msg('badipaddress'); } return true; }
/** * Get the host's IP address. * Does not support IPv6 at present due to the lack of a convenient interface in PHP. * @throws MWException * @return string */ protected function getIP() { if ($this->ip === null) { if (IP::isIPv4($this->host)) { $this->ip = $this->host; } elseif (IP::isIPv6($this->host)) { throw new MWException('$wgSquidServers does not support IPv6'); } else { wfSuppressWarnings(); $this->ip = gethostbyname($this->host); if ($this->ip === $this->host) { $this->ip = false; } wfRestoreWarnings(); } } return $this->ip; }
/** * Backend block code. * $userID and $expiry will be filled accordingly * @return array(message key, arguments) on failure, empty array on success */ function doBlock(&$userId = null, &$expiry = null) { global $wgUser, $wgSysopUserBans, $wgSysopRangeBans; $userId = 0; # Expand valid IPv6 addresses, usernames are left as is $this->BlockAddress = IP::sanitizeIP($this->BlockAddress); # isIPv4() and IPv6() are used for final validation $rxIP4 = '\\d{1,3}\\.\\d{1,3}\\.\\d{1,3}\\.\\d{1,3}'; $rxIP6 = '\\w{1,4}:\\w{1,4}:\\w{1,4}:\\w{1,4}:\\w{1,4}:\\w{1,4}:\\w{1,4}:\\w{1,4}'; $rxIP = "({$rxIP4}|{$rxIP6})"; # Check for invalid specifications if (!preg_match("/^{$rxIP}\$/", $this->BlockAddress)) { $matches = array(); if (preg_match("/^({$rxIP4})\\/(\\d{1,2})\$/", $this->BlockAddress, $matches)) { # IPv4 if ($wgSysopRangeBans) { if (!IP::isIPv4($this->BlockAddress) || $matches[2] < 16 || $matches[2] > 32) { return array('ip_range_invalid'); } $this->BlockAddress = Block::normaliseRange($this->BlockAddress); } else { # Range block illegal return array('range_block_disabled'); } } else { if (preg_match("/^({$rxIP6})\\/(\\d{1,3})\$/", $this->BlockAddress, $matches)) { # IPv6 if ($wgSysopRangeBans) { if (!IP::isIPv6($this->BlockAddress) || $matches[2] < 64 || $matches[2] > 128) { return array('ip_range_invalid'); } $this->BlockAddress = Block::normaliseRange($this->BlockAddress); } else { # Range block illegal return array('range_block_disabled'); } } else { # Username block if ($wgSysopUserBans) { $user = User::newFromName($this->BlockAddress); if (!is_null($user) && $user->getID()) { # Use canonical name $userId = $user->getID(); $this->BlockAddress = $user->getName(); } else { return array('nosuchusershort', htmlspecialchars($user ? $user->getName() : $this->BlockAddress)); } } else { return array('badipaddress'); } } } } $reasonstr = $this->BlockReasonList; if ($reasonstr != 'other' && $this->BlockReason != '') { // Entry from drop down menu + additional comment $reasonstr .= ': ' . $this->BlockReason; } elseif ($reasonstr == 'other') { $reasonstr = $this->BlockReason; } $expirestr = $this->BlockExpiry; if ($expirestr == 'other') { $expirestr = $this->BlockOther; } if (strlen($expirestr) == 0) { return array('ipb_expiry_invalid'); } if ($expirestr == 'infinite' || $expirestr == 'indefinite') { $expiry = Block::infinity(); } else { # Convert GNU-style date, on error returns -1 for PHP <5.1 and false for PHP >=5.1 $expiry = strtotime($expirestr); if ($expiry < 0 || $expiry === false) { return array('ipb_expiry_invalid'); } $expiry = wfTimestamp(TS_MW, $expiry); } # Create block # Note: for a user block, ipb_address is only for display purposes $block = new Block($this->BlockAddress, $userId, $wgUser->getID(), $reasonstr, wfTimestampNow(), 0, $expiry, $this->BlockAnonOnly, $this->BlockCreateAccount, $this->BlockEnableAutoblock, $this->BlockHideName, $this->BlockEmail); if (wfRunHooks('BlockIp', array(&$block, &$wgUser))) { if (!$block->insert()) { return array('ipb_already_blocked', htmlspecialchars($this->BlockAddress)); } wfRunHooks('BlockIpComplete', array($block, $wgUser)); # Prepare log parameters $logParams = array(); $logParams[] = $expirestr; $logParams[] = $this->blockLogFlags(); # Make log entry, if the name is hidden, put it in the oversight log $log_type = $this->BlockHideName ? 'oversight' : 'block'; $log = new LogPage($log_type); $log->addEntry('block', Title::makeTitle(NS_USER, $this->BlockAddress), $reasonstr, $logParams); # Report to the user return array(); } else { return array('hookaborted'); } }
function CheckIpV4ToIp26(){ $ipt=$_POST["CheckIpV4ToIp26"]; $ip=new IP(); if($ip->isIPv4($ipt)){ echo $ip->IPv4To6($ipt); } }
/** * @covers IP::isIPv4 * @dataProvider provideValidIPv4Address */ public function testIsIPv4($ip, $desc) { $this->assertTrue(IP::isIPv4($ip), $desc); }
/** * @covers IP::isIPv4 */ public function testisIPv4() { $this->assertFalse(IP::isIPv4(false), 'Boolean false is not an IP'); $this->assertFalse(IP::isIPv4(true), 'Boolean true is not an IP'); $this->assertFalse(IP::isIPv4(""), 'Empty string is not an IP'); $this->assertFalse(IP::isIPv4('abc')); $this->assertFalse(IP::isIPv4(':')); $this->assertFalse(IP::isIPv4('124.24.52'), 'IPv4 not enough quads'); $this->assertFalse(IP::isIPv4('24.324.52.13'), 'IPv4 out of range'); $this->assertFalse(IP::isIPv4('.24.52.13'), 'IPv4 starts with period'); $this->assertTrue(IP::isIPv4('124.24.52.13')); $this->assertTrue(IP::isIPv4('1.24.52.13')); $this->assertTrue(IP::isIPv4('74.24.52.13/20', 'IPv4 range')); }
/** * Validate a block target. * * @since 1.21 * @param string $value Block target to check * @param User $user Performer of the block * @return Status */ public static function validateTarget($value, User $user) { global $wgBlockCIDRLimit; /** @var User $target */ list($target, $type) = self::getTargetAndType($value); $status = Status::newGood($target); if ($type == Block::TYPE_USER) { if ($target->isAnon()) { $status->fatal('nosuchusershort', wfEscapeWikiText($target->getName())); } $unblockStatus = self::checkUnblockSelf($target, $user); if ($unblockStatus !== true) { $status->fatal('badaccess', $unblockStatus); } } elseif ($type == Block::TYPE_RANGE) { list($ip, $range) = explode('/', $target, 2); if (IP::isIPv4($ip) && $wgBlockCIDRLimit['IPv4'] == 32 || IP::isIPv6($ip) && $wgBlockCIDRLimit['IPv6'] == 128) { // Range block effectively disabled $status->fatal('range_block_disabled'); } if (IP::isIPv4($ip) && $range > 32 || IP::isIPv6($ip) && $range > 128) { // Dodgy range $status->fatal('ip_range_invalid'); } if (IP::isIPv4($ip) && $range < $wgBlockCIDRLimit['IPv4']) { $status->fatal('ip_range_toolarge', $wgBlockCIDRLimit['IPv4']); } if (IP::isIPv6($ip) && $range < $wgBlockCIDRLimit['IPv6']) { $status->fatal('ip_range_toolarge', $wgBlockCIDRLimit['IPv6']); } } elseif ($type == Block::TYPE_IP) { # All is well } else { $status->fatal('badipaddress'); } return $status; }