Пример #1
0
 /**
  * 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])));
 }
Пример #2
0
 /**
  * @covers IP::isIPv6
  */
 public function testisIPv6()
 {
     $this->assertFalse(IP::isIPv6(':fc:100::'), 'IPv6 starting with lone ":"');
     $this->assertFalse(IP::isIPv6('fc:100:::'), 'IPv6 ending with a ":::"');
     $this->assertFalse(IP::isIPv6('fc:300'), 'IPv6 with only 2 words');
     $this->assertFalse(IP::isIPv6('fc:100:300'), 'IPv6 with only 3 words');
     $this->assertTrue(IP::isIPv6('fc:100::'));
     $this->assertTrue(IP::isIPv6('fc:100:a::'));
     $this->assertTrue(IP::isIPv6('fc:100:a:d::'));
     $this->assertTrue(IP::isIPv6('fc:100:a:d:1::'));
     $this->assertTrue(IP::isIPv6('fc:100:a:d:1:e::'));
     $this->assertTrue(IP::isIPv6('fc:100:a:d:1:e:ac::'));
     $this->assertFalse(IP::isIPv6('fc:100:a:d:1:e:ac:0::'), 'IPv6 with 8 words ending with "::"');
     $this->assertFalse(IP::isIPv6('fc:100:a:d:1:e:ac:0:1::'), 'IPv6 with 9 words ending with "::"');
     $this->assertFalse(IP::isIPv6(':::'));
     $this->assertFalse(IP::isIPv6('::0:'), 'IPv6 ending in a lone ":"');
     $this->assertTrue(IP::isIPv6('::'), 'IPv6 zero address');
     $this->assertTrue(IP::isIPv6('::0'));
     $this->assertTrue(IP::isIPv6('::fc'));
     $this->assertTrue(IP::isIPv6('::fc:100'));
     $this->assertTrue(IP::isIPv6('::fc:100:a'));
     $this->assertTrue(IP::isIPv6('::fc:100:a:d'));
     $this->assertTrue(IP::isIPv6('::fc:100:a:d:1'));
     $this->assertTrue(IP::isIPv6('::fc:100:a:d:1:e'));
     $this->assertTrue(IP::isIPv6('::fc:100:a:d:1:e:ac'));
     $this->assertFalse(IP::isIPv6('::fc:100:a:d:1:e:ac:0'), 'IPv6 with "::" and 8 words');
     $this->assertFalse(IP::isIPv6('::fc:100:a:d:1:e:ac:0:1'), 'IPv6 with 9 words');
     $this->assertFalse(IP::isIPv6(':fc::100'), 'IPv6 starting with lone ":"');
     $this->assertFalse(IP::isIPv6('fc::100:'), 'IPv6 ending with lone ":"');
     $this->assertFalse(IP::isIPv6('fc:::100'), 'IPv6 with ":::" in the middle');
     $this->assertTrue(IP::isIPv6('fc::100'), 'IPv6 with "::" and 2 words');
     $this->assertTrue(IP::isIPv6('fc::100:a'), 'IPv6 with "::" and 3 words');
     $this->assertTrue(IP::isIPv6('fc::100:a:d', 'IPv6 with "::" and 4 words'));
     $this->assertTrue(IP::isIPv6('fc::100:a:d:1'), 'IPv6 with "::" and 5 words');
     $this->assertTrue(IP::isIPv6('fc::100:a:d:1:e'), 'IPv6 with "::" and 6 words');
     $this->assertTrue(IP::isIPv6('fc::100:a:d:1:e:ac'), 'IPv6 with "::" and 7 words');
     $this->assertTrue(IP::isIPv6('2001::df'), 'IPv6 with "::" and 2 words');
     $this->assertTrue(IP::isIPv6('2001:5c0:1400:a::df'), 'IPv6 with "::" and 5 words');
     $this->assertTrue(IP::isIPv6('2001:5c0:1400:a::df:2'), 'IPv6 with "::" and 6 words');
     $this->assertFalse(IP::isIPv6('fc::100:a:d:1:e:ac:0'), 'IPv6 with "::" and 8 words');
     $this->assertFalse(IP::isIPv6('fc::100:a:d:1:e:ac:0:1'), 'IPv6 with 9 words');
     $this->assertTrue(IP::isIPv6('fc:100:a:d:1:e:ac:0'));
 }
