Create new firewall.

    TARGET: Id of the server the firewall will protect
495808
def cli(env, target, firewall_type, high_availability):
    

    mgr = SoftLayer.FirewallManager(env.client)

    if not env.skip_confirmations:
        if firewall_type == 'vlan':
            pkg = mgr.get_dedicated_package(ha_enabled=high_availability)
        elif firewall_type == 'vs':
            pkg = mgr.get_standard_package(target, is_virt=True)
        elif firewall_type == 'server':
            pkg = mgr.get_standard_package(target, is_virt=False)

        if not pkg:
            exceptions.CLIAbort(
                "Unable to add firewall - Is network public enabled?")

        env.out("******************")
        env.out("Product: %s" % pkg[0]['description'])
        env.out("Price: $%s monthly" % pkg[0]['prices'][0]['recurringFee'])
        env.out("******************")

        if not formatting.confirm("This action will incur charges on your "
                                  "account. Continue?"):
            raise exceptions.CLIAbort('Aborted.')

    if firewall_type == 'vlan':
        mgr.add_vlan_firewall(target, ha_enabled=high_availability)
    elif firewall_type == 'vs':
        mgr.add_standard_firewall(target, is_virt=True)
    elif firewall_type == 'server':
        mgr.add_standard_firewall(target, is_virt=False)

    env.fout("Firewall is being created!")
1074355
def create_fwrule(kwargs=None, call=None):
    '''
    
    '''
    if call != 'function':
        raise SaltCloudSystemExit(
            'The create_fwrule function must be called with -f or --function.'
        )

    if not kwargs or 'name' not in kwargs:
        log.error(
            'A name must be specified when creating a firewall rule.'
        )
        return False
    if 'allow' not in kwargs:
        log.error(
            'Must use "allow" to specify allowed protocols/ports.'
        )
        return False

    name = kwargs['name']
    network_name = kwargs.get('network', 'default')
    allow = _parse_allow(kwargs['allow'])
    src_range = kwargs.get('src_range', '0.0.0.0/0')
    src_tags = kwargs.get('src_tags', None)
    dst_tags = kwargs.get('dst_tags', None)

    if src_range:
        src_range = src_range.split(',')
    if src_tags:
        src_tags = src_tags.split(',')
    if dst_tags:
        dst_tags = dst_tags.split(',')
    conn = get_conn()

    __utils__['cloud.fire_event'](
        'event',
        'create firewall',
        'salt/cloud/firewall/creating',
        args={
            'name': name,
            'network': network_name,
            'allow': kwargs['allow'],
        },
        sock_dir=__opts__['sock_dir'],
        transport=__opts__['transport']
    )

    fwrule = conn.ex_create_firewall(
        name, allow,
        network=network_name,
        source_ranges=src_range,
        source_tags=src_tags,
        target_tags=dst_tags
    )

    __utils__['cloud.fire_event'](
        'event',
        'created firewall',
        'salt/cloud/firewall/created',
        args={
            'name': name,
            'network': network_name,
            'allow': kwargs['allow'],
        },
        sock_dir=__opts__['sock_dir'],
        transport=__opts__['transport']
    )
    return _expand_item(fwrule)
601083
def addServer(self, normalPort, sslPort, f, name):
        
        tcp = internet.TCPServer(normalPort, f)
        tcp.setName(name)
        self.servers.append(tcp)
        if sslPort is not None:
            ssl = internet.SSLServer(sslPort, f, contextFactory=self.sslfac)
            ssl.setName(name+'s')
            self.servers.append(ssl)
1025541
def create_dhcprelay_ipv6(self):
        """"""
        return DHCPRelayIPv6(
            self.networkapi_url,
            self.user,
            self.password,
            self.user_ldap)
1191400
def __make_server(self):
        ""
        notice('Making server, getting listening socket', self.color)
        self.mode = 's'
        sock = utils.get_server_sock()
        self.__s = sock
        with self.__client_list_lock:
            self.clients = deque()
        self.threads = deque()
        notice('Making beacon', self.color)
        b = Thread(target=self.__beacon_thread, name='beacon')
        b.start()
        self.threads.append(b)
        l = Thread(target=self.__listen_thread, name='listen')
        notice('Starting listen thread', self.color)
        l.start()
        self.threads.append(l)
