Exemplo n.º 1
0
def getVPNConnectionStatus():
    # Open the openvpn output file and parse it for known phrases
    # Return 'connected', 'auth failed', 'network failed', 'error' or ''

    if fakeConnection(): return connection_status.UNKNOWN

    # **** ADD MORE PLATFORMS HERE ****
    # Might not need to mess with this too much if the log output from openvpn is the same
    
    p = getPlatform()
    if p == platforms.LINUX or p == platforms.RPI:
        path = getVPNLogFilePath()
        state = connection_status.UNKNOWN
        if xbmcvfs.exists(path):
            debugTrace("Reading log file")
            log = open(path,'r')
            lines = log.readlines()
            for line in lines:
                if "Initialization Sequence Completed" in line:
                    state = connection_status.CONNECTED
                    break
                if "AUTH_FAILED" in line:
                    state = connection_status.AUTH_FAILED
                if "TLS Error" in line:
                    state = connection_status.NETWORK_FAILED
                if "Connection timed out" in line:
                    state = connection_status.TIMEOUT
            log.close()
            # Haven't found what's expected so return an empty stream
            if not state == connection_status.UNKNOWN: debugTrace("VPN connection status is " + str(state))
            return state
        else:
            errorTrace("platform.py", "Tried to get VPN connection status but log file didn't exist")
            return connection_status.ERROR
Exemplo n.º 2
0
def getIPInfo(addon):
    # Based this code on a routine in the VPN for OPENELEC plugin
    # Generate request to find out where this IP is based
    # Return ip info source, ip, location, isp
    source = addon.getSetting("ip_info_source")
    if not source in getIPSources():
        addon.setSetting("ip_info_source", getIPSources()[0])
        source == getIPSources()[0]

    debugTrace("Getting IP info from " + source)
    retry = 0
    while retry < 5:
        ip, country, region, city, isp = getIPInfoFrom(source)

        if ip == "no info":
            debugTrace("No location information was returned for IP using " + source)
            # Got a response but couldn't format it.  No point retrying
            return source, "no info", "unknown", "unknown"
        elif ip == "error":
            errorTrace("common.py", "Something bad happened when trying to get a response from iplocation.net " + isp)
            # Didn't get a valid response so want to retry three times in case service was busy
            if retry == 2 : return source + " (not available)", "unknown", "unknown", "unknown"
            xbmc.sleep(3000)            
        else:
            # Worked, exit loop
            break
        retry = retry + 1
        
    location = ""
    if not (region == "-" or region == "Not Available"): location = region
    if not (country == "-" or country == "Not Available"):
        if not location == "": location = location + ", "
        location = location + country

    return source, ip, location, isp
Exemplo n.º 3
0
def topLevel():
    # Build the top level menu with URL callbacks to this plugin
    debugTrace("Displaying the top level menu")
    url = base_url + "?settings"
    li = xbmcgui.ListItem("Add-on Settings", iconImage=getIconPath()+"settings.png")
    xbmcplugin.addDirectoryItem(handle=addon_handle, url=url, listitem=li)
    url = base_url + "?display"
    li = xbmcgui.ListItem("Display VPN status", iconImage=getIconPath()+"display.png")
    xbmcplugin.addDirectoryItem(handle=addon_handle, url=url, listitem=li)
    if addon.getSetting("vpn_system_menu_item") == "true":
        url = base_url + "?system"
        li = xbmcgui.ListItem("Display enhanced information", iconImage=getIconPath()+"enhanced.png")
        xbmcplugin.addDirectoryItem(handle=addon_handle, url=url, listitem=li, isFolder=True)
    url = base_url + "?list"
    li = xbmcgui.ListItem("Change or disconnect VPN connection", iconImage=getIconPath()+"locked.png")
    xbmcplugin.addDirectoryItem(handle=addon_handle, url=url, listitem=li, isFolder=True)
    url = base_url + "?cycle"
    li = xbmcgui.ListItem("Cycle through primary VPN connections", iconImage=getIconPath()+"cycle.png")
    xbmcplugin.addDirectoryItem(handle=addon_handle, url=url, listitem=li)
    url = base_url + "?switch"
    if isVPNMonitorRunning():
        li = xbmcgui.ListItem("Pause add-on filtering", iconImage=getIconPath()+"paused.png")
    else:
        li = xbmcgui.ListItem("Restart add-on filtering", iconImage=getIconPath()+"play.png")
    xbmcplugin.addDirectoryItem(handle=addon_handle, url=url, listitem=li)
    xbmcplugin.endOfDirectory(addon_handle)
    return
Exemplo n.º 4
0
def changeConnection():
    # Connect, or display status if we're already using selected VPN profile
    debugTrace("Changing connection to " + params + " from " + getVPNProfile() + ", connected:" + str(isVPNConnected()))
    if isVPNConnected() and params == getVPNProfile():
        displayStatus()
    else:        
        connectVPN("0", params)
    return
Exemplo n.º 5
0
def displayStatus():
    _, ip, country, isp = getIPInfo(addon)
    if isVPNConnected():
        debugTrace("VPN is connected, displaying the connection info")
        xbmcgui.Dialog().ok(addon_name, "Connected to a VPN in " + country + ".\nUsing profile " + getVPNProfileFriendly() + ".\nExternal IP address is " + ip + ".\nService Provider is " + isp)
    else:
        debugTrace("VPN is not connected, displaying the connection info")
        xbmcgui.Dialog().ok(addon_name, "Disconnected from VPN.\nNetwork location is " + country + ".\nIP address is " + ip + ".\nService Provider is " + isp)
    return
Exemplo n.º 6
0
def disconnect():
    # Disconnect or display status if already disconnected
    debugTrace("Disconnect selected from connections menu")
    if isVPNConnected():
        disconnectVPN()
        setVPNState("off")
    else:
        displayStatus()
    return
Exemplo n.º 7
0
def updateVPNFiles(vpn_provider):
    # If the OVPN files aren't generated then they need to be updated with location info    
    
    infoTrace("vpnproviders.py", "Updating VPN profiles for " + vpn_provider)
    # Get the list of VPN profile files        
    ovpn_connections = getProfileList(vpn_provider)

    # See if there's a port override going on
    addon = xbmcaddon.Addon("service.vpn.manager")
    if addon.getSetting("default_udp") == "true":
        portUDP = ""
    else:
        portUDP = addon.getSetting("alternative_udp_port")
        
    if addon.getSetting("default_tcp") == "true":
        portTCP = ""
    else:
        portTCP = addon.getSetting("alternative_tcp_port")
    
    for connection in ovpn_connections:
        try:
            f = open(connection, 'r+')
            debugTrace("Processing file " + connection)
            lines = f.readlines()
            f.seek(0)
            f.truncate()
            # Update the necessary values in the ovpn file
            for line in lines:
                
                if "auth-user-pass" in line:
                    line = "auth-user-pass " + getAddonPathWrapper(vpn_provider + "/" + "pass.txt\n")

                if "remote " in line:
                    port = ""
                    for newline in lines:
                        if "proto " in newline:
                            if "tcp" in newline and not portTCP == "": port = portTCP
                            if "udp" in newline and not portUDP == "": port = portUDP
                    if not port == "":
                        tokens = line.split()
                        line = "remote " + tokens[1] + " " + port + "\n"
                           
                f.write(line)
            f.close()
        except:
            errorTrace("profileupdate.py", "Failed to update ovpn file")
            return False

    # Write a file to indicate successful update of the ovpn files
    ovpn_file = open(getAddonPath(True, vpn_provider + "/GENERATED.txt"), 'w')
    ovpn_file.close()
            
    return True    
    
