Add an rule to the temporary ip allow list.
    See :func:`_access_rule`.
    1- Add an IP:
    CLI Example:

    .. code-block:: bash

        salt '*' csf.tempallow 127.0.0.1 3600 port=22 direction='in' comment='# Temp dev ssh access'
194584
def tempallow(ip=None, ttl=None, port=None, direction=None, comment=''):
    '''
    
    '''
    return _tmp_access_rule('tempallow', ip, ttl, port, direction, comment)
947166
def update_firewall_rule(self, firewall_rule, protocol=None, action=None,
                             name=None, description=None, ip_version=None,
                             source_ip_address=None, destination_ip_address=None, source_port=None,
                             destination_port=None, shared=None, enabled=None):
        '''
        
        '''
        body = {}
        if protocol:
            body['protocol'] = protocol
        if action:
            body['action'] = action
        if name:
            body['name'] = name
        if description:
            body['description'] = description
        if ip_version:
            body['ip_version'] = ip_version
        if source_ip_address:
            body['source_ip_address'] = source_ip_address
        if destination_ip_address:
            body['destination_ip_address'] = destination_ip_address
        if source_port:
            body['source_port'] = source_port
        if destination_port:
            body['destination_port'] = destination_port
        if shared:
            body['shared'] = shared
        if enabled:
            body['enabled'] = enabled
        return self.network_conn.update_firewall_rule(firewall_rule, body={'firewall_rule': body})
364701
def command_freeze(session_name, socket_name, socket_path):
    """"""

    t = Server(socket_name=socket_name, socket_path=socket_path)

    try:
        session = t.find_where({'session_name': session_name})

        if not session:
            raise exc.TmuxpException('Session not found.')
    except exc.TmuxpException as e:
        print(e)
        return

    sconf = freeze(session)
    configparser = kaptan.Kaptan()
    newconfig = config.inline(sconf)
    configparser.import_config(newconfig)
    config_format = click.prompt(
        'Convert to', value_proc=_validate_choices(['yaml', 'json']), default='yaml'
    )

    if config_format == 'yaml':
        newconfig = configparser.export(
            'yaml', indent=2, default_flow_style=False, safe=True
        )
    elif config_format == 'json':
        newconfig = configparser.export('json', indent=2)
    else:
        sys.exit('Unknown config format.')

    print(newconfig)
    print(
        '---------------------------------------------------------------'
        '\n'
        'Freeze does it best to snapshot live tmux sessions.\n'
    )
    if click.confirm(
        'The new config *WILL* require adjusting afterwards. Save config?'
    ):
        dest = None
        while not dest:
            save_to = os.path.abspath(
                os.path.join(
                    get_config_dir(),
                    '%s.%s' % (sconf.get('session_name'), config_format),
                )
            )
            dest_prompt = click.prompt(
                'Save to: %s' % save_to,
                value_proc=get_abs_path,
                default=save_to,
                confirmation_prompt=True,
            )
            if os.path.exists(dest_prompt):
                print('%s exists. Pick a new filename.' % dest_prompt)
                continue

            dest = dest_prompt

        dest = os.path.abspath(os.path.relpath(os.path.expanduser(dest)))
        if click.confirm('Save to %s?' % dest):
            destdir = os.path.dirname(dest)
            if not os.path.isdir(destdir):
                os.makedirs(destdir)
            buf = open(dest, 'w')
            buf.write(newconfig)
            buf.close()

            print('Saved to %s.' % dest)
    else:
        print(
            'tmuxp has examples in JSON and YAML format at '
            '<http://tmuxp.readthedocs.io/en/latest/examples.html>\n'
            'View tmuxp docs at <http://tmuxp.readthedocs.io/>.'
        )
        sys.exit()
1107847
def create_firewall_rule(self, server, firewall_rule_body):
        
        server_uuid, server_instance = uuid_and_instance(server)

        url = '/server/{0}/firewall_rule'.format(server_uuid)
        body = {'firewall_rule': firewall_rule_body}
        res = self.post_request(url, body)

        return FirewallRule(server=server_instance, **res['firewall_rule'])
682863
def _make_tmp_path(self, conn):
        '''  '''

        basefile = 'ansible-%s-%s' % (time.time(), random.randint(0, 2**48))
        basetmp = os.path.join(C.DEFAULT_REMOTE_TMP, basefile)
        if self.sudo and self.sudo_user != 'root':
            basetmp = os.path.join('/tmp', basefile)

        cmd = 'mkdir -p %s' % basetmp
        if self.remote_user != 'root':
            cmd += ' && chmod a+rx %s' % basetmp
        cmd += ' && echo %s' % basetmp

        result = self._low_level_exec_command(conn, cmd, None, sudoable=False)
        rc = utils.last_non_blank_line(result['stdout']).strip() + '/'
        return rc
