#!/usr/bin/python2

# 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 selinux
import semanage

# 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.

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 the arguments

# Fail if they are not set correctly.

# Check the port in policy
h = semanage.semanage_handle_create()
semanage.semanage_connect(h)
# This could check high / low values, but eh.
(r, k) = semanage.semanage_port_key_create(h, port, port, semanage.SEMANAGE_PROTO_TCP)

# Do I need to check _local too?
(t, e) = semanage.semanage_port_exists(h, k)

if label is None:
    sys.exit(e)

# See if it has a specifc label

if (e == 0):
    # No point checking the label, it doesn't exist
    sys.exit(e)

(t, sp) = semanage.semanage_port_query(h, k)

# do we need to check if this is none? We already know that the port exists, so it must have a context ...
r = semanage.semanage_port_get_con(sp)

if label == semanage.semanage_context_get_type(r):
    sys.exit(1)

else:
    sys.stderr.write('Port belongs to %s\n' % semanage.semanage_context_get_type(r))
    sys.exit(2)