Exemplo n.º 8
0
def switchService():
    debugTrace("Switching monitor state, current state is " + getVPNMonitorState())
    if isVPNMonitorRunning():
        setVPNMonitorState("Stopped")
        addon.setSetting("monitor_paused", "true")
        infoTrace("addon.py", "VPN monitor service paused")
    else:
        setVPNMonitorState("Started")
        addon.setSetting("monitor_paused", "false")
        infoTrace("addon.py", "VPN monitor service restarted")
    xbmc.executebuiltin('Container.Refresh')
    return
Exemplo n.º 9
0
def sendAPI(command, command_text, api_data, check_response):
    # Common routine to send an API command
    try:
        response = ""
        rc = True
        rest_url = REQUEST_URL + command
        
        auth_token,_,_,_ = getTokens()
        # Login again if the token is blank and the command is not login anyway
        if auth_token == "" and not "=login" in command:
            debugTrace("Logging in again because auth token not valid")
            addon = xbmcaddon.Addon(getID())
            rc = authenticateShellfire(addon.getSetting("vpn_provider"), addon.getSetting("vpn_username"), addon.getSetting("vpn_password"))
            auth_token,_,_,_ = getTokens()
            if auth_token == "" or not rc:
                raise Exception(command_text + " was not authorized")
        
        if ifHTTPTrace(): infoTrace("alternativeShellfire.py", command_text + " " + rest_url)     
        else: debugTrace(command_text)
        
        req = urllib2.Request(rest_url, api_data, REQUEST_HEADERS)
        if not auth_token == "": req.add_header("x-authorization-token", auth_token)
        t_before = now()
        response = urllib2.urlopen(req)
        api_data = json.load(response)   
        t_after = now()    
        response.close()

        # Trace if the command took a long time
        if ifJSONTrace(): infoTrace("alternativeShellfire.py", "JSON received is \n" + json.dumps(api_data, indent=4))
        if t_after - t_before > TIME_WARN: infoTrace("alternativeShellfire.py", command_text + " took " + str(t_after - t_before) + " seconds")
        
        # Check the response and fail if it's bad
        if check_response:
            if not api_data["status"] == "success":
                raise Exception(command_text + " returned bad response, " + api_data["status"])
        
    except urllib2.HTTPError as e:
        errorTrace("alternativeShellfire.py", command_text + " failed")
        errorTrace("alternativeShellfire.py", "API call was " + rest_url)
        if not api_data == "": errorTrace("alternativeShellfire.py", "Data returned was \n" + json.dumps(api_data, indent=4))
        errorTrace("alternativeShellfire.py", "Response was " + str(e.code) + " " + e.reason)
        errorTrace("alternativeShellfire.py", e.read())
        rc = False
    except Exception as e:
        errorTrace("alternativeShellfire.py", command_text + " failed")
        errorTrace("alternativeShellfire.py", "API call was " + rest_url)
        if not api_data == "": errorTrace("alternativeShellfire.py", "Data returned was \n" + json.dumps(api_data, indent=4))
        errorTrace("alternativeShellfire.py", "Response was " + str(type(e)) + " " + str(e))
        rc = False
    
    return rc, api_data
Exemplo n.º 10
0
def stopVPN():
    # Stop the platform VPN task.
    if not fakeConnection():
        p = getPlatform()
        if p == platforms.LINUX or p == platforms.RPI:
            command="killall -9 openvpn"            
            #if p == platforms.LINUX and use_sudo : command = "sudo " + command
            debugTrace("Stopping VPN with " + command)
            os.system(command)
            
        # **** ADD MORE PLATFORMS HERE ****
        
    return
Exemplo n.º 11
0
def fixOVPNFiles(vpn_provider, alternative_locations_name):
    debugTrace("Fixing OVPN files for " + vpn_provider + " using list " + alternative_locations_name)
    # Generate or update the VPN files
    if ovpnGenerated(vpn_provider):
        if not isUserDefined(vpn_provider):
            return generateOVPNFiles(vpn_provider, alternative_locations_name)
        else:
            # User Defined provider is a special case.  The files are copied from
            # userdata rather than generated as such, followed by an update (if needed)
            if copyUserDefinedFiles():
                return updateVPNFiles(vpn_provider)
    else:
        return updateVPNFiles(vpn_provider)
Exemplo n.º 12
0
def startService():
    # Routine for config to call to request that service starts.  Can time out if there's no response
    # Check to see if service is not already running (shouldn't be...)
    if not xbmcgui.Window(10000).getProperty("VPN_Manager_Service_Control") == "stopped": return True
    
    debugTrace("Requesting service restarts")
    # Update start property and wait for service to respond or timeout
    xbmcgui.Window(10000).setProperty("VPN_Manager_Service_Control", "start")
    for i in range (0, 30):
        xbmc.sleep(1000)
        if xbmcgui.Window(10000).getProperty("VPN_Manager_Service_Control") == "started": return True
    # No response in 30 seconds, service is probably dead
    errorTrace("common.py", "Couldn't communicate with VPN monitor service, didn't acknowledge a start")
    return False
Exemplo n.º 13
0
def stopService():
    # Routine for config to call to request service stops and waits until that happens
    # Check to see if the service has stopped previously
    if xbmcgui.Window(10000).getProperty("VPN_Manager_Service_Control") == "stopped": return True
    
    debugTrace("Requesting service stops")
    # Update start property and wait for service to respond or timeout
    xbmcgui.Window(10000).setProperty("VPN_Manager_Service_Control", "stop")
    for i in range (0, 30):
        xbmc.sleep(1000)
        if xbmcgui.Window(10000).getProperty("VPN_Manager_Service_Control") == "stopped": return True
    # Haven't had a response in 30 seconds which is badness
    errorTrace("common.py", "Couldn't communicate with VPN monitor service, didn't acknowledge a stop")
    return False
Exemplo n.º 14
0
def startVPN(vpn_profile):
    # Call the platform VPN to start the VPN
    if not fakeConnection():
        p = getPlatform()
        if p == platforms.RPI or p == platforms.LINUX:
            command=getOpenVPNPath() + " \"" + vpn_profile + "\" > " + getVPNLogFilePath() + " &"           
            debugTrace("Starting VPN with " + command)
            os.system(command)
            
        # **** ADD MORE PLATFORMS HERE ****
        
    else:
        # This bit is just to help with debug during development.
        command=getOpenVPNPath() + " \"" + vpn_profile + "\" > " + getVPNLogFilePath() + " &"
        debugTrace("Starting VPN with " + command)
    return
Exemplo n.º 15
0
def writeCert(vpn_provider, cert_name, content):
    # Write out the certificate represented by the content
    filename = getAddonPath(True, vpn_provider + "/" + cert_name)
    try:
        line = ""
        debugTrace("Writing certificate " + cert_name)
        output = open(filename, 'w')
        # Output the content line by line
        for line in content:       
            output.write(line)
        output.close()
        return True
    except Exception as e:
        errorTrace("alternativeShellfire`.py", "Couldn't write certificate " + filename)
        errorTrace("alternativeShellfire.py", str(e))
        return False
Exemplo n.º 16
0
def copyKeyAndCert(vpn_provider, ovpn_name, user_key, user_cert):
    # Copy the user key and cert to the userdata directory
    key_dest = getUserDataPath(vpn_provider + "/" + getKeyName(vpn_provider, ovpn_name))
    key_source = user_key
    cert_dest = getUserDataPath(vpn_provider + "/" + getCertName(vpn_provider, ovpn_name))
    cert_source = user_cert
    try:
        debugTrace("Copying key " + key_source + " to " + key_dest)
        if xbmcvfs.exists(key_dest): xbmcvfs.delete(key_dest)
        xbmcvfs.copy(key_source, key_dest)
        debugTrace("Copying cert " + cert_source + " to " + cert_dest)
        if xbmcvfs.exists(cert_dest): xbmcvfs.delete(cert_dest)
        xbmcvfs.copy(cert_source, cert_dest)
        return True
    except:
        errorTrace("vpnproviders.py", "Failed to copy user key or cert file to userdata")
        return False