197963
def _format_rule(self, protocol, cidr, min_port, max_port, direction):
        """"""
        if cidr is None:
            cidr = 'any'

        if direction == n_const.INGRESS_DIRECTION:
            dst_ip = 'any'
            src_ip = cidr
        elif direction == n_const.EGRESS_DIRECTION:
            dst_ip = cidr
            src_ip = 'any'

        if protocol == n_const.PROTO_NAME_ICMP:
            rule = "permit icmp %s %s" % (src_ip, dst_ip)
            if min_port:
                rule += " %s" % (min_port)
                if max_port:
                    rule += " %s" % (max_port)
        else:
            rule = "permit %s %s %s" % (protocol, src_ip, dst_ip)
            if min_port and max_port:
                rule += " range %s %s" % (min_port, max_port)
            elif min_port and not max_port:
                rule += " eq %s" % min_port
        return rule
47216
def floating_ip_associate(name, kwargs, call=None):
    '''
    
    '''
    if call != 'action':
        raise SaltCloudSystemExit(
            'The floating_ip_associate action must be called with -a of --action.'
        )

    if 'floating_ip' not in kwargs:
        log.error('floating_ip is required')
        return False

    conn = get_conn()
    conn.floating_ip_associate(name, kwargs['floating_ip'])
    return list_nodes()[name]
508290
def add_host(zone, name, ttl, ip, keyname, keyfile, nameserver, timeout,
             port=53, keyalgorithm='hmac-md5'):
    '''
    
    '''
    res = []
    if zone in name:
        name = name.replace(zone, '').rstrip('.')
    fqdn = '{0}.{1}'.format(name, zone)

    ret = create(zone, name, ttl, 'A', ip, keyname, keyfile, nameserver,
                 timeout, port, keyalgorithm)
    res.append(ret[fqdn])

    parts = ip.split('.')[::-1]
    i = len(parts)
    popped = []

    # Iterate over possible reverse zones
    while i > 1:
        p = parts.pop(0)
        i -= 1
        popped.append(p)

        zone = '{0}.{1}'.format('.'.join(parts), 'in-addr.arpa.')
        name = '.'.join(popped)
        rev_fqdn = '{0}.{1}'.format(name, zone)
        ret = create(zone, name, ttl, 'PTR', "{0}.".format(fqdn), keyname,
                     keyfile, nameserver, timeout, port, keyalgorithm)

        if "Created" in ret[rev_fqdn]:
            res.append(ret[rev_fqdn])
            return {fqdn: res}

    res.append(ret[rev_fqdn])

    return {fqdn: res}
775608
def add_host(ip, alias):
    '''
    
    '''
    hfn = _get_or_create_hostfile()
    if not os.path.isfile(hfn):
        return False

    if has_pair(ip, alias):
        return True

    hosts = _list_hosts()

    # Make sure future calls to _list_hosts() will re-read the file
    __context__.pop('hosts._list_hosts', None)

    inserted = False
    for i, h in six.iteritems(hosts):
        for j in range(len(h)):
            if h[j].startswith('#') and i == ip:
                h.insert(j, alias)
                inserted = True
    if not inserted:
        hosts.setdefault(ip, []).append(alias)
    _write_hosts(hosts)
    return True
978738
def list_port_fwd(zone, permanent=True):
    '''
    
    '''
    ret = []

    cmd = '--zone={0} --list-forward-ports'.format(zone)

    if permanent:
        cmd += ' --permanent'

    for i in __firewall_cmd(cmd).splitlines():
        (src, proto, dest, addr) = i.split(':')

        ret.append(
            {'Source port': src.split('=')[1],
             'Protocol': proto.split('=')[1],
             'Destination port': dest.split('=')[1],
             'Destination address': addr.split('=')[1]}
        )

    return ret
675320
def create_firewall_rule(self, protocol, action, **kwargs):
        '''
        
        '''
        body = {'protocol': protocol, 'action': action}
        if 'tenant_id' in kwargs:
            body['tenant_id'] = kwargs['tenant_id']
        if 'name' in kwargs:
            body['name'] = kwargs['name']
        if 'description' in kwargs:
            body['description'] = kwargs['description']
        if 'ip_version' in kwargs:
            body['ip_version'] = kwargs['ip_version']
        if 'source_ip_address' in kwargs:
            body['source_ip_address'] = kwargs['source_ip_address']
        if 'destination_port' in kwargs:
            body['destination_port'] = kwargs['destination_port']
        if 'shared' in kwargs:
            body['shared'] = kwargs['shared']
        if 'enabled' in kwargs:
            body['enabled'] = kwargs['enabled']
        return self.network_conn.create_firewall_rule(body={'firewall_rule': body})