Пример #3
0
 /**
  * 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;
 }
Пример #5
0
 /**
  * Roughly increments the cache misses in the last hour by unique visitors
  * @param WebRequest $request
  * @return void
  */
 public function incrMissesRecent(WebRequest $request)
 {
     if (mt_rand(0, self::MISS_FACTOR - 1) == 0) {
         $cache = ObjectCache::getLocalClusterInstance();
         # Get a large IP range that should include the user  even if that
         # person's IP address changes
         $ip = $request->getIP();
         if (!IP::isValid($ip)) {
             return;
         }
         $ip = IP::isIPv6($ip) ? IP::sanitizeRange("{$ip}/32") : IP::sanitizeRange("{$ip}/16");
         # Bail out if a request already came from this range...
         $key = wfMemcKey(get_class($this), 'attempt', $this->mType, $this->mKey, $ip);
         if ($cache->get($key)) {
             return;
             // possibly the same user
         }
         $cache->set($key, 1, self::MISS_TTL_SEC);
         # Increment the number of cache misses...
         $key = $this->cacheMissKey();
         if ($cache->get($key) === false) {
             $cache->set($key, 1, self::MISS_TTL_SEC);
         } else {
             $cache->incr($key);
         }
     }
 }
Пример #6
0
 /**
  * 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');
     }
 }
Пример #7
0
 /**
  * Does the string match an anonymous IPv4 address?
  *
  * This function exists for username validation, in order to reject
  * usernames which are similar in form to IP addresses. Strings such
  * as 300.300.300.300 will return true because it looks like an IP
  * address, despite not being strictly valid.
  *
  * We match \d{1,3}\.\d{1,3}\.\d{1,3}\.xxx as an anonymous IP
  * address because the usemod software would "cloak" anonymous IP
  * addresses like this, if we allowed accounts like this to be created
  * new users could get the old edits of these anonymous users.
  *
  * @param $name String to match
  * @return Bool
  */
 public static function isIP($name)
 {
     return preg_match('/^\\d{1,3}\\.\\d{1,3}\\.\\d{1,3}\\.(?:xxx|\\d{1,3})$/', $name) || IP::isIPv6($name);
 }
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";
    }
}
Пример #9
0
function Checkipv6Virts()
{
    $unix = new unix();
    $sock = new sockets();
    $EnableipV6 = $sock->GET_INFO("EnableipV6");
    $NetBuilder = new system_nic();
    if (!is_numeric($EnableipV6)) {
        $EnableipV6 = 0;
    }
    if ($EnableipV6 == 0) {
        return;
    }
    $q = new mysql();
    $sql = "SELECT nic FROM nics_virtuals WHERE ipv6=1";
    $results = $q->QUERY_SQL($sql, "artica_backup");
    $eths = array();
    while ($ligne = @mysql_fetch_array($results, MYSQL_ASSOC)) {
        $eths[$ligne["nic"]] = $ligne["nic"];
    }
    if (count($eths) == 0) {
        echo "Starting......: " . date("H:i:s") . " Building Ipv6 virtuals IP -> 0 interface...\n";
        return;
    }
    $echo = $unix->find_program("echo");
    $ipbin = $unix->find_program("ip");
    $ip = new IP();
    $sh = array();
    while (list($eth, $ligne) = each($eths)) {
        echo "Starting......: " . date("H:i:s") . " Building Ipv6 virtuals IP for `{$eth}` interface...\n";
        $sh[] = "{$echo} 0 > /proc/sys/net/ipv6/conf/{$eth}/disable_ipv6";
        $sh[] = "{$echo} 0 > /proc/sys/net/ipv6/conf/{$eth}/autoconf";
        $sh[] = "{$echo} 0 > /proc/sys/net/ipv6/conf/{$eth}/accept_ra";
        $sh[] = "{$echo} 0 > /proc/sys/net/ipv6/conf/{$eth}/accept_ra_defrtr";
        $sh[] = "{$echo} 0 > /proc/sys/net/ipv6/conf/{$eth}/accept_ra_pinfo";
        $sh[] = "{$echo} 0 > /proc/sys/net/ipv6/conf/{$eth}/accept_ra_rtr_pref";
        $sql = "SELECT * FROM nics_virtuals WHERE ipv6=1 AND nic='{$eth}' ORDER BY ID DESC";
        $results = $q->QUERY_SQL($sql, "artica_backup");
        while ($ligne = @mysql_fetch_array($results, MYSQL_ASSOC)) {
            $ipv6addr = $ligne["ipaddr"];
            $netmask = $ligne["netmask"];
            if (!is_numeric($netmask)) {
                $netmask = 0;
            }
            if ($netmask == 0) {
                continue;
            }
            if (!$ip->isIPv6($ipv6addr)) {
                continue;
            }
            echo "Starting......: " . date("H:i:s") . " Building Ipv6 virtuals IP for `{$eth}` [{$ipv6addr}/{$netmask}]...\n";
            $sh[] = "{$ipbin} addr add dev {$eth} {$ipv6addr}/{$netmask}";
        }
    }
    if (count($sh) == 0) {
        return;
    }
    while (list($num, $cmdline) = each($sh)) {
        if ($GLOBALS["VERBOSE"]) {
            echo "Starting......: " . date("H:i:s") . " Building Ipv6 virtuals {$cmdline}\n";
        }
        shell_exec($cmdline);
    }
}
Пример #10
0
 /**
  * Primitive rate limits: enforce maximum actions per time period
  * to put a brake on flooding.
  *
  * The method generates both a generic profiling point and a per action one
  * (suffix being "-$action".
  *
  * @note When using a shared cache like memcached, IP-address
  * last-hit counters will be shared across wikis.
  *
  * @param string $action Action to enforce; 'edit' if unspecified
  * @param int $incrBy Positive amount to increment counter by [defaults to 1]
  * @return bool True if a rate limiter was tripped
  */
 public function pingLimiter($action = 'edit', $incrBy = 1)
 {
     // Call the 'PingLimiter' hook
     $result = false;
     if (!Hooks::run('PingLimiter', array(&$this, $action, &$result, $incrBy))) {
         return $result;
     }
     global $wgRateLimits;
     if (!isset($wgRateLimits[$action])) {
         return false;
     }
     // Some groups shouldn't trigger the ping limiter, ever
     if (!$this->isPingLimitable()) {
         return false;
     }
     global $wgMemc;
     $limits = $wgRateLimits[$action];
     $keys = array();
     $id = $this->getId();
     $userLimit = false;
     if (isset($limits['anon']) && $id == 0) {
         $keys[wfMemcKey('limiter', $action, 'anon')] = $limits['anon'];
     }
     if (isset($limits['user']) && $id != 0) {
         $userLimit = $limits['user'];
     }
     if ($this->isNewbie()) {
         if (isset($limits['newbie']) && $id != 0) {
             $keys[wfMemcKey('limiter', $action, 'user', $id)] = $limits['newbie'];
         }
         if (isset($limits['ip'])) {
             $ip = $this->getRequest()->getIP();
             $keys["mediawiki:limiter:{$action}:ip:{$ip}"] = $limits['ip'];
         }
         if (isset($limits['subnet'])) {
             $ip = $this->getRequest()->getIP();
             $matches = array();
             $subnet = false;
             if (IP::isIPv6($ip)) {
                 $parts = IP::parseRange("{$ip}/64");
                 $subnet = $parts[0];
             } elseif (preg_match('/^(\\d+\\.\\d+\\.\\d+)\\.\\d+$/', $ip, $matches)) {
                 // IPv4
                 $subnet = $matches[1];
             }
             if ($subnet !== false) {
                 $keys["mediawiki:limiter:{$action}:subnet:{$subnet}"] = $limits['subnet'];
             }
         }
     }
     // Check for group-specific permissions
     // If more than one group applies, use the group with the highest limit
     foreach ($this->getGroups() as $group) {
         if (isset($limits[$group])) {
             if ($userLimit === false || $limits[$group][0] / $limits[$group][1] > $userLimit[0] / $userLimit[1]) {
                 $userLimit = $limits[$group];
             }
         }
     }
     // Set the user limit key
     if ($userLimit !== false) {
         list($max, $period) = $userLimit;
         wfDebug(__METHOD__ . ": effective user limit: {$max} in {$period}s\n");
         $keys[wfMemcKey('limiter', $action, 'user', $id)] = $userLimit;
     }
     $triggered = false;
     foreach ($keys as $key => $limit) {
         list($max, $period) = $limit;
         $summary = "(limit {$max} in {$period}s)";
         $count = $wgMemc->get($key);
         // Already pinged?
         if ($count) {
             if ($count >= $max) {
                 wfDebugLog('ratelimit', "User '{$this->getName()}' " . "(IP {$this->getRequest()->getIP()}) tripped {$key} at {$count} {$summary}");
                 $triggered = true;
             } else {
                 wfDebug(__METHOD__ . ": ok. {$key} at {$count} {$summary}\n");
             }
         } else {
             wfDebug(__METHOD__ . ": adding record for {$key} {$summary}\n");
             if ($incrBy > 0) {
                 $wgMemc->add($key, 0, intval($period));
                 // first ping
             }
         }
         if ($incrBy > 0) {
             $wgMemc->incr($key, $incrBy);
         }
     }
     return $triggered;
 }