Exemplo n.º 17
0
def getVPNConnectionStatus():
    # Open the openvpn output file and parse it for known phrases
    # Return 'connected', 'auth failed', 'network failed', 'error' or ''

    if fakeConnection():
        return connection_status.UNKNOWN

    # **** ADD MORE PLATFORMS HERE ****
    # Might not need to mess with this too much if the log output from different platform openvpns are the same

    p = getPlatform()
    if p == platforms.LINUX or p == platforms.RPI or p == platforms.WINDOWS:
        path = getVPNLogFilePath()
        state = connection_status.UNKNOWN
        if xbmcvfs.exists(path):
            debugTrace("Reading log file")
            log = open(path, "r")
            lines = log.readlines()
            for line in lines:
                if "Initialization Sequence Completed" in line:
                    state = connection_status.CONNECTED
                    break
                if "AUTH_FAILED" in line:
                    state = connection_status.AUTH_FAILED
                if "TLS Error" in line:
                    state = connection_status.NETWORK_FAILED
                if "Connection timed out" in line:
                    state = connection_status.TIMEOUT
                if p == platforms.WINDOWS and "ROUTE" in line and "Access is denied" in line:
                    # This is a Windows, not running Kodi as administrator error
                    state = connection_status.ACCESS_DENIED
                    break
                # if "ERROR: Linux route" in line:
                # state = connection_status.ROUTE_FAILED
                # This tests for a Linux route failure, only it's commented out as
                # it can legitimately fail if the route already exists.  If it fails
                # for other reasons, I can't tell the different just yet.
                # break
            log.close()
            # Haven't found what's expected so return an empty stream
            if not state == connection_status.UNKNOWN:
                debugTrace("VPN connection status is " + str(state))
            return state
        else:
            errorTrace("platform.py", "Tried to get VPN connection status but log file didn't exist")
            return connection_status.ERROR
Exemplo n.º 18
0
def checkForShellfireUpdates(vpn_provider):
    # See if the current stored tokens have changed
    addon = xbmcaddon.Addon(getID())
    current = addon.getSetting("vpn_locations_list")
    # If nothing has been selected/validated, then it doesn't matter if there's updates or not
    if current == "": return False
    # Likewise, if nothing is connected, then it doesn't matter yet
    if addon.getSetting("1_vpn_validated") == "": return False
    debugTrace("Checking for updates for " + current)
    # Get the list of services and see if the current ID is still the same
    services = getServices()
    if services == None: return False
    for s in services:
        # Look for the current service/id. If it's found nothing has been updated
        if s == current: return False
    # If we didn't find the service/id, then it's changed, so there are updates
    return True
Exemplo n.º 19
0
def writeCredentials(addon): 
   
    # Write the credentials file        
    try:
        credentials_path = getCredentialsPath(addon)
        debugTrace("Writing VPN credentials file to " + credentials_path)
        credentials = open(credentials_path,'w')
        credentials.truncate()
        credentials.close()
        credentials = open(credentials_path,'a')
        credentials.write(addon.getSetting("vpn_username")+"\n")
        credentials.write(addon.getSetting("vpn_password")+"\n")
        credentials.close()
    except:
        errorTrace("common.py", "Couldn't create credentials file " + credentials_path)
        return False
    xbmc.sleep(500)
    return True
Exemplo n.º 20
0
def getServices():
    # Get the list of services
    rc, api_data = sendAPI("?action=getAllVpnDetails", "Retrieving list of services", "", True)
    if not rc: return None
  
    # Extract and return the list of service levels the user is entitled to
    try:
        services = []
        service_list = ""
        for item in api_data["data"]:
            services.append(item["eAccountType"] +";" + str(item["iVpnId"]))
            service_list = service_list + item["eAccountType"] + ", (" + str(item["iVpnId"]) + ") "
        debugTrace("Found services " + service_list)
        return services
    except Exception as e:
        errorTrace("alternativeShellfire.py", "Couldn't parse the data that came back when listing the serice levels")
        errorTrace("alternativeShellfire.py", str(e))
        return None
Exemplo n.º 21
0
def listConnections():
    # Start with the disconnect option
    url = base_url + "?disconnect"
    if getVPNProfileFriendly() == "":
        li = xbmcgui.ListItem("[COLOR ffff0000](Disconnected)[/COLOR]", iconImage=getIconPath()+"disconnected.png")
    else:
        li = xbmcgui.ListItem("[COLOR ffff0000]Disconnect[/COLOR]", iconImage=getIconPath()+"unlocked.png")
    xbmcplugin.addDirectoryItem(handle=addon_handle, url=url, listitem=li)

    # We should have a VPN set up by now, but don't list if we haven't.
    vpn_provider = addon.getSetting("vpn_provider")
    debugTrace("Listing the connections available for " + vpn_provider)
    if vpn_provider != "":
        # Get the list of connections and add them to the directory
        all_connections = getAddonList(vpn_provider, "*.ovpn")
        ovpn_connections = getFilteredProfileList(all_connections, addon.getSetting("vpn_protocol"), None)
        connections = getFriendlyProfileList(ovpn_connections)
        inc = 0
        for connection in ovpn_connections:
            url = base_url + "?change?" + ovpn_connections[inc]
            conn_text = ""
            conn_primary = ""
            i=1
            # Adjust 10 and 11 below if changing number of conn_max
            while (i < 11):
                if addon.getSetting(str(i) + "_vpn_validated_friendly") == connections[inc] :
                    conn_primary = " (" + str(i) + ")"
                    i = 10
                i=i+1

            if getVPNProfileFriendly() == connections[inc] and isVPNConnected(): 
                conn_text = "[COLOR ff00ff00]" + connections[inc] + conn_primary + " (Connected)[/COLOR]"
                icon = getIconPath()+"connected.png"
            else:
                if not conn_primary == "":
                    conn_text = "[COLOR ff0099ff]" + connections[inc] + conn_primary + "[/COLOR]"
                else:
                    conn_text = connections[inc] + conn_primary
                icon = getIconPath()+"locked.png"                
            li = xbmcgui.ListItem(conn_text, iconImage=icon)
            xbmcplugin.addDirectoryItem(handle=addon_handle, url=url, listitem=li)
            inc = inc + 1
    xbmcplugin.endOfDirectory(addon_handle)            
    return
Exemplo n.º 22
0
def stopVPN():
    # Stop the platform VPN task.
    if not fakeConnection():
        p = getPlatform()
        if p == platforms.LINUX or p == platforms.RPI:
            command = "killall -9 openvpn"
            if useSudo():
                command = "sudo " + command
            debugTrace("(Linux) Stopping VPN with " + command)
            os.system(command)
        if p == platforms.WINDOWS:
            command = "taskkill /F /T /IM openvpn*"
            debugTrace("(Windows) Stopping VPN with " + command)
            args = shlex.split(command)
            proc = subprocess.Popen(args, creationflags=subprocess.SW_HIDE, shell=True)

        # **** ADD MORE PLATFORMS HERE ****

    return
Exemplo n.º 23
0
def stopVPNConnection():
    # Kill the running VPN task and reset the current VPN window properties
    setVPNProfile("")
    setVPNProfileFriendly("")
    debugTrace("Stopping VPN")

    # End any existing openvpn process
    waiting = True
    while waiting:
        # Send the kill command to end the openvpn process
        stopVPN()
    
        # Wait half a second just to make sure the process has time to die
        xbmc.sleep(500)

        # See if the openvpn process is still alive
        waiting = isVPNConnected()
            
    setVPNState("stopped")
    return
