Skip to content

Commit

Permalink
Purged all eval() statements for security. #39. Begin 1.6.3 develop…
Browse files Browse the repository at this point in the history
…ment.
  • Loading branch information
samclane committed Mar 19, 2019
1 parent e0ed753 commit feccb38
Show file tree
Hide file tree
Showing 8 changed files with 51 additions and 51 deletions.
4 changes: 2 additions & 2 deletions _constants.py
Original file line number Diff line number Diff line change
@@ -1,4 +1,4 @@
VERSION = "1.6.2"
BUILD_DATE = "2019-03-15T15:39:00.879002"
VERSION = "1.6.3"
BUILD_DATE = "2019-03-19T15:49:40.853627"
AUTHOR = "Sawyer McLane"
DEBUGGING = False
2 changes: 1 addition & 1 deletion debug.spec
Original file line number Diff line number Diff line change
Expand Up @@ -3,7 +3,7 @@ import datetime

bd = datetime.datetime.now().isoformat()
auth = "Sawyer McLane"
vers = "1.6.2"
vers = "1.6.3"
is_debug = True

# Write version info into _constants.py resource file
Expand Down
4 changes: 2 additions & 2 deletions default.ini
Original file line number Diff line number Diff line change
Expand Up @@ -14,6 +14,6 @@ duration = 0.0

# Used for diagnostic purposes. Please do not change.
[Info]
version = 1.6.2
version = 1.6.3
author = Sawyer McLane
builddate = 2019-03-15T15:39:00.879002
builddate = 2019-03-19T15:49:40.853627
2 changes: 1 addition & 1 deletion demo.spec
Original file line number Diff line number Diff line change
Expand Up @@ -3,7 +3,7 @@ import datetime

bd = datetime.datetime.now().isoformat()
auth = "Sawyer McLane"
vers = "1.6.2"
vers = "1.6.3"
is_debug = True

# Write version info into _constants.py resource file
Expand Down
50 changes: 26 additions & 24 deletions gui.pyw
Original file line number Diff line number Diff line change
Expand Up @@ -21,7 +21,7 @@ from utilities import audio, color_thread
from utilities.keypress import Keystroke_Watcher
from utilities.utils import *

RED = [0, 65535, 65535, 3500] # Overwrite color, which appears black otherwise
RED = [0, 65535, 65535, 3500] # Fixes RED from appearing BLACK

audio.init(config)

Expand Down Expand Up @@ -145,7 +145,8 @@ class LifxFrame(ttk.Frame):
self.key_listener = Keystroke_Watcher(self)
for keypress, function in dict(config['Keybinds']).items():
light, color = function.split(':')
color = Color(*eval(color, {}))
color = Color(*globals()[color]) if color in globals().keys() else list(
map(int, color.strip("()[]").split(",")))
self.save_keybind(light, keypress, color)

# Stop splashscreen and start main function
Expand All @@ -166,7 +167,7 @@ class LifxFrame(ttk.Frame):
self.after(HEARTBEAT_RATE, self.update_icons)

# Minimize if in config
if eval(config["AppSettings"]["start_minimized"], {}):
if config.getboolean("AppSettings", "start_minimized"):
self.master.withdraw()

def scan_for_lights(self):
Expand Down Expand Up @@ -377,18 +378,20 @@ class LightFrame(ttk.Labelframe):
# Add buttons for pre-made colors
self.preset_colors_lf = ttk.LabelFrame(self, text="Preset Colors", padding="3 3 12 12")
self.colorVar = StringVar(self, value="Presets")
self.default_colors = ["RED",
"ORANGE",
"YELLOW",
"GREEN",
"CYAN",
"BLUE",
"PURPLE",
"PINK",
"WHITE",
"COLD_WHITE",
"WARM_WHITE",
"GOLD"]

self.default_colors = {"RED": RED,
"ORANGE": ORANGE,
"YELLOW": YELLOW,
"GREEN": GREEN,
"CYAN": CYAN,
"BLUE": BLUE,
"PURPLE": PURPLE,
"PINK": PINK,
"WHITE": WHITE,
"COLD_WHITE": COLD_WHITE,
"WARM_WHITE": WARM_WHITE,
"GOLD": GOLD}

self.preset_dropdown = OptionMenu(self.preset_colors_lf, self.colorVar, *self.default_colors)
self.preset_dropdown.grid(row=0, column=0)
self.preset_dropdown.configure(width=13)
Expand Down Expand Up @@ -440,14 +443,13 @@ class LightFrame(ttk.Labelframe):
'y1': Entry(self.screen_region_lf, width=6),
'y2': Entry(self.screen_region_lf, width=6)
}
if self.label in config["AverageColor"].keys():
region = eval(config['AverageColor'][self.label],
{"full": "full", "get_primary_monitor": get_primary_monitor})
region = config['AverageColor'][self.label if self.label in config["AverageColor"].keys() else 'defaultmonitor']
if region == "full":
region = ["full"] * 4 # TODO
elif region[:19] == "get_primary_monitor":
region = get_primary_monitor()
else:
region = eval(config['AverageColor']['defaultmonitor'],
{"full": "full", "get_primary_monitor": get_primary_monitor})
if isinstance(region, str):
region = ["full"] * 4
region = list(map(int, region.strip("()[]").split(',')))
self.screen_region_entires['x1'].insert(END, region[0])
self.screen_region_entires['y1'].insert(END, region[1])
self.screen_region_entires['x2'].insert(END, region[2])
Expand Down Expand Up @@ -624,13 +626,13 @@ class LightFrame(ttk.Labelframe):
return utils.RGBtoHSBK(color, temperature=self.get_color_values_hsbk().kelvin)