Пример #11
0
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;
}
Пример #12
0
 /** 
  * 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;
 }
Пример #13
0
 /**
  * Convert some unusual representations of IPv4 addresses to their
  * canonical dotted quad representation.
  *
  * This currently only checks a few IPV4-to-IPv6 related cases.  More
  * unusual representations may be added later.
  *
  * @param $addr something that might be an IP address
  * @return valid dotted quad IPv4 address or null
  */
 public static function canonicalize($addr)
 {
     if (self::isValid($addr)) {
         return $addr;
     }
     // Annoying IPv6 representations like ::ffff:1.2.3.4
     if (strpos($addr, ':') !== false && strpos($addr, '.') !== false) {
         $addr = str_replace('.', ':', $addr);
         if (IP::isIPv6($addr)) {
             return $addr;
         }
     }
     // IPv6 loopback address
     $m = array();
     if (preg_match('/^0*' . RE_IPV6_GAP . '1$/', $addr, $m)) {
         return '127.0.0.1';
     }
     // IPv4-mapped and IPv4-compatible IPv6 addresses
     if (preg_match('/^' . RE_IPV6_V4_PREFIX . '(' . RE_IP_ADD . ')$/i', $addr, $m)) {
         return $m[1];
     }
     if (preg_match('/^' . RE_IPV6_V4_PREFIX . RE_IPV6_WORD . ':' . RE_IPV6_WORD . '$/i', $addr, $m)) {
         return long2ip((hexdec($m[1]) << 16) + hexdec($m[2]));
     }
     return null;
     // give up
 }