Exemplo n.º 24
0
def authenticateShellfire(vpn_provider, userid, password):
    # Authenticate with the API and store the tokens returned

    # If the same credentials have been used before, don't bother authenticating
    _,_,_, creds = getTokens()
    if creds == vpn_provider + userid + password: 
        debugTrace("Previous authentication was good")
        return True
    
    # Get the authentication token to use on future calls
    resetTokens()
    rc, api_data = sendAPI("?action=login", "Authenticating with VPN", '{"email":"' + userid + '", "password":"******"}', True)
    if not rc: return False
        
    # Extract the auth token and store it
    auth_token = api_data["data"]["token"]
    if not auth_token == None: 
        setTokens(auth_token, "", vpn_provider + userid + password)
        return True

    return False
Exemplo n.º 25
0
def isVPNTaskRunning():
    # Return True if the VPN task is still running, or the VPN connection is still active
    # Return False if the VPN task is no longer running and the connection is not active

    if fakeConnection():
        return True

    p = getPlatform()
    if p == platforms.LINUX or p == platforms.RPI:
        try:
            command = "pidof openvpn"
            if useSudo():
                command = "sudo " + command
            debugTrace("(Linux) Checking VPN task with " + command)
            pid = os.system(command)
            # This horrible call returns 0 if it finds a process, it's not returning the PID number
            if pid == 0:
                return True
            return False
        except:
            errorTrace("platform.py", "VPN task list failed")
            return False
    if p == platforms.WINDOWS:
        try:
            command = 'tasklist /FI "IMAGENAME eq OPENVPN.EXE"'
            debugTrace("(Windows) Checking VPN task with " + command)
            args = shlex.split(command)
            out = subprocess.check_output(args, creationflags=subprocess.SW_HIDE, shell=True).strip()
            if "openvpn.exe" in out:
                return True
            else:
                return False
        except:
            errorTrace("platform.py", "VPN task list failed")
            return False

    # **** ADD MORE PLATFORMS HERE ****

    return False
Exemplo n.º 26
0
def resetVPNConnections(addon):
    # Reset all connection information so the user is forced to revalidate everything
    infoTrace("resetVPN.py", "Resetting all validated VPN settings and disconnected existing VPN connections")
    
    forceCycleLock()
    
    resetVPNConfig(addon, 1)
    # Remove any last connect settings
    setVPNLastConnectedProfile("")
    setVPNLastConnectedProfileFriendly("")
        
    # Removal any password files that were created (they'll get recreated if needed)
    debugTrace("Deleting all pass.txt files")
    cleanPassFiles()
    
    # No need to stop/start monitor, just need to let it know that things have changed.
    # Because this is a reset of the VPN, the monitor should just work out it has no good connections
    updateService()
    debugTrace("Stopping any active VPN connections")
    stopVPNConnection()
    
    freeCycleLock()
    
    xbmcgui.Dialog().notification(addon.getAddonInfo("name"), "Disconnected", getIconPath()+"disconnected.png", 5000, False)
Exemplo n.º 27
0
def startVPNConnection(vpn_profile):  
    # Start the VPN, wait for connection, return the result

    startVPN(vpn_profile)
    debugTrace("Waiting for VPN to connect")
    i = 0
    loop_max = 77
    if fakeConnection(): loop_max = 2

    while i <= loop_max:
        xbmc.sleep(2000)
        state = getVPNConnectionStatus()
        if not state == connection_status.UNKNOWN: break
        i = i + 2

    if fakeConnection(): state = connection_status.CONNECTED
    
    if state == connection_status.CONNECTED:
        setVPNProfile(getVPNRequestedProfile())
        setVPNProfileFriendly(getVPNRequestedProfileFriendly())
        setVPNState("started")
        debugTrace("VPN connection to " + getVPNProfile() + " successful")

    return state
Exemplo n.º 28
0
def gotKeys(vpn_provider, ovpn_name):
    # Check to see if we have the key for this connection.  If this provider just uses
    # a single key then the getKey/CertName piece will work this out.  If no key is passed
    # in then we'll just report whether or not any keys exist for this provider
    if not ovpn_name == "":
        key_name = getUserDataPath(vpn_provider + "/" + getKeyName(vpn_provider, ovpn_name))
        cert_name = getUserDataPath(vpn_provider + "/" + getCertName(vpn_provider, ovpn_name))
        debugTrace("Checking for user key " + key_name)
        debugTrace("Checking for user cert " + cert_name)
        if xbmcvfs.exists(key_name) and xbmcvfs.exists(cert_name): return True
        debugTrace("One of the user key and cert files did not exist")
        return False
    else:
        return False
Exemplo n.º 29
0
def startVPN(vpn_profile):
    # Call the platform VPN to start the VPN
    if not fakeConnection():
        p = getPlatform()
        if p == platforms.RPI or p == platforms.LINUX:
            command = getOpenVPNPath() + ' "' + vpn_profile + '" > ' + getVPNLogFilePath() + " &"
            if useSudo():
                command = "sudo " + command
            debugTrace("(Linux) Starting VPN with " + command)
            os.system(command)
        if p == platforms.WINDOWS:
            command = getOpenVPNPath() + ' "' + vpn_profile + '"'
            debugTrace("(Windows) Starting VPN with " + command)
            args = shlex.split(command)
            outfile = open(getVPNLogFilePath(), "w")
            proc = subprocess.Popen(args, stdout=outfile, creationflags=subprocess.SW_HIDE, shell=True)

        # **** ADD MORE PLATFORMS HERE ****

    else:
        # This bit is just to help with debug during development.
        command = getOpenVPNPath() + ' "' + vpn_profile + '" > ' + getVPNLogFilePath()
        debugTrace("Faking starting VPN with " + command)
    return
Exemplo n.º 30
0
    def runRules(self, dialogs, group_mask, rules_mask):

        try:
            comm_delay = int(self.addon.getSetting("command_delay")) * 1000
        except:
            comm_delay = 10000
        #comm_delay = 1000

        if (not dialogs or xbmcgui.Dialog().yesno(
                self.addon_name,
                "About to take over the Kodi GUI.\n[B]You must avoid any input[/B] until the process is finished.\nAre you sure you want to continue?"
        )):

            api = None
            if xbmc.getCondVisibility("System.HasAddon(service.vpn.manager)"):
                try:
                    api = VPNAPI()
                except Exception as e:
                    errorTrace("service.py", "Couldn't connect to the VPN API")
                    errorTrace("service.py", str(e))
                    api = None

            if api == None:
                percent_adjust = 1
            else:
                percent_adjust = 3

            progDiag = xbmcgui.DialogProgressBG()
            progDiag.create("Running commands", "[B]Avoid any input![/B]")
            progDiag.update(0)
            xbmc.sleep(5000)

            rules = self.getRules(group_mask, rules_mask)

            if len(rules) > 0:

                percent = 0
                percent_inc = (100 / (len(rules) + percent_adjust))

                # Pause the VPN filtering
                if not api == None:
                    percent += percent_inc
                    progDiag.update(percent, "Pausing VPN filtering")
                    api.pause()
                xbmc.sleep(comm_delay)

                debugTrace("Running commands, rules group is " + group_mask +
                           " and mask is " + rules_mask)
                for rule in rules:
                    rule_group, rule_number, rule_title, rule_function, rule_addon, commands = parseRulesString(
                        rule)
                    debugTrace("Rule string is " + rule)
                    percent += percent_inc
                    if xbmc.getCondVisibility("System.HasAddon(" + rule_addon +
                                              ")"):
                        progDiag.update(
                            percent,
                            "Running " + rule_title + ", " + rule_function)
                        infoTrace(
                            "rules.py", "Running " + rule_number + ", " +
                            rule_title + ", " + rule_function)
                        xbmc.sleep(2000)
                        comm_percent = float(0)
                        comm_percent_inc = float(percent_inc) / float(
                            (len(commands) + 1))
                        for command in commands:
                            debugTrace("Executing " + command)
                            comm_percent += comm_percent_inc
                            progDiag.update(percent + int(comm_percent))
                            comm_delay_mod = 1
                            try:
                                if command.startswith("*"):
                                    comm_delay_mod = int(
                                        command[1:command.index(" ")])
                                    command = command[command.index(" ") +
                                                      1:].strip(" \t\n\r")
                                xbmc.executebuiltin(command)
                                xbmc.sleep(comm_delay * comm_delay_mod)
                            except Exception as e:
                                errorTrace("rules.py",
                                           "Couldn't run command " + command)
                                errorTrace("rules.py", str(e))
                                progDiag.update(
                                    percent,
                                    "[B]Error running command, check log[/B]")
                    else:
                        progDiag.update(percent, "Checking installed add-ons")
                        debugTrace("Couldn't find addon " + rule_addon)
                        xbmc.sleep(300)

                # Restart the VPN filtering
                if not api == None:
                    percent += percent_inc
                    progDiag.update(percent, "Restarting VPN filtering")
                    api.restart()
                    xbmc.sleep(comm_delay)

                progDiag.update(100, "Finished running rules", " ")
                xbmc.sleep(2000)
            else:
                progDiag.update(
                    100, "Couldn't find any rules for installed add-ons", " ")
                xbmc.sleep(5000)

            progDiag.close()
            xbmc.sleep(1000)