def change_preset_dropdown(self, *args):
color = Color(*eval(self.colorVar.get()))
color = Color(*globals()[self.colorVar.get()])
self.preset_dropdown.config(bg=tuple2hex(HSBKtoRGB(color)),
activebackground=tuple2hex(HSBKtoRGB(color)))
self.set_color(color, False)

def change_user_dropdown(self, *args):
color = Color(*eval(config["PresetColors"][self.uservar.get()], {}))
color = list(map(int, config["PresetColors"][self.uservar.get()].strip("()[]").split(",")))
self.user_dropdown.config(bg=tuple2hex(HSBKtoRGB(color)),
activebackground=tuple2hex(HSBKtoRGB(color)))
self.set_color(color, rapid=False)
Expand Down
2 changes: 1 addition & 1 deletion main.spec
Original file line number Diff line number Diff line change
Expand Up @@ -3,7 +3,7 @@ import datetime

bd = datetime.datetime.now().isoformat()
auth = "Sawyer McLane"
vers = "1.6.2"
vers = "1.6.3"
is_debug = False

# Write version info into _constants.py resource file
Expand Down
23 changes: 10 additions & 13 deletions ui/settings.py
Original file line number Diff line number Diff line change
@@ -1,5 +1,4 @@
import configparser
import itertools
import logging
import tkinter.ttk as ttk
from shutil import copyfile
Expand Down Expand Up @@ -203,17 +202,17 @@ def body(self, master):

# Widgets
# Starting minimized
self.start_mini = BooleanVar(master, value=eval(config["AppSettings"]["start_minimized"], {}))
self.start_mini = BooleanVar(master, value=config.getboolean("AppSettings", "start_minimized"))
self.start_mini_check = Checkbutton(master, variable=self.start_mini)

# Avg monitor color match
self.avg_monitor = StringVar(master, value=config["AverageColor"]["DefaultMonitor"])
options = []
lst = getDisplayRects()
for i in range(1, len(lst) + 1):
els = [list(x) for x in itertools.combinations(lst, i)]
options.extend(els)
self.avg_monitor_dropdown = OptionMenu(master, self.avg_monitor, *lst, 'full')
options = ['full', 'get_primary_monitor', *getDisplayRects()]
# lst = getDisplayRects()
# for i in range(1, len(lst) + 1):
# els = [list(x) for x in itertools.combinations(lst, i)]
# options.extend(els)
self.avg_monitor_dropdown = OptionMenu(master, self.avg_monitor, *options)

self.duration_scale = Scale(master, from_=0, to_=2, resolution=1 / 15, orient=HORIZONTAL)
self.duration_scale.set(float(config["AverageColor"]["Duration"]))
Expand Down Expand Up @@ -301,10 +300,9 @@ def get_color(self):

def register_keybinding(self, bulb: str, keys: str, color: str):
try:
color = eval(color, {c: eval(c) for c in self.root_window.framesdict[
self.keybind_bulb_selection.get()].default_colors}) # should match color to variable w/ same name
except NameError: # must be using a custom color
color = eval(config["PresetColors"][color], {})
color = self.root_window.framesdict[self.keybind_bulb_selection.get()].default_colors[color]
except KeyError: # must be using a custom color
color = list(map(int, config["PresetColors"][color].strip("{}[]").split(',')))
self.root_window.save_keybind(bulb, keys, color)
config["Keybinds"][str(keys)] = str(bulb + ":" + str(color))
self.mlb.insert(END, (str(bulb), str(keys), str(color)))
Expand All @@ -314,7 +312,6 @@ def register_keybinding(self, bulb: str, keys: str, color: str):
self.keybind_keys_select.config(state='readonly')
self.preset_color_name.focus_set() # Set focus to a dummy widget to reset the Entry


def on_keybind_keys_click(self, event):
""" Call when cursor is in key-combo entry """
self.update()
Expand Down
15 changes: 8 additions & 7 deletions utilities/color_thread.py
Original file line number Diff line number Diff line change
Expand Up @@ -2,17 +2,15 @@
# coding=utf-8
import logging
import threading
from statistics import mode
from functools import lru_cache
from collections import deque

from functools import lru_cache
from statistics import mode

from PIL import Image
from desktopmagic.screengrab_win32 import *
from lifxlan import utils

from ui.settings import config
from utilities.utils import get_primary_monitor


@lru_cache(maxsize=32)
Expand All @@ -22,15 +20,19 @@ def get_monitor_from_bounds(func):

N_POINTS = 3
window = deque([0, 0, 0, 0] for _ in range(N_POINTS))


def column(matrix, i):
return [row[i] for row in matrix]


def avg_screen_color(initial_color, func_bounds=lambda: None):
global window
monitor = get_monitor_from_bounds(func_bounds)
if "full" in monitor:
im = getScreenAsImage()
else:
im = getRectAsImage(eval(monitor, {'get_primary_monitor': get_primary_monitor}))
im = getRectAsImage(list(map(int, monitor.strip("{}[]").split(','))))
color = im.resize((1, 1), Image.HAMMING).getpixel((0, 0))
color_hsbk = list(utils.RGBtoHSBK(color, temperature=initial_color[3]))
window.rotate(1)
Expand Down Expand Up @@ -113,7 +115,6 @@ def get_duration():
return float(config["AverageColor"]["duration"])



def install_thread_excepthook():
"""
Workaround for sys.excepthook thread bug
Expand All @@ -136,4 +137,4 @@ def run(*args, **kwargs):
threading.Thread.run = run


install_thread_excepthook()
install_thread_excepthook()

0 comments on commit feccb38

Please sign in to comment.