#!/usr/bin/python3

# BEGIN COPYRIGHT BLOCK
# Copyright (C) 2016 Red Hat, Inc.
# All rights reserved.
#
# License: GPL (version 3 or any later version).
# See LICENSE for details.
# END COPYRIGHT BLOCK
#

import sys
import sepolicy

# These are python 3 capable, but el7 doesn't have libsemanage-python3

# Given a port number as the first argument, determine if it's already part of the policy.
# The second (optional) argument is a label type to check.

# 0 for does not exist in policy. 1 mean exists (with no label)
# or if a lable is given, exists AND inside of label type.
# 2 means port exists but belongs to a different type.

# Get the arguments
# Fail if they are not set correctly.
if len(sys.argv) <= 1:
    sys.stderr.write("Must provide port to query\n")
    sys.exit(512)

port = int(sys.argv[1])
label = None
try:
    label = sys.argv[2]
except:
    pass

# Get all defined ports from the policy
portrecs, portrecsbynum = sepolicy.gen_port_dict()
all_ports = []
for i in portrecs:
    if i[0] not in all_ports:
        all_ports.append(i[0])
all_ports.sort()

found = False
for i in portrecsbynum:
    # Check if the port is in range
    if i[0] <= port and port <= i[1] and 'tcp' == i[2]:
        # See if it has a specific label
        # Ignore default label types
        if portrecsbynum[i][0] not in ['unreserved_port_t', 'reserved_port_t',
                                       'ephemeral_port_t']:
            # Port exists within our label type or exists if none is given
            if label == portrecsbynum[i][0] or label == None:
                found = True
                sys.exit(1)
            else:
                sys.stderr.write("Port belongs to {}\n".format(portrecsbynum[i][0]))
                sys.exit(2)
if not found:
        sys.exit(0)