Exemplo n.º 31
0
        timeout = Timer(KeyListener.TIMEOUT, dialog.close)
        timeout.start()
        dialog.doModal()
        timeout.cancel()
        key = dialog.key
        del dialog
        if key == None: return ""
        return key


addon = xbmcaddon.Addon("service.zomboided.tools")
addon_name = addon.getAddonInfo("name")

action = sys.argv[1]

debugTrace("-- Entered mapkey.py with parameter " + action + " --")

sleep_key = ""

map_name = getKeyMapsFileName()
xml_start = '<keymap><global><keyboard>\n'
xml_key = '<key id="#KEY">runscript(#PATH#COMMAND)</key>\n'
xml_long = '<key id="#KEY" mod="longpress">runscript(#PATH#COMMAND)</key>\n'
xml_end = '</keyboard></global></keymap>\n'
sleep_command = "sleep.py"

# Fix the keymap if it's been renamed by the Keymap addon
fixKeymaps()

lines = []
Exemplo n.º 32
0
#!/usr/bin/python
# -*- coding: utf-8 -*-
#
#    Copyright (C) 2016 Zomboided
#
#    This program is free software: you can redistribute it and/or modify
#    it under the terms of the GNU General Public License as published by
#    the Free Software Foundation, either version 3 of the License, or
#    (at your option) any later version.
#
#    This program is distributed in the hope that it will be useful,
#    but WITHOUT ANY WARRANTY; without even the implied warranty of
#    MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE.  See the
#    GNU General Public License for more details.
#
#    You should have received a copy of the GNU General Public License
#    along with this program. If not, see <http://www.gnu.org/licenses/>.
#
#    This module does the same as calling the cycle function from the add-on
#    menu screen but allows a user to configure it to a button on a remote, etc

from libs.common import requestVPNCycle
from libs.utility import debugTrace, errorTrace, infoTrace


# Call the common cycle routine
debugTrace("-- Entered cycle.py --")
requestVPNCycle()
debugTrace("-- Exit cycle.py --")
Exemplo n.º 33
0
    @staticmethod
    def record_key():
        dialog = KeyListener()
        timeout = Timer(KeyListener.TIMEOUT, dialog.close)
        timeout.start()
        dialog.doModal()
        timeout.cancel()
        key = dialog.key
        del dialog
        if key == None: return ""
        return key


action = sys.argv[1]

debugTrace("-- Entered mapkey.py with parameter " + action + " --")

if not getID() == "":
    addon = xbmcaddon.Addon(getID())
    addon_name = getName()

    cycle_key = ""
    table_key = ""
    table_long = False
    info_key = ""

    map_name = getKeyMapsFileName()
    xml_start = '<keymap><global><keyboard>\n'
    xml_key = '<key id="#KEY">runscript(#PATH#COMMAND)</key>\n'
    xml_long = '<key id="#KEY" mod="longpress">runscript(#PATH#COMMAND)</key>\n'
    xml_end = '</keyboard></global></keymap>\n'
Exemplo n.º 34
0
def getUserCerts(vpn_provider):
    # Return the list of key and cert files for a given provider (aka directory name...)
    path = getUserDataPath(getVPNLocation(vpn_provider) + "/*.crt")
    debugTrace("Getting certificate files " + path)
    return (glob.glob(path))
Exemplo n.º 35
0
def updateVPNFiles(vpn_provider):
    # If the OVPN files aren't generated then they need to be updated with location info

    infoTrace("vpnproviders.py", "Updating VPN profiles for " + vpn_provider)
    # Get the list of VPN profile files
    ovpn_connections = getAddonList(vpn_provider, "*.ovpn")

    # See if there's a port override going on
    addon = xbmcaddon.Addon("service.vpn.manager")
    if addon.getSetting("default_udp") == "true":
        portUDP = ""
    else:
        portUDP = addon.getSetting("alternative_udp_port")

    if addon.getSetting("default_tcp") == "true":
        portTCP = ""
    else:
        portTCP = addon.getSetting("alternative_tcp_port")

    # Get the logging level
    verb_value = addon.getSetting("openvpn_verb")
    if verb_value == "":
        verb_value = "1"
        addon.setSetting("openvpn_verb", verb_value)

    for connection in ovpn_connections:
        try:
            f = open(connection, 'r+')
            debugTrace("Processing file " + connection)
            lines = f.readlines()
            f.seek(0)
            f.truncate()
            # Get the profile friendly name in case we need to generate key/cert names
            name = connection[connection.rfind(getSeparator()) + 1:]
            # Update the necessary values in the ovpn file
            for line in lines:

                # Update path to pass.txt
                if not isUserDefined(vpn_provider) or addon.getSetting(
                        "user_def_credentials") == "true":
                    if line.startswith("auth-user-pass"):
                        line = "auth-user-pass " + getAddonPathWrapper(
                            vpn_provider + "/" + "pass.txt\n")

                # Update port numbers
                if line.startswith("remote "):
                    port = ""
                    for newline in lines:
                        if "proto " in newline:
                            if "tcp" in newline and not portTCP == "":
                                port = portTCP
                            if "udp" in newline and not portUDP == "":
                                port = portUDP
                    if not port == "":
                        tokens = line.split()
                        line = "remote " + tokens[1] + " " + port + "\n"

                # Update user cert and key
                if usesUserKeys(vpn_provider):
                    if line.startswith("cert "):
                        line = "cert " + getUserDataPathWrapper(
                            vpn_provider + "/" +
                            getCertName(vpn_provider, name) + "\n")
                    if line.startswith("key "):
                        line = "key " + getUserDataPathWrapper(
                            vpn_provider + "/" +
                            getKeyName(vpn_provider, name) + "\n")

                # For user defined profile we need to replace any path tags with the addon dir path
                if isUserDefined(vpn_provider):
                    line = line.replace("#PATH",
                                        getAddonPathWrapper(vpn_provider))

                # Set the logging level
                if line.startswith("verb "):
                    line = "verb " + verb_value + "\n"

                f.write(line)
            f.close()
        except:
            errorTrace("vpnproviders.py", "Failed to update ovpn file")
            return False

    # Flag that the files have been generated
    writeGeneratedFile(vpn_provider)

    return True
Exemplo n.º 36
0
def cycleConnection():
    # Cycle through the connections
    debugTrace("Cycling through available connections")
    requestVPNCycle(False)
    return
Exemplo n.º 37
0
#    it under the terms of the GNU General Public License as published by
#    the Free Software Foundation, either version 3 of the License, or
#    (at your option) any later version.
#
#    This program is distributed in the hope that it will be useful,
#    but WITHOUT ANY WARRANTY; without even the implied warranty of
#    MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE.  See the
#    GNU General Public License for more details.
#
#    You should have received a copy of the GNU General Public License
#    along with this program. If not, see <http://www.gnu.org/licenses/>.
#
#    This module assists with the import of a user defined VPN provider