1332999
def create(name, availability_zones, listeners, subnets=None,
           security_groups=None, scheme='internet-facing',
           region=None, key=None, keyid=None,
           profile=None):
    '''
    
    '''
    conn = _get_conn(region=region, key=key, keyid=keyid, profile=profile)
    if exists(name, region, key, keyid, profile):
        return True
    if isinstance(availability_zones, six.string_types):
        availability_zones = salt.utils.json.loads(availability_zones)

    if isinstance(listeners, six.string_types):
        listeners = salt.utils.json.loads(listeners)

    _complex_listeners = []
    for listener in listeners:
        _complex_listeners.append(listener_dict_to_tuple(listener))

    try:
        lb = conn.create_load_balancer(name=name, zones=availability_zones, subnets=subnets,
                                       security_groups=security_groups, scheme=scheme,
                                       complex_listeners=_complex_listeners)
        if lb:
            log.info('Created ELB %s', name)
            return True
        else:
            log.error('Failed to create ELB %s', name)
            return False
    except boto.exception.BotoServerError as error:
        log.error('Failed to create ELB %s: %s: %s',
                  name, error.error_code, error.message,
                  exc_info_on_loglevel=logging.DEBUG)
        return False
671223
def create_network(self, name, admin_state_up=True, router_ext=None, network_type=None, physical_network=None, segmentation_id=None, shared=None, vlan_transparent=None):
        '''
        
        '''
        body = {'name': name,
                'admin_state_up': admin_state_up}
        if router_ext:
            body['router:external'] = router_ext
        if network_type:
            body['provider:network_type'] = network_type
        if physical_network:
            body['provider:physical_network'] = physical_network
        if segmentation_id:
            body['provider:segmentation_id'] = segmentation_id
        if shared:
            body['shared'] = shared
        if vlan_transparent:
            body['vlan_transparent'] = vlan_transparent
        return self.network_conn.create_network(body={'network': body})
484983
def cli(env, identifier):
    """"""

    mgr = SoftLayer.FirewallManager(env.client)

    firewall_type, firewall_id = firewall.parse_id(identifier)
    if firewall_type == 'vlan':
        orig_rules = mgr.get_dedicated_fwl_rules(firewall_id)
    else:
        orig_rules = mgr.get_standard_fwl_rules(firewall_id)
    # open an editor for the user to enter their rules
    edited_rules = open_editor(rules=orig_rules)
    env.out(edited_rules)
    if formatting.confirm("Would you like to submit the rules. "
                          "Continue?"):
        while True:
            try:
                rules = parse_rules(edited_rules)
                if firewall_type == 'vlan':
                    rules = mgr.edit_dedicated_fwl_rules(firewall_id,
                                                         rules)
                else:
                    rules = mgr.edit_standard_fwl_rules(firewall_id,
                                                        rules)
                break
            except (SoftLayer.SoftLayerError, ValueError) as error:
                env.out("Unexpected error({%s})" % (error))
                if formatting.confirm("Would you like to continue editing "
                                      "the rules. Continue?"):
                    edited_rules = open_editor(content=edited_rules)
                    env.out(edited_rules)
                    if formatting.confirm("Would you like to submit the "
                                          "rules. Continue?"):
                        continue
                    else:
                        raise exceptions.CLIAbort('Aborted.')
                else:
                    raise exceptions.CLIAbort('Aborted.')
                env.fout('Firewall updated!')
    else:
        raise exceptions.CLIAbort('Aborted.')
980035
def cli(env, identifier):
    """"""

    mgr = SoftLayer.FirewallManager(env.client)

    firewall_type, firewall_id = firewall.parse_id(identifier)
    if firewall_type == 'vlan':
        rules = mgr.get_dedicated_fwl_rules(firewall_id)
    else:
        rules = mgr.get_standard_fwl_rules(firewall_id)

    env.fout(get_rules_table(rules))
480826
def SetServerInformation(self, server, port):
    
    self._host = server
    self._port = port
1267538
def create_ip(self):
        """"""
        return Ip(
            self.networkapi_url,
            self.user,
            self.password,
            self.user_ldap)
873921
def update_firewall(self, firewall, body=None):
        """"""
        return self.put(self.firewall_path % (firewall), body=body)