Пример #14
0
function ipv6_add()
{
    $ip = new IP();
    if (!$ip->isIPv6($_POST["RemoteAddAddrv6"])) {
        echo "No an IPv6 address...\n";
        return;
    }
    $sock = new sockets();
    $datas = explode("\n", $sock->GET_INFO("PowerDNSListenAddrV6"));
    while (list($index, $ipmask) = each($datas)) {
        $array[$ipmask] = $ipmask;
    }
    $array[$_POST["RemoteAddAddrv6"]] = $_POST["RemoteAddAddrv6"];
    while (list($index, $ipmask) = each($array)) {
        $f[] = $ipmask;
    }
    $sock->SaveConfigFile(@implode("\n", $f), "PowerDNSListenAddrV6");
    $sock->getFrameWork("cmd.php?pdns-restart=yes");
}
Пример #15
0
	/**
	 * Primitive rate limits: enforce maximum actions per time period
	 * to put a brake on flooding.
	 *
	 * @note When using a shared cache like memcached, IP-address
	 * last-hit counters will be shared across wikis.
	 *
	 * @param string $action Action to enforce; 'edit' if unspecified
	 * @param integer $incrBy Positive amount to increment counter by [defaults to 1]
	 * @return bool True if a rate limiter was tripped
	 */
	public function pingLimiter( $action = 'edit', $incrBy = 1 ) {
		// Call the 'PingLimiter' hook
		$result = false;
		if ( !wfRunHooks( 'PingLimiter', array( &$this, $action, &$result, $incrBy ) ) ) {
			return $result;
		}

		global $wgRateLimits;
		if ( !isset( $wgRateLimits[$action] ) ) {
			return false;
		}

		// Some groups shouldn't trigger the ping limiter, ever
		if ( !$this->isPingLimitable() ) {
			return false;
		}

		global $wgMemc, $wgRateLimitLog;
		wfProfileIn( __METHOD__ );

		$limits = $wgRateLimits[$action];
		$keys = array();
		$id = $this->getId();
		$userLimit = false;

		if ( isset( $limits['anon'] ) && $id == 0 ) {
			$keys[wfMemcKey( 'limiter', $action, 'anon' )] = $limits['anon'];
		}

		if ( isset( $limits['user'] ) && $id != 0 ) {
			$userLimit = $limits['user'];
		}
		if ( $this->isNewbie() ) {
			if ( isset( $limits['newbie'] ) && $id != 0 ) {
				$keys[wfMemcKey( 'limiter', $action, 'user', $id )] = $limits['newbie'];
			}
			if ( isset( $limits['ip'] ) ) {
				$ip = $this->getRequest()->getIP();
				$keys["mediawiki:limiter:$action:ip:$ip"] = $limits['ip'];
			}
			if ( isset( $limits['subnet'] ) ) {
				$ip = $this->getRequest()->getIP();
				$matches = array();
				$subnet = false;
				if ( IP::isIPv6( $ip ) ) {
					$parts = IP::parseRange( "$ip/64" );
					$subnet = $parts[0];
				} elseif ( preg_match( '/^(\d+\.\d+\.\d+)\.\d+$/', $ip, $matches ) ) {
					// IPv4
					$subnet = $matches[1];
				}
				if ( $subnet !== false ) {
					$keys["mediawiki:limiter:$action:subnet:$subnet"] = $limits['subnet'];
				}
			}
		}
		// Check for group-specific permissions
		// If more than one group applies, use the group with the highest limit
		foreach ( $this->getGroups() as $group ) {
			if ( isset( $limits[$group] ) ) {
				if ( $userLimit === false || $limits[$group] > $userLimit ) {
					$userLimit = $limits[$group];
				}
			}
		}
		// Set the user limit key
		if ( $userLimit !== false ) {
			list( $max, $period ) = $userLimit;
			wfDebug( __METHOD__ . ": effective user limit: $max in {$period}s\n" );
			$keys[wfMemcKey( 'limiter', $action, 'user', $id )] = $userLimit;
		}

		$triggered = false;
		foreach ( $keys as $key => $limit ) {
			list( $max, $period ) = $limit;
			$summary = "(limit $max in {$period}s)";
			$count = $wgMemc->get( $key );
			// Already pinged?
			if ( $count ) {
				if ( $count >= $max ) {
					wfDebug( __METHOD__ . ": tripped! $key at $count $summary\n" );
					if ( $wgRateLimitLog ) {
						wfSuppressWarnings();
						file_put_contents( $wgRateLimitLog, wfTimestamp( TS_MW ) . ' ' . wfWikiID() . ': ' . $this->getName() . " tripped $key at $count $summary\n", FILE_APPEND );
						wfRestoreWarnings();
					}
					$triggered = true;
				} else {
					wfDebug( __METHOD__ . ": ok. $key at $count $summary\n" );
				}
			} else {
				wfDebug( __METHOD__ . ": adding record for $key $summary\n" );
				if ( $incrBy > 0 ) {
					$wgMemc->add( $key, 0, intval( $period ) ); // first ping
				}
			}
			if ( $incrBy > 0 ) {
				$wgMemc->incr( $key, $incrBy );
			}
		}

		wfProfileOut( __METHOD__ );
		return $triggered;
	}