import xbmc
from libs.utility import debugTrace, errorTrace, infoTrace, newPrint, getID
from libs.userdefined import importWizard

debugTrace("Entered import.py")

if not getID() == "":     
    importWizard()        

    # Return to the settings screen
    command = "Addon.OpenSettings(" + getID() + ")"
    xbmc.executebuiltin(command)
else:
    errorTrace("import.py", "VPN service is not ready")

debugTrace("Exit import.py")
Exemplo n.º 38
0
def requestSleep():

    # Don't know where this was called from so using plugin name to get addon handle
    addon = xbmcaddon.Addon("service.zomboided.tools")
    addon_name = addon.getAddonInfo("name")

    # Don't sleep if we can't get a lock
    if getSleepLock():
        t = now()
        remain = getSleepRemaining()
        if t - getSleepReqTime() < SLEEP_DELAY_TIME:
            # The last time sleep was requested was very recently so move to next value
            current = getSleepReq()
            if current == "": current = getSleep()
            if current == SLEEP_OFF:
                current = "End"
            elif current == SLEEP_END:
                current = addon.getSetting("sleep_inc")
            elif current.isdigit():
                current_int = int(current)
                if getSleepReq() == "" and remain.isdigit():
                    # This deals with the case where a timer is running already
                    current_int = int(remain)
                sleep_max = int(addon.getSetting("sleep_max"))
                sleep_inc = int(addon.getSetting("sleep_inc"))
                if current_int >= sleep_max:
                    current = SLEEP_OFF
                else:
                    if current_int + sleep_inc > sleep_max:
                        current = addon.getSetting("sleep_max")
                    else:
                        current = str(
                            ((current_int / sleep_inc) + 1) * sleep_inc)
            else:
                current == SLEEP_OFF
            setSleepReq(current)
            debugTrace("Repeat sleep request, " + current + ", remain is " +
                       "")
        else:
            # Otherwise get the value of the current sleep state and display it
            if remain == "":
                current = getSleep()
            else:
                current = remain
            debugTrace("New sleep request, " + current + ", remain is " + "")

        if current.isdigit():
            if current == "0":
                xbmcgui.Dialog().notification("Sleeping in less than a minute",
                                              "", "", 2000, False)
            elif current == "1":
                xbmcgui.Dialog().notification("Sleeping in 1 minute", "", "",
                                              2000, False)
            else:
                xbmcgui.Dialog().notification(
                    "Sleeping in " + current + " minutes", "", "", 2000, False)
        else:
            if current == SLEEP_END:
                xbmcgui.Dialog().notification("Sleeping at end of video", "",
                                              "", 2000, False)
            else:
                xbmcgui.Dialog().notification("Sleep is off", "", "", 2000,
                                              False)

        addAlert()
        setSleepReqTime(t)
        xbmc.sleep(1000)
        freeSleepLock()
Exemplo n.º 39
0
import xbmcgui
import xbmcvfs
import datetime
import os
from libs.vpnproviders import removeGeneratedFiles, cleanPassFiles, providers, usesUserKeys, usesMultipleKeys, getUserKeys, getUserCerts
from libs.utility import debugTrace, errorTrace, infoTrace
from libs.platform import getLogPath, getUserDataPath
from libs.common import resetVPNConnections, isVPNConnected
#from libs.generation import generateAll
from libs.credentials import defCred
addon = xbmcaddon.Addon("service.purevpn.monitor")
addon_name = addon.getAddonInfo("name")

action = sys.argv[1]

debugTrace("-- Entered profileupdate.py with parameter " + action + " --")

# Reset the ovpn files
if action == "ovpn":
    if addon.getSetting("1_vpn_validated") == "" or xbmcgui.Dialog().yesno(
            addon_name,
            "Resetting the ovpn files will reset all VPN connections.  Connections must be re-validated before use.\nContinue?"
    ):

        # Only used during development to create location files
        #generateAll()

        # Reset the connection before we do anything else
        if isVPNConnected(): resetVPNConnections(addon)
        debugTrace("Deleting all generated ovpn files")
        # Delete the ovpn files and the generated flag file.
Exemplo n.º 40
0
import datetime
import os
from libs.vpnproviders import removeGeneratedFiles, cleanPassFiles, providers, usesUserKeys, usesMultipleKeys, getUserKeys
from libs.vpnproviders import getUserCerts, getVPNDisplay, getVPNLocation, refreshFromGit, removeDownloadedFiles, isAlternative, resetAlternative
from libs.utility import debugTrace, errorTrace, infoTrace, newPrint, getID, getName
from libs.platform import getLogPath, getUserDataPath, writeVPNLog, copySystemdFiles, addSystemd, removeSystemd, generateVPNs
from libs.common import resetVPNConnections, isVPNConnected, disconnectVPN, suspendConfigUpdate, resumeConfigUpdate
from libs.ipinfo import resetIPServices
try:
    from libs.generation import generateAll
except:
    pass

action = sys.argv[1]

debugTrace("-- Entered managefiles.py with parameter " + action + " --")

if not getID() == "":
    addon = xbmcaddon.Addon(getID())
    addon_name = getName()

    # Reset the ovpn files
    if action == "ovpn":
        if addon.getSetting("1_vpn_validated") == "" or xbmcgui.Dialog().yesno(
                addon_name,
                "Resetting the VPN provider will disconnect and reset all VPN connections, and then remove any files that have been created. Continue?"
        ):
            suspendConfigUpdate()
            # Disconnect so that live files are not being modified
            if isVPNConnected(): resetVPNConnections(addon)
            debugTrace("Deleting all generated files")
Exemplo n.º 41
0
 def parseRulesFiles(self, rules):
     # Parse the rules file
     self.rules = []
     rule_numbers = []
     self.groups = []
     group_active = False
     current_group = ""
     if not rules == None:
         rule = ""
         try:
             debugTrace("Parsing rules file")
             for r in rules:
                 rule = r.strip(" \t\n\r")
                 # Groups
                 if rule.startswith("[") and rule.endswith("]"):
                     if rule[1] == "/":
                         # Group end
                         group_active = False
                         current_group = ""
                     else:
                         # Group start
                         group_active = True
                         group = rule[1:rule.index("]")]
                         current_group = group
                         if not group in self.groups:
                             self.groups.append(group)
                     rule = ""
                 # Comments
                 if rule.startswith("#"):
                     rule = ""
                 # Repeat
                 found_repeat = False
                 if rule.startswith("+"):
                     repeat_rule = rule[1:(rule.index(";") + 1)]
                     for repeat in rules:
                         if repeat.startswith(repeat_rule):
                             rule = repeat
                             found_repeat = True
                             break
                     if not found_repeat:
                         rule = ""
                 # Try and write rule
                 if not rule == "":
                     number = rule[0:(rule.index(";"))]
                     if not found_repeat and number in rule_numbers:
                         # Rule or rules with the same number already exists, just update them
                         i = 0
                         for replace in self.rules:
                             rule_group, rule_number, rule_title, rule_function, rule_addon, commands = parseRulesString(
                                 replace)
                             if number == rule_number:
                                 self.rules[i] = rule_group + "; " + rule
                                 debugTrace("Replacing " + replace +
                                            " with " + rule)
                             i += 1
                     else:
                         # Write rule if it's part of a group
                         if group_active:
                             self.rules.append(current_group + "; " + rule)
                             rule_numbers.append(number)
                             debugTrace("Found " + rule + " in " +
                                        current_group)
                         else:
                             errorTrace(
                                 "rules.py", "Excluded rule " + rule +
                                 " as it is not in a group")
         except Exception as e:
             errorTrace(
                 "rules.py",
                 "Couldn't parse rules files, last line read was '" + rule +
                 "'")
             errorTrace("rules.py", str(e))
