Skip to content

Commit 0614976

Browse files
committed
feat: added new ways to detect if running on equinor environment
1 parent 79aeec5 commit 0614976

File tree

1 file changed

+67
-18
lines changed

1 file changed

+67
-18
lines changed

tagreader/utils.py

Lines changed: 67 additions & 18 deletions
Original file line numberDiff line numberDiff line change
@@ -1,7 +1,7 @@
11
import enum
22
import hashlib
3-
import logging
43
import platform
4+
import socket
55
import ssl
66
from datetime import datetime, tzinfo
77
from enum import Enum
@@ -33,7 +33,6 @@ def is_linux() -> bool:
3333
import winreg
3434

3535
if is_mac():
36-
import socket
3736
import subprocess
3837

3938

@@ -145,6 +144,7 @@ def add_equinor_root_certificate() -> bool:
145144
with open(ca_file, "ab") as f:
146145
f.write(bytes(certificate, "ascii"))
147146
logger.debug("Equinor Root Certificate added to certifi store")
147+
return True
148148

149149

150150
def find_local_equinor_root_certificate() -> str:
@@ -153,7 +153,7 @@ def find_local_equinor_root_certificate() -> str:
153153

154154
if is_windows():
155155
logger.debug("Checking for Equinor Root CA in Windows certificate store")
156-
for cert in ssl.enum_certificates("CA"):
156+
for cert in ssl.enum_certificates("CA"): # type: ignore
157157
found_cert = cert[0]
158158
# deepcode ignore InsecureHash: <Only hashes to compare with known hash>
159159
if hashlib.sha1(found_cert).hexdigest().upper() == equinor_root_pem_hash:
@@ -189,6 +189,9 @@ def get_macos_equinor_certificates():
189189
import ssl
190190
import tempfile
191191

192+
if not is_mac():
193+
raise OSError("Function only works on MacOS")
194+
192195
ca_search = "Equinor Root CA"
193196

194197
ctx = ssl.create_default_context()
@@ -210,38 +213,84 @@ def is_equinor() -> bool:
210213
If Windows host:
211214
Finds host's domain in Windows Registry at
212215
HKLM\\SYSTEM\\ControlSet001\\Services\\Tcpip\\Parameters\\Domain
216+
or check if hostname starts with eqdev or eqpc
213217
If mac os host:
214-
Finds statoil.net as AD hostname in certificates
218+
Finds statoil.net as AD hostname in certificates or
219+
Finds statoil.net, client.statoil.net or equinor.com in dns search domains
215220
If Linux host:
216-
Checks whether statoil.no is search domain
221+
Checks whether statoil.no is dns search domains
217222
218223
Returns:
219224
bool: True if Equinor
220225
"""
226+
227+
hostname = socket.gethostname()
228+
221229
if is_windows():
222-
with winreg.OpenKey(
223-
winreg.HKEY_LOCAL_MACHINE, r"SYSTEM\ControlSet001\Services\Tcpip\Parameters"
230+
if hostname.lower().startswith("eqdev") or hostname.lower().startswith("eqpc"):
231+
return True
232+
with winreg.OpenKey( # type: ignore
233+
winreg.HKEY_LOCAL_MACHINE, r"SYSTEM\ControlSet001\Services\Tcpip\Parameters" # type: ignore
224234
) as key:
225-
domain = winreg.QueryValueEx(key, "Domain")
226-
if "statoil" in domain[0]:
235+
domain = winreg.QueryValueEx(key, "Domain") # type: ignore
236+
if "statoil" in domain[0] or "equinor" in domain[0]:
237+
return True
238+
elif is_linux() or is_mac():
239+
with open("/etc/resolv.conf", "r") as f:
240+
if any(
241+
domain in f.read()
242+
for domain in ["client.statoil.net", "statoil.net", "equinor.com"]
243+
):
244+
return True
245+
246+
if is_mac():
247+
248+
def get_mac_dns_search_list():
249+
"""
250+
Retrieves the DNS search list configured on macOS.
251+
"""
252+
try:
253+
# Execute the scutil command to get DNS configuration
254+
result = subprocess.run(
255+
["scutil", "--dns"], capture_output=True, text=True, check=True
256+
)
257+
output = result.stdout
258+
259+
search_list = []
260+
# Parse the output to find the search domains
261+
for line in output.splitlines():
262+
if "search domain" in line:
263+
# Extract the domain from the line
264+
parts = line.split(":")
265+
if len(parts) > 1:
266+
domain = parts[1].strip()
267+
# Remove any leading/trailing quotes if present
268+
domain = domain.strip('"')
269+
search_list.append(domain)
270+
return search_list
271+
except subprocess.CalledProcessError as e:
272+
print(f"Error executing scutil: {e}")
273+
return []
274+
except Exception as e:
275+
print(f"An unexpected error occurred: {e}")
276+
return []
277+
278+
if any(
279+
domain in get_mac_dns_search_list()
280+
for domain in ["client.statoil.net", "statoil.net", "equinor.com"]
281+
):
227282
return True
228-
elif is_mac():
283+
229284
s = subprocess.run(
230285
["security", "find-certificate", "-a", "-c" "client.statoil.net"],
231286
stdout=subprocess.PIPE,
232287
).stdout
233288

234-
host = socket.gethostname()
235-
236289
# deepcode ignore IdenticalBranches: Not an error. First test is just more precise.
237-
if host + ".client.statoil.net" in str(s):
290+
if hostname + ".client.statoil.net" in str(s):
238291
return True
239-
elif "client.statoil.net" in host and host in str(s):
292+
elif "client.statoil.net" in hostname and hostname in str(s):
240293
return True
241-
elif is_linux():
242-
with open("/etc/resolv.conf", "r") as f:
243-
if "statoil.no" in f.read():
244-
return True
245294
else:
246295
raise OSError(
247296
f"Unsupported system: {platform.system()}. Please report this as an issue."

0 commit comments

Comments
 (0)