Пример #16
0
 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');
 }
Пример #17
0
function save_nic6(){
$sock=new sockets();
	$tpl=new templates();
	$ip=new IP();

	$nic=$_POST["ipv6-eth"];
	$tpl=new templates();
	$nics=new system_nic($nic);
	if($nics->dhcp==0){
		if(!$ip->isIPv6($_POST["ipv6addr"])){
			echo "{$_POST["ipv6addr"]} not a valid ipv6 address...\n";
			return;
		}
	}
	$nics->eth=$nic;
	$nics->ipv6=$_POST["ipv6-enable"];
	$nics->ipv6addr=$_POST["ipv6addr"];
	$nics->ipv6mask=$_POST["ipv6mask"];
	$nics->ipv6gw=$_POST["ipv6gw"];
	$nics->SaveNic();
	
}
Пример #18
0
function virtuals_addv6(){
	$sock=new sockets();
	$tpl=new templates();
	$ipclass=new IP();
	$ERROR_NO_PRIVS=$tpl->javascript_parse_text("{ERROR_NO_PRIVS}");
	$DisableNetworksManagement=$sock->GET_INFO("DisableNetworksManagement");
	if($DisableNetworksManagement==null){$DisableNetworksManagement=0;}		
	if($DisableNetworksManagement==1){echo $ERROR_NO_PRIVS;return;}	
	$NoGatewayForVirtualNetWork=$sock->GET_INFO("NoGatewayForVirtualNetWork");
	if(!is_numeric($NoGatewayForVirtualNetWork)){$NoGatewayForVirtualNetWork=0;}	
	if($_POST["nic"]==null){echo $tpl->_ENGINE_parse_body("{nic}=null");exit;}
	if($_POST["failover"]==1){
		$_POST["gateway"]=$_POST["virt-ipaddr"];
		$_POST["ForceGateway"]=0;
		
	}	
	
	if(!$ipclass->isIPv6($_POST["virt-ipaddr"])){
		echo "{$_POST["virt-ipaddr"]} is not an ipv6 ip address...";
		return;
	}
	
	if($NoGatewayForVirtualNetWork==1){$_POST["gateway"]=null;}
	$q=new mysql();
	if(!is_numeric($_POST["failover"])){$_POST["failover"]=0;}
	if(!is_numeric($_POST["ForceGateway"])){$_POST["ForceGateway"]=0;}
	
	if(!$q->FIELD_EXISTS("nics_virtuals","ForceGateway","artica_backup")){$sql="ALTER TABLE `nics_virtuals` ADD `ForceGateway` TINYINT( 1 ) NOT NULL";$q->QUERY_SQL($sql,'artica_backup');if(!$q->ok){echo $q->mysql_error."\n$sql\n";return;}}		
	if(!$q->FIELD_EXISTS("nics_virtuals","failover","artica_backup")){$sql="ALTER TABLE `nics_virtuals` ADD `failover` TINYINT( 1 ) NOT NULL,ADD INDEX ( `failover` )";$q->QUERY_SQL($sql,'artica_backup');if(!$q->ok){echo $q->mysql_error."\n$sql\n\n";return;}}
	if(!$q->FIELD_EXISTS("nics_virtuals","ipv6","artica_backup")){$sql="ALTER TABLE `nics_virtuals` ADD `ipv6` TINYINT( 1 ) NOT NULL,ADD INDEX ( `ipv6` )";$q->QUERY_SQL($sql,'artica_backup');if(!$q->ok){echo $q->mysql_error."\n$sql\n\n";return;}}	
	$sql="INSERT INTO nics_virtuals (nic,org,ipaddr,netmask,ipv6,gateway,ForceGateway,failover)
	VALUES('{$_POST["nic"]}','{$_POST["org"]}','{$_POST["virt-ipaddr"]}',
	'{$_POST["netmask"]}','1','{$_POST["gateway"]}',{$_POST["ForceGateway"]},{$_POST["failover"]});
	";	

	if($_POST["ID"]>0){
		$sql="UPDATE nics_virtuals SET nic='{$_POST["nic"]}',
		org='{$_POST["org"]}',
		ipaddr='{$_POST["virt-ipaddr"]}',
		netmask='{$_POST["netmask"]}',
		ipv6='1',
		gateway='{$_POST["gateway"]}',
		ForceGateway='{$_POST["ForceGateway"]}',
		failover='{$_POST["failover"]}'
		WHERE ID={$_POST["ID"]}";
	}
	writelogs("$sql",__FUNCTION__,__FILE__,__LINE__);
	
	$q->QUERY_SQL($sql,"artica_backup");
	if(!$q->ok){if(preg_match("#Unknown col#i", $q->mysql_error)){$q->BuildTables();$q->QUERY_SQL($sql,"artica_backup");}}
	if(!$q->ok){echo $q->mysql_error."\n$sql\n";}	
	
}
Пример #19
0
 /**
  * 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');
     }
 }
Пример #20
0
 /**
  * Returns the subnet of a given IP
  *
  * @param string $ip
  * @return string|false
  */
 public static function getSubnet($ip)
 {
     $matches = array();
     $subnet = false;
     if (IP::isIPv6($ip)) {
         $parts = IP::parseRange("{$ip}/64");
         $subnet = $parts[0];
     } elseif (preg_match('/^(\\d+\\.\\d+\\.\\d+)\\.\\d+$/', $ip, $matches)) {
         // IPv4
         $subnet = $matches[1];
     }
     return $subnet;
 }