716148
def cmd(send, msg, args):
    
    parser = arguments.ArgParser(args['config'])
    parser.add_argument('--nick', action=arguments.NickParser, required=True)
    parser.add_argument('--role', choices=['admin'], required=True)
    group = parser.add_mutually_exclusive_group(required=True)
    group.add_argument('--add', action='store_true')
    group.add_argument('--remove', action='store_true')
    try:
        cmdargs = parser.parse_args(msg)
    except arguments.ArgumentException as e:
        send(str(e))
        return
    session = args['db']
    admin = session.query(Permissions).filter(Permissions.nick == cmdargs.nick).first()
    if cmdargs.add:
        if admin is None:
            session.add(Permissions(nick=cmdargs.nick, role=cmdargs.role))
            send("%s is now an %s." % (cmdargs.nick, cmdargs.role))
        else:
            send("%s is already an %s." % (admin.nick, admin.role))
    else:
        if admin is None:
            send("%s was not an %s." % (cmdargs.nick, cmdargs.role))
        else:
            session.delete(admin)
            send("%s is no longer an %s." % (admin.nick, admin.role))
977330
def add_access_control_headers(self, env=None):
        
        allowed_methods = 'GET, POST, PUT, OPTIONS, DELETE, PATCH, HEAD, TRACE, CONNECT'
        allowed_origin = None
        if env is not None:
            acr_method = env.get('HTTP_ACCESS_CONTROL_REQUEST_METHOD')
            if acr_method is not None and acr_method not in allowed_methods:
                allowed_methods = allowed_methods + ', ' + acr_method
            r_method = env.get('REQUEST_METHOD')
            if r_method is not None and r_method not in allowed_methods:
                allowed_methods = allowed_methods + ', ' + r_method
            acr_headers = env.get('HTTP_ACCESS_CONTROL_REQUEST_HEADERS')
            if acr_headers is not None:
                self.status_headers.add_header('Access-Control-Allow-Headers', acr_headers)
            allowed_origin = env.get('HTTP_ORIGIN', env.get('HTTP_REFERER', allowed_origin))
        if allowed_origin is None:
            allowed_origin = '*'
        self.status_headers.replace_header('Access-Control-Allow-Origin',  allowed_origin)
        self.status_headers.add_header('Access-Control-Allow-Methods', allowed_methods)
        self.status_headers.add_header('Access-Control-Allow-Credentials', 'true')
        self.status_headers.add_header('Access-Control-Max-Age', '1800')
        return self
1206342
def list_port_forwarding_rules(ip_address_id=nil, listall=false)
      params = { 'command' => 'listPortForwardingRules' }
      params['ipAddressId'] = ip_address_id if ip_address_id
      params['listall'] = listall
      json = send_request(params)
      json['portforwardingrule']
    end
550520
def _port_add_or_delete_policy(action, name, sel_type=None, protocol=None, port=None, sel_range=None):
    '''
    
    '''
    if action not in ['add', 'delete']:
        raise SaltInvocationError('Actions supported are "add" and "delete", not "{0}".'.format(action))
    if action == 'add' and not sel_type:
        raise SaltInvocationError('SELinux Type is required to add a policy')
    (protocol, port) = _parse_protocol_port(name, protocol, port)
    cmd = 'semanage port --{0} --proto {1}'.format(action, protocol)
    if sel_type:
        cmd += ' --type {0}'.format(sel_type)
    if sel_range:
        cmd += ' --range {0}'.format(sel_range)
    cmd += ' {0}'.format(port)
    return __salt__['cmd.run_all'](cmd)
866495
def update_ip_rule(self, ip, mac):
        """"""

        rule_no = self._find_rule_no(mac)
        chain = self._find_chain_name(mac)
        if not rule_no or not chain:
            LOG.error('Failed to update ip rule for %(ip)s %(mac)s',
                      {'ip': ip, 'mac': mac})
            return

        update_cmd = ['iptables', '-R', '%s' % chain, '%s' % rule_no,
                      '-s', '%s/32' % ip, '-m', 'mac', '--mac-source',
                      '%s' % mac, '-j', 'RETURN']
        LOG.debug('Execute command: %s', update_cmd)
        dsl.execute(update_cmd, self._root_helper, log_output=False)
327408
def salt_ssh(project, target, module, args=None, kwargs=None):
    
    cmd = ['salt-ssh']
    cmd.extend(generate_salt_cmd(target, module, args, kwargs))
    cmd.append('--state-output=mixed')
    cmd.append('--roster-file=%s' % project.roster_path)
    cmd.append('--config-dir=%s' % project.salt_ssh_config_dir)
    cmd.append('--ignore-host-keys')
    cmd.append('--force-color')
    cmd = ' '.join(cmd)
    logger.debug('salt-ssh cmd: %s', cmd)

    proc = subprocess.Popen(cmd, shell=True, stdout=subprocess.PIPE, stderr=subprocess.PIPE)
    out, err = proc.communicate()
    if proc.returncode != 0 or err:
        raise Exception(err)
    return out + err