568094
def create(self, create_missing=None):
        
        return type(self)(
            self._server_config,
            id=self.create_json(create_missing)['id'],
        ).read()
1089924
def delete_firewall_rule(self, server_uuid, firewall_rule_position):
        
        url = '/server/{0}/firewall_rule/{1}'.format(server_uuid, firewall_rule_position)
        return self.request('DELETE', url)
1184418
def create(self, environment, target_name):
        
        remote_server_command(
            ["ssh", environment.deploy_target, "create", target_name],
            environment, self,
            clean_up=True,
            )
530404
def add_server(self, name, ip, port):
        """"""
        new_server = {
            'key': name,  # Zeroconf name with both hostname and port
            'name': name.split(':')[0],  # Short name
            'ip': ip,  # IP address seen by the client
            'port': port,  # TCP port
            'username': 'glances',  # Default username
            'password': '',  # Default password
            'status': 'UNKNOWN',  # Server status: 'UNKNOWN', 'OFFLINE', 'ONLINE', 'PROTECTED'
            'type': 'DYNAMIC'}  # Server type: 'STATIC' or 'DYNAMIC'
        self._server_list.append(new_server)
        logger.debug("Updated servers list (%s servers): %s" %
                     (len(self._server_list), self._server_list))
180983
def create(self):
        
        retries_left = self.MAX_RETRIES

        # The server may close the connection at any time, causing the auth key creation to fail.
        # If that happens, just try again up to MAX_RETRIES times.
        while True:
            self.connection = Connection(self.dc_id, self.test_mode, self.ipv6, self.proxy)

            try:
                log.info("Start creating a new auth key on DC{}".format(self.dc_id))

                self.connection.connect()

                # Step 1; Step 2
                nonce = int.from_bytes(urandom(16), "little", signed=True)
                log.debug("Send req_pq: {}".format(nonce))
                res_pq = self.send(functions.ReqPqMulti(nonce=nonce))
                log.debug("Got ResPq: {}".format(res_pq.server_nonce))
                log.debug("Server public key fingerprints: {}".format(res_pq.server_public_key_fingerprints))

                for i in res_pq.server_public_key_fingerprints:
                    if i in RSA.server_public_keys:
                        log.debug("Using fingerprint: {}".format(i))
                        public_key_fingerprint = i
                        break
                    else:
                        log.debug("Fingerprint unknown: {}".format(i))
                else:
                    raise Exception("Public key not found")

                # Step 3
                pq = int.from_bytes(res_pq.pq, "big")
                log.debug("Start PQ factorization: {}".format(pq))
                start = time.time()
                g = Prime.decompose(pq)
                p, q = sorted((g, pq // g))  # p < q
                log.debug("Done PQ factorization ({}s): {} {}".format(round(time.time() - start, 3), p, q))

                # Step 4
                server_nonce = res_pq.server_nonce
                new_nonce = int.from_bytes(urandom(32), "little", signed=True)

                data = types.PQInnerData(
                    pq=res_pq.pq,
                    p=p.to_bytes(4, "big"),
                    q=q.to_bytes(4, "big"),
                    nonce=nonce,
                    server_nonce=server_nonce,
                    new_nonce=new_nonce,
                ).write()

                sha = sha1(data).digest()
                padding = urandom(- (len(data) + len(sha)) % 255)
                data_with_hash = sha + data + padding
                encrypted_data = RSA.encrypt(data_with_hash, public_key_fingerprint)

                log.debug("Done encrypt data with RSA")

                # Step 5. TODO: Handle "server_DH_params_fail". Code assumes response is ok
                log.debug("Send req_DH_params")
                server_dh_params = self.send(
                    functions.ReqDHParams(
                        nonce=nonce,
                        server_nonce=server_nonce,
                        p=p.to_bytes(4, "big"),
                        q=q.to_bytes(4, "big"),
                        public_key_fingerprint=public_key_fingerprint,
                        encrypted_data=encrypted_data
                    )
                )

                encrypted_answer = server_dh_params.encrypted_answer

                server_nonce = server_nonce.to_bytes(16, "little", signed=True)
                new_nonce = new_nonce.to_bytes(32, "little", signed=True)

                tmp_aes_key = (
                    sha1(new_nonce + server_nonce).digest()
                    + sha1(server_nonce + new_nonce).digest()[:12]
                )

                tmp_aes_iv = (
                    sha1(server_nonce + new_nonce).digest()[12:]
                    + sha1(new_nonce + new_nonce).digest() + new_nonce[:4]
                )

                server_nonce = int.from_bytes(server_nonce, "little", signed=True)

                answer_with_hash = AES.ige256_decrypt(encrypted_answer, tmp_aes_key, tmp_aes_iv)
                answer = answer_with_hash[20:]

                server_dh_inner_data = Object.read(BytesIO(answer))

                log.debug("Done decrypting answer")

                dh_prime = int.from_bytes(server_dh_inner_data.dh_prime, "big")
                delta_time = server_dh_inner_data.server_time - time.time()

                log.debug("Delta time: {}".format(round(delta_time, 3)))

                # Step 6
                g = server_dh_inner_data.g
                b = int.from_bytes(urandom(256), "big")
                g_b = pow(g, b, dh_prime).to_bytes(256, "big")

                retry_id = 0

                data = types.ClientDHInnerData(
                    nonce=nonce,
                    server_nonce=server_nonce,
                    retry_id=retry_id,
                    g_b=g_b
                ).write()

                sha = sha1(data).digest()
                padding = urandom(- (len(data) + len(sha)) % 16)
                data_with_hash = sha + data + padding
                encrypted_data = AES.ige256_encrypt(data_with_hash, tmp_aes_key, tmp_aes_iv)

                log.debug("Send set_client_DH_params")
                set_client_dh_params_answer = self.send(
                    functions.SetClientDHParams(
                        nonce=nonce,
                        server_nonce=server_nonce,
                        encrypted_data=encrypted_data
                    )
                )

                # TODO: Handle "auth_key_aux_hash" if the previous step fails

                # Step 7; Step 8
                g_a = int.from_bytes(server_dh_inner_data.g_a, "big")
                auth_key = pow(g_a, b, dh_prime).to_bytes(256, "big")
                server_nonce = server_nonce.to_bytes(16, "little", signed=True)

                # TODO: Handle errors

                #######################
                # Security checks
                #######################

                assert dh_prime == Prime.CURRENT_DH_PRIME
                log.debug("DH parameters check: OK")

                # https://core.telegram.org/mtproto/security_guidelines#g-a-and-g-b-validation
                g_b = int.from_bytes(g_b, "big")
                assert 1 < g < dh_prime - 1
                assert 1 < g_a < dh_prime - 1
                assert 1 < g_b < dh_prime - 1
                assert 2 ** (2048 - 64) < g_a < dh_prime - 2 ** (2048 - 64)
                assert 2 ** (2048 - 64) < g_b < dh_prime - 2 ** (2048 - 64)
                log.debug("g_a and g_b validation: OK")

                # https://core.telegram.org/mtproto/security_guidelines#checking-sha1-hash-values
                answer = server_dh_inner_data.write()  # Call .write() to remove padding
                assert answer_with_hash[:20] == sha1(answer).digest()
                log.debug("SHA1 hash values check: OK")

                # https://core.telegram.org/mtproto/security_guidelines#checking-nonce-server-nonce-and-new-nonce-fields
                # 1st message
                assert nonce == res_pq.nonce
                # 2nd message
                server_nonce = int.from_bytes(server_nonce, "little", signed=True)
                assert nonce == server_dh_params.nonce
                assert server_nonce == server_dh_params.server_nonce
                # 3rd message
                assert nonce == set_client_dh_params_answer.nonce
                assert server_nonce == set_client_dh_params_answer.server_nonce
                server_nonce = server_nonce.to_bytes(16, "little", signed=True)
                log.debug("Nonce fields check: OK")

                # Step 9
                server_salt = AES.xor(new_nonce[:8], server_nonce[:8])

                log.debug("Server salt: {}".format(int.from_bytes(server_salt, "little")))

                log.info(
                    "Done auth key exchange: {}".format(
                        set_client_dh_params_answer.__class__.__name__
                    )
                )
            except Exception as e:
                if retries_left:
                    retries_left -= 1
                else:
                    raise e

                time.sleep(1)
                continue
            else:
                return auth_key
            finally:
                self.connection.close()