Пример #21
0
 /**
  * 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;
 }
Пример #22
0
 /**
  * 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');
     }
 }
Пример #23
0
function instances_search()
{
    $tpl = new templates();
    $MyPage = CurrentPageName();
    $page = 1;
    $sock = new sockets();
    $ipClass = new IP();
    $DisableNetworksManagement = $sock->GET_INFO("DisableNetworksManagement");
    if (!is_numeric($DisableNetworksManagement)) {
        $DisableNetworksManagement = 0;
    }
    $GLOBALS["interfaces_LIST"] = unserialize(base64_decode($sock->getFrameWork("cmd.php?ifconfig-interfaces=yes")));
    $q = new mysql();
    if ($_GET["System"] == 1) {
        instances_system_search();
        return;
    }
    if (isset($_POST["sortname"])) {
        if ($_POST["sortname"] != null) {
            $ORDER = "ORDER BY {$_POST["sortname"]} {$_POST["sortorder"]}";
        }
    }
    if (isset($_POST['page'])) {
        $page = $_POST['page'];
    }
    $sql = "SELECT COUNT(*) as TCOUNT FROM postfix_multi WHERE (`key` = 'myhostname')";
    $ligne = mysql_fetch_array($q->QUERY_SQL($sql, "artica_backup"));
    $FullTotal = $ligne["TCOUNT"];
    if ($ligne["TCOUNT"] == 0) {
        json_error_show("No instance");
    }
    $query2 = "WHERE (`key` = 'myhostname')";
    if ($_POST["query"] != null) {
        $search = $_POST["query"];
        $search = "*" . $search . "*";
        $search = str_replace("**", "*", $search);
        $search = str_replace("*", "%", $search);
        if ($_POST["qtype"] == "hostname") {
            $query2 = "WHERE (`key` = 'myhostname' AND value LIKE '{$search}')";
        }
        if ($_POST["qtype"] == "organization") {
            $query2 = "WHERE (`key` = 'myhostname' AND ou LIKE '{$search}')";
        }
        if ($_POST["qtype"] == "ipaddr") {
            $query2 = "WHERE (`key` = 'myhostname' AND ip_address LIKE '{$search}')";
        }
        $sql = "SELECT COUNT(*) as TCOUNT FROM postfix_multi {$query2}";
        $ligne = mysql_fetch_array($q->QUERY_SQL($sql, "artica_backup"));
        if (!$q->ok) {
            json_error_show($q->mysql_error);
        }
        $FullTotal = $ligne["TCOUNT"];
        if ($FullTotal == 0) {
            json_error_show("No instance for {$search}");
        }
    }
    if (isset($_POST['rp'])) {
        $rp = $_POST['rp'];
    }
    $pageStart = ($page - 1) * $rp;
    $limitSql = "LIMIT {$pageStart}, {$rp}";
    $sql = "SELECT ou, ip_address, `key` , `value` FROM postfix_multi {$query2} {$limitSql}";
    writelogs($sql, __FUNCTION__, __FILE__, __LINE__);
    $q = new mysql();
    $results = $q->QUERY_SQL($sql, "artica_backup");
    if (!$q->ok) {
        json_error_show($q->mysql_error);
    }
    $data = array();
    $data['page'] = $page;
    $data['total'] = $FullTotal;
    $data['rows'] = array();
    $c = 0;
    while ($ligne = @mysql_fetch_array($results, MYSQL_ASSOC)) {
        $img = "<img src=img/24-idisk-server.png>";
        if ($ligne["ou"] == null) {
            $textou = "&nbsp;";
        } else {
            $textou = $ligne["ou"];
        }
        $instances[$c] = $ligne["value"];
        $strlen = strlen($ligne["value"]);
        if ($strlen > 33) {
            $hostname_text = substr($ligne["value"], 0, 33) . "...";
        } else {
            $hostname_text = $ligne["value"];
        }
        $maincf = new maincf_multi($ligne["value"]);
        $enabled = 1;
        $fontcolor = "black";
        if ($maincf->GET("DisabledInstance") == 1) {
            $enabled = 0;
            $fontcolor = "#B3B3B3";
            $img = "&nbsp;";
        }
        $md = md5($ligne["value"]);
        $href = "<a href=\"javascript:blur();\" \n\t\tOnClick=\"javascript:YahooWin('650','domains.postfix.multi.config.php?ou={$ligne["ou"]}&hostname={$ligne["value"]}','{$ligne["value"]}');\" \n\t\tstyle='font-size:16px;text-decoration:underline;color:{$fontcolor}'>";
        $md = md5($ligne["value"]);
        if (!$ipClass->isIPv6($ligne["ip_address"])) {
            $interface_img = InterfaceStatus($ligne["ip_address"]);
        } else {
            $interface_img = "22-win-nic.png";
        }
        $interface_text = "\n\t\t<table>\n\t\t<tr style=background-color:none;border:0px>\n\t\t\t<td width=1% valign=top style=border:0px><img src=img/{$interface_img}></td>\n\t\t\t<td style=border:0px><span style='font-size:16px;color:{$fontcolor};font-weight:bold'>{$href}{$ligne["ip_address"]}</a></span></td>\n\t\t</tr>\n\t\t</table>\n\t\t";
        $data['rows'][] = array('id' => "{$md}", 'cell' => array($img, "<span style='font-size:16px;color:{$fontcolor};font-weight:bold'>{$href}{$hostname_text}</a></span>", "<span style='font-size:16px;color:{$fontcolor};font-weight:bold'>{$href}{$textou}</a></span>", $interface_text, "<span style='font-size:16px;color:{$fontcolor};font-weight:bold'><input type='hidden' id='instanceStatus-{$c}' value='{$ligne["value"]}'><span id='instanceStatus-{$c}-tofill'></span></span>", "<span style='font-size:16px;color:{$fontcolor};font-weight:bold'>" . Field_checkbox("DisabledInstance_{$md}", 1, $enabled, "DisableInstance('{$ligne["value"]}','{$md}')") . "</span>", imgsimple("plus-24.png", "{create_new_instance_based_on_this_instance}", "DuplicateInstance('{$ligne["value"]}')"), imgsimple("delete-24.png", "{delete}", "POSTFIX_MULTI_INSTANCE_INFOS_DEL('{$ligne["ou"]}','{$ligne["ip_address"]}',{$md})")));
        $c++;
    }
    echo json_encode($data);
}