From 6e359a1ba001a567894fdc0ec120fda781e232eb Mon Sep 17 00:00:00 2001 From: Burak Yucesoy Date: Mon, 2 Jul 2018 15:37:11 +0300 Subject: [PATCH] Fix integer conversion in masks At the moment, parse functions in Mask32 and Mask128 convert strings into integers using to_i function, which is dangerous because it silently accepts inputs like 'aaa' as 0. With this PR, they switch to use Integer function, which throws ArgumentError if invalid input is passed. We catch ArgumentError and throw ValidationError to user instead. --- lib/mask128.rb | 4 +++- lib/mask32.rb | 12 +++++++++--- 2 files changed, 12 insertions(+), 4 deletions(-) diff --git a/lib/mask128.rb b/lib/mask128.rb index 6f297bd..8d24093 100755 --- a/lib/mask128.rb +++ b/lib/mask128.rb @@ -30,7 +30,9 @@ def Mask128.parse(mask) if (mask.start_with?("/")) # cidr format mask = mask[1..-1] # remove "/" end - return Mask128.new(mask.to_i) + return Mask128.new(Integer(mask)) + rescue ArgumentError + raise ValidationError, "#{mask} is not valid integer." end #cmp compares equality with another Mask128. Return: diff --git a/lib/mask32.rb b/lib/mask32.rb index c852be7..c9e4063 100755 --- a/lib/mask32.rb +++ b/lib/mask32.rb @@ -28,9 +28,15 @@ def initialize(prefix_len) def Mask32.parse(mask) mask.strip! if (mask.start_with?("/")) # cidr format - return Mask32.new(mask[1..-1].to_i) # remove "/" - elsif (!mask.include?(".")) - return Mask32.new(mask.to_i) + mask = mask[1..-1] # remove "/" + end + + if (!mask.include?(".")) + begin + return Mask32.new(Integer(mask)) + rescue ArgumentError + raise ValidationError, "#{mask} is not valid integer." + end end # for extended netmask