-
Notifications
You must be signed in to change notification settings - Fork 1
/
simplified_openvpn_helper.py
94 lines (78 loc) · 2.75 KB
/
simplified_openvpn_helper.py
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
#!/usr/bin/env python3
# -*- coding: utf-8 -*-
# pylint: disable=R0904
"""File that contains SimplifiedOpenvpnHelper class."""
import os
import socket
import inspect
import hashlib
from requests import get
class SimplifiedOpenvpnHelper:
"""Class that contains shareable helper methods."""
@staticmethod
def current_method():
"""Returns name of the current method."""
return inspect.stack()[1][3]
@staticmethod
def read_file_as_value(filename, verbose=False):
"""Reads contents of the file and returns it."""
if not os.path.isfile(filename):
if verbose:
print("> File that you tried to read as value doesn't exist.")
return None
value = None
with open(filename) as content:
value = content.read().rstrip()
return value
@staticmethod
def create_directory(value, mode=0o700):
"""Creates new directory on filesystem."""
if not os.path.exists(value):
os.makedirs(value, mode)
@staticmethod
def sanitize_path(path):
"""Makes sure that path are ending with forward slash."""
if os.path.isfile(path):
if path.endswith('/'):
path = path.rstrip('/')
elif os.path.isdir(path):
if not path.endswith('/'):
path = path + '/'
return path
@staticmethod
def is_valid_ipv4(ipv4):
"""Check if IP is valid IPv4 address."""
if isinstance(ipv4, str) and len(ipv4.strip()) > 6:
return True
return False
@staticmethod
def is_valid_hostname(hostname):
"""Checks if specified hostname matches rules and returns boolean."""
if len(hostname) > 255 or len(hostname) < 1:
return False
return True
@staticmethod
def fetch_hostname_by_system():
"""Fetches Fully Qualified Domain Name from system."""
return socket.getfqdn()
@staticmethod
def fetch_hostname_by_reverse_dns(ipv4=None):
"""Tries to fetch hostname by reverse DNS lookup and returns it if possible."""
if ipv4 is None:
ipv4 = SimplifiedOpenvpnHelper.fetch_external_ipv4()
if ipv4:
return socket.gethostbyaddr(ipv4)
return None
@staticmethod
def fetch_external_ipv4():
"""Fetches and returns external IPv4 address."""
ipv4 = get('http://api.ipify.org').text
if ipv4:
return ipv4.strip()
return None
@staticmethod
def generate_share_hash(slug, sovpn_share_salt=''):
"""Calculates and return SOVPN share hash for specified slug."""
feed = (sovpn_share_salt + slug).encode('utf-8')
share_hash = hashlib.sha1(feed).hexdigest()
return share_hash