Exemplo n.º 42
0
#    GNU General Public License for more details.
#
#    You should have received a copy of the GNU General Public License
#    along with this program. If not, see <http://www.gnu.org/licenses/>.
#
#    This module displays a list of connections on the screen and allows a
#    user to select one to connect to.  It can be called from a remote button.

import xbmcgui
import xbmcaddon
from libs.vpnproviders import getAddonList, isAlternative, getAlternativeLocations, getAlternativeLocationName
from libs.common import requestVPNCycle, getFilteredProfileList, getFriendlyProfileList, setAPICommand, connectionValidated, getValidatedList
from libs.common import getVPNProfile, getVPNProfileFriendly, getVPNState, clearVPNCycle, getCycleLock, freeCycleLock
from libs.utility import debugTrace, errorTrace, infoTrace, newPrint, getID, getName

debugTrace("-- Entered table.py --")

if not getID() == "":
    # Get info about the addon that this script is pretending to be attached to
    addon = xbmcaddon.Addon(getID())
    addon_name = getName()

    cancel_text = "[I][COLOR grey]Cancel[/COLOR][/I]"
    disconnect_text = "[COLOR ffff0000]Disconnect[/COLOR]"
    disconnected_text = "[COLOR ffff0000](Disconnected)[/COLOR]"

    # Don't display the table if there's nothing been set up
    if connectionValidated(addon):
        if getCycleLock():

            vpn_provider = addon.getSetting("vpn_provider_validated")
Exemplo n.º 43
0
def listConnections():
    # Start with the disconnect option
    url = base_url + "?disconnect"
    if getVPNProfileFriendly() == "":
        li = xbmcgui.ListItem("[COLOR ffff0000](Disconnected)[/COLOR]",
                              iconImage=getIconPath() + "disconnected.png")
    else:
        li = xbmcgui.ListItem("[COLOR ffff0000]Disconnect[/COLOR]",
                              iconImage=getIconPath() + "unlocked.png")
    xbmcplugin.addDirectoryItem(handle=addon_handle, url=url, listitem=li)

    # We should have a VPN set up by now, but don't list if we haven't.
    vpn_provider = addon.getSetting("vpn_provider")
    debugTrace("Listing the connections available for " + vpn_provider)
    if vpn_provider != "":
        # Get the list of connections and add them to the directory
        if not isAlternative(vpn_provider):
            all_connections = getAddonList(vpn_provider, "*.ovpn")
            ovpn_connections = getFilteredProfileList(
                all_connections, addon.getSetting("vpn_protocol"), None)
            connections = getFriendlyProfileList(ovpn_connections, "", "")
        else:
            ovpn_connections = getAlternativeLocations(vpn_provider, False)
            connections = getAlternativeFriendlyLocations(vpn_provider, False)
        inc = 0
        for connection in ovpn_connections:
            url = base_url + "?change?" + ovpn_connections[inc]
            conn_text = ""
            conn_primary = ""
            i = 1
            # Adjust 10 and 11 below if changing number of conn_max
            while (i < 11):
                if addon.getSetting(
                        str(i) +
                        "_vpn_validated_friendly") == connections[inc]:
                    conn_primary = " (" + str(i) + ")"
                    i = 10
                i = i + 1

            if getVPNProfileFriendly() == connections[inc] and isVPNConnected(
            ):
                conn_text = "[COLOR ff00ff00]" + connections[
                    inc] + conn_primary + " (Connected)[/COLOR]"
                if fakeConnection():
                    icon = getIconPath() + "faked.png"
                else:
                    icon = getIconPath() + "connected.png"
            else:
                if not conn_primary == "":
                    conn_text = "[COLOR ff0099ff]" + connections[
                        inc] + conn_primary + "[/COLOR]"
                else:
                    conn_text = connections[inc] + conn_primary
                icon = getIconPath() + "locked.png"
            li = xbmcgui.ListItem(conn_text, iconImage=icon)
            xbmcplugin.addDirectoryItem(handle=addon_handle,
                                        url=url,
                                        listitem=li)
            inc = inc + 1
    xbmcplugin.endOfDirectory(addon_handle)
    return
Exemplo n.º 44
0
def generateOVPNFiles(vpn_provider, alternative_locations_name):
    # Generate the OVPN files for a VPN provider using the template and update with location info

    infoTrace(
        "vpnproviders.py", "Generating OVPN files for " + vpn_provider +
        " using list " + alternative_locations_name)

    # See if there's a port override going on
    addon = xbmcaddon.Addon("service.vpn.manager")
    if addon.getSetting("default_udp") == "true":
        portUDP = ""
    else:
        portUDP = addon.getSetting("alternative_udp_port")

    if addon.getSetting("default_tcp") == "true":
        portTCP = ""
    else:
        portTCP = addon.getSetting("alternative_tcp_port")

    # Get the logging level
    verb_value = addon.getSetting("openvpn_verb")
    if verb_value == "":
        verb_value = "1"
        addon.setSetting("openvpn_verb", verb_value)

    # Load ovpn template
    try:
        debugTrace("Opening template file for " + vpn_provider)
        template_file = open(
            getAddonPath(True, vpn_provider + "/TEMPLATE.txt"), 'r')
        debugTrace("Opened template file for " + vpn_provider)
        template = template_file.readlines()
        template_file.close()
    except:
        errorTrace("vpnproviders.py",
                   "Couldn't open the template file for " + vpn_provider)
        return False

    # Load locations file
    if not alternative_locations_name == "":
        if alternative_locations_name == "User":
            locations_name = getUserDataPath(vpn_provider + "/LOCATIONS.txt")
        else:
            locations_name = getAddonPath(
                True, vpn_provider + "/LOCATIONS " +
                alternative_locations_name + ".txt")
    else:
        locations_name = getAddonPath(True, vpn_provider + "/LOCATIONS.txt")

    try:
        debugTrace("Opening locations file for " + vpn_provider + "\n" +
                   locations_name)
        locations_file = open(locations_name, 'r')
        debugTrace("Opened locations file for " + vpn_provider)
        locations = locations_file.readlines()
        locations_file.close()
    except:
        errorTrace(
            "vpnproviders.py", "Couldn't open the locations file for " +
            vpn_provider + "\n" + locations_name)
        return False

    # For each location, generate an OVPN file using the template
    for location in locations:
        try:
            location_values = location.split(",")
            geo = location_values[0]
            servers = location_values[1].split()
            proto = location_values[2]
            ports = (location_values[3].strip(' \t\n\r')).split()
            port = ""

            # Initialise the set of values that can be modified by the location file tuples
            ca_cert = "ca.crt"
            ta_key = "ta.key"
            user_key = getUserDataPathWrapper(vpn_provider + "/" +
                                              getKeyName(vpn_provider, geo))
            user_cert = getUserDataPathWrapper(vpn_provider + "/" +
                                               getCertName(vpn_provider, geo))
            remove_flags = ""

            if len(location_values) > 4:
                # The final location value is a list of multiple x=y declarations.
                # These need to be parsed out and modified.
                modifier_tuples = (location_values[4].strip(' \t\n\r')).split()
                # Loop through all of the values splitting them into name value pairs
                for modifier in modifier_tuples:
                    pair = modifier.split("=")
                    if "#CERT" in pair[0]: ca_cert = pair[1].strip()
                    if "#REMOVE" in pair[0]: remove_flags = pair[1].strip()
                    if "#TLSKEY" in pair[0]: ta_key = pair[1].strip()
                    if "#USERKEY" in pair[0]: user_key = pair[1].strip()
                    if "#USERCERT" in pair[0]: user_cert = pair[1].strip()
            if proto == "udp" and not portUDP == "": port = portUDP
            if proto == "tcp" and not portTCP == "": port = portTCP
            if port == "" and len(ports) == 1: port = ports[0]
        except:
            errorTrace(
                "vpnproviders.py", "Location file for " + vpn_provider +
                " invalid on line\n" + location)
            return False

        try:
            ovpn_file = open(
                getAddonPath(True, vpn_provider + "/" + geo + ".ovpn"), 'w')
            if proto == "tcp":
                servprot = "tcp-client"
            else:
                servprot = proto

            # Do a replace on the tags in the template with data from the location file
            for line in template:
                output_line = line.strip(' \t\n\r')
                # Must check to see if there's a remove tag on the line before looking for other tags
                if "#REMOVE" in output_line:
                    if output_line[output_line.index("#REMOVE") +
                                   7] in remove_flags:
                        # Remove the line if it's a flag this location doesn't care about
                        output_line = ""
                    else:
                        # Delete the tag if this location doesn't want this line removed
                        output_line = output_line.replace(
                            "#REMOVE" +
                            output_line[output_line.index("#REMOVE") + 7], "")
                output_line = output_line.replace("#PROTO", proto)
                output_line = output_line.replace("#SERVPROT", servprot)
                # If there are multiple servers then we'll need to duplicate the server
                # line (which starts with 'remote ') and fix the server.  The rest of the
                # code will deal with the port which is the same for all lines (although
                # this assumption might not be true for all VPN providers...)
                if output_line.startswith("remote "):
                    server_template = output_line
                    server_lines = ""
                    i = 0
                    for server in servers:
                        if not server_lines == "":
                            server_lines = server_lines + "\n"
                        server_lines = server_lines + server_template.replace(
                            "#SERVER", server)
                        if port == "":
                            server_lines = server_lines.replace(
                                "#PORT", ports[i])
                        i = i + 1
                    output_line = server_lines
                # There might be other places we use server and port, so still the do the replace
                output_line = output_line.replace("#SERVER", servers[0])
                output_line = output_line.replace("#PORT", port)
                output_line = output_line.replace(
                    "#PASS",
                    getAddonPathWrapper(vpn_provider + "/" + "pass.txt"))
                output_line = output_line.replace(
                    "#CERT", getAddonPathWrapper(vpn_provider + "/" + ca_cert))
                output_line = output_line.replace(
                    "#TLSKEY",
                    getAddonPathWrapper(vpn_provider + "/" + ta_key))
                output_line = output_line.replace(
                    "#CRLVERIFY",
                    getAddonPathWrapper(vpn_provider + "/" + "crl.pem"))
                output_line = output_line.replace("#USERKEY", user_key)
                output_line = output_line.replace("#USERCERT", user_cert)
                # Overwrite the verb value with the one in the settings
                if output_line.startswith("verb "):
                    output_line = "verb " + verb_value
                # This is a little hack to remove a tag that doesn't work with TCP but is needed for UDP
                # Could do this with a #REMOVE, but doing it here is less error prone.
                if "explicit-exit-notify" in line and proto == "tcp":
                    output_line = ""
                if not output_line == "": ovpn_file.write(output_line + "\n")
            ovpn_file.close()
            debugTrace("Wrote location " + geo + " " + proto)
        except:
            errorTrace(
                "vpnproviders.py", "Can't write a location file for " +
                vpn_provider + " failed on line\n" + location)
            return False

    # Flag that the files have been generated
    writeGeneratedFile(vpn_provider)

    return True
Exemplo n.º 45
0
import xbmc
import xbmcaddon
import xbmcplugin
import xbmcgui
import os
from libs.common import connectionValidated, getIPInfo, isVPNConnected, getVPNProfile, getVPNProfileFriendly
from libs.common import getFriendlyProfileList, connectVPN, disconnectVPN, setVPNState, requestVPNCycle, getFilteredProfileList
from libs.common import isVPNMonitorRunning, setVPNMonitorState, getVPNMonitorState, wizard
from libs.common import getIconPath, getSystemData, getVPNServer
from libs.platform import getPlatform, platforms, getPlatformString, fakeConnection
from libs.vpnproviders import getAddonList, isAlternative, getAlternativeLocations, getAlternativeFriendlyLocations
from libs.utility import debugTrace, errorTrace, infoTrace, newPrint
from libs.sysbox import popupSysBox

debugTrace("-- Entered addon.py " + sys.argv[0] + " " + sys.argv[1] + " " +
           sys.argv[2] + " --")

# Set the addon name for use in the dialogs
addon = xbmcaddon.Addon()
addon_name = addon.getAddonInfo("name")
addon_id = addon.getAddonInfo('id')

# Get the arguments passed in
base_url = sys.argv[0]
addon_handle = int(sys.argv[1])
args = sys.argv[2].split("?", )
action = ""
params = ""
# If an argument has been passed in, the first character will be a ?, so the first list element is empty
inc = 0
for token in args:
Exemplo n.º 46
0
#    This module validates a VPN connection from addon settings page.

import xbmc
import xbmcaddon
import xbmcgui
import xbmcvfs
import sys
from libs.common import connectVPN
from libs.utility import debugTrace, errorTrace, infoTrace, getID, getName
from libs.vpnproviders import usesPassAuth, getVPNLocation, getUserDataPath
from libs.platform import getAddonPath

# Get the first argument which will indicate the connection that's being dealt with
connection_order = sys.argv[1]

debugTrace("Entered connect.py with parameter " + connection_order)

if not getID() == "":

    addon = xbmcaddon.Addon(getID())
    addon_name = getName()

    # If a new connection is being validated, check everything needed is entered
    vpn_provider = addon.getSetting("vpn_provider")
    vpn_username = addon.getSetting("vpn_username")
    vpn_password = addon.getSetting("vpn_password")
        
    if xbmcvfs.exists(getUserDataPath(getVPNLocation(vpn_provider) + "/DEFAULT.txt")):
        vpn_username = "******"
        vpn_password = "******"
        
Exemplo n.º 47
0
def getUserDataList(vpn_provider, filter):
    # Return all user files for a provider (aka directory name...)
    path = getUserDataPath(getVPNLocation(vpn_provider) + "/" + filter)
    debugTrace("Getting list of files in " + path)
    return sorted(glob.glob(path))
Exemplo n.º 48
0
import xbmcvfs
import datetime
import os
from libs.vpnproviders import removeGeneratedFiles, cleanPassFiles, providers, usesUserKeys, usesMultipleKeys, getUserKeys
from libs.vpnproviders import getUserCerts, getVPNDisplay, getVPNLocation
from libs.utility import debugTrace, errorTrace, infoTrace
from libs.platform import getLogPath, getUserDataPath, writeVPNLog
from libs.common import resetVPNConnections, isVPNConnected
#from libs.generation import generateAll

addon = xbmcaddon.Addon("service.vpn.manager")
addon_name = addon.getAddonInfo("name")

action = sys.argv[1]

debugTrace("-- Entered managefiles.py with parameter " + action + " --")

# Reset the ovpn files
if action == "ovpn":
    if addon.getSetting("1_vpn_validated") == "" or xbmcgui.Dialog().yesno(addon_name, "Resetting the .ovpn files will reset all VPN connections.  Connections must be re-validated before use.\nContinue?"):
    
        # Only used during development to create location files
        #generateAll()

        # Reset the connection before we do anything else
        resetVPNConnections(addon)            
        debugTrace("Deleting all generated ovpn files")
        # Delete the ovpn files and the generated flag file.
        removeGeneratedFiles()
        # Remove any user/password files
        cleanPassFiles()
Exemplo n.º 49
0
def getAddonList(vpn_provider, filter):
    # Return the list of ovpn files for a given provider (aka directory name...)
    path = getAddonPath(True, getVPNLocation(vpn_provider) + "/" + filter)
    debugTrace("Getting list of profiles in " + path)
    return sorted(glob.glob(path))