Module: Veracode

Defined in:
lib/veracode.rb,
lib/veracode/gems.rb,
lib/veracode/schema.rb,
lib/veracode/version.rb

Defined Under Namespace

Modules: ActiveRecord

Constant Summary collapse

SupportedGems =
%w{
  actionmailer
  actionpack
  activemodel
  activerecord
  activeresource
  activesupport
  arel
  builder
  erubis
  haml
  haml-rails
  rails
  railties
  veracode
}
VERSION =
'1.1.8'
ARCHIVE_VERSION =
'2020-06-29'

Class Method Summary collapse

Class Method Details

.add_to_archive(data) ⇒ Object



416
417
418
419
420
421
# File 'lib/veracode.rb', line 416

def self.add_to_archive(data)
  if @disasmlog.nil?
    prepare_archive
  end
  @disasmlog.write(data)
end

.archive(objects, with_disasm = true) ⇒ Object

Archiving Objects



637
638
639
640
641
642
643
644
645
646
647
648
649
650
651
652
653
654
655
656
657
658
659
660
661
662
663
664
665
666
667
668
669
670
671
672
673
674
675
676
677
678
679
680
# File 'lib/veracode.rb', line 637

def self.archive(objects, with_disasm=true)
  veracode_artifacts = Set[
    safe_name(Veracode),
    safe_name(Veracode::ActiveRecord),
    safe_name(Veracode::ActiveRecord::Model),
    safe_name(Veracode::ActiveRecord::Schema)
  ]
  rails_filters = [
    "ActionCable::",
    "ActionController::",
    "ActionDispatch::",
    "ActionMailer::",
    "ActiveJob::",
    "ActiveSupport::",
    "ActiveStorage::",
    "ActionView::(?!CompiledTemplates)", #Allows Compiled templates with the not group
    "ActiveRecord::",
  ]
  objects = objects.reject do |o|
    sn = safe_name(o).dup
    while with_disasm && !sn.slice!(/^#<(Class|Module):/).nil? do sn = sn[0..-2] end #strip #<Class: and #<Module: prefix, strip corresponding > suffix
    veracode_artifacts.include?(sn) || (with_disasm && sn[/^(#{rails_filters.join('|')}).*/])
  end

  if $options[:verbose]
    puts "Archiving #{objects.count.to_s} objects" + (with_disasm ? " with disassembly" : "")
    puts
  end

  objects.sort_by {|o| safe_name(o) }.each do |o|

    sn = safe_name(o)
    puts "archiving #{o.class.to_s.downcase} #{quote(sn)}" if $options[:verbose]

    add_to_archive "#{o.class.to_s.downcase} #{quote(sn)}\n" + 
                 ( o.is_a?(Class)  ? class_header(o)  : "") + # superclass
                 ( @rails6 && sn == "ActionView::Base" ? "include \"ActionView::CompiledTemplates\"\n" : "") + #hack for rails 6 compiled template output
                 ( o.is_a?(Module) ? module_header(o) : "") + # included modules
                 ( o.is_a?(Object) ? object_contents(o, with_disasm) : "") + 
                 ( o.is_a?(Module) ? module_contents(o, with_disasm) : "") + 
                 "end#{o.class.to_s.downcase}\n" + 
                 "\n"
  end
end

.archive_rails6_templatesObject



682
683
684
685
686
687
688
689
690
691
692
693
694
695
696
697
698
699
700
701
702
703
704
705
706
707
708
709
710
711
# File 'lib/veracode.rb', line 682

def self.archive_rails6_templates
  puts "archiving views" if $options[:verbose]
  begin
    o = @view.compiled_method_container
    compiled_views = o.instance_methods - @view_methods
    formatted_contents = ""
    for m_symbol in compiled_views
      begin
        m = o.instance_method(m_symbol)
        formatted_contents += format_method(m, "public_instance", true)
      rescue Exception => e
        log_error "Error archiving singleton method #{m_symbol.to_s.dump}: #{e.message}"
      end
    end
    # fake the module outpput to match what SAF expects from Rails <= 5
    add_to_archive "module \"ActionView::CompiledTemplates\"\n" + 
                  "extend \"ActiveSupport::Dependencies::ModuleConstMissing\"\n" +
                  "extend \"Module::Concerning\"\n" +
                  "extend \"ActiveSupport::ToJsonWithActiveSupportEncoder\"\n" +
                  "extend \"PP::ObjectMixin\"\n" +
                  "extend \"ActiveSupport::Dependencies::Loadable\"\n" +
                  "extend \"JSON::Ext::Generator::GeneratorMethods::Object\"\n" +
                  "extend \"ActiveSupport::Tryable\"\n" +
                  "extend \"Kernel\"\n" +
                  formatted_contents +
                  "endmodule\n"
  rescue Exception => e
    log_error "Error archiving Rails 6 views: #{e.message}"
  end
end

.archive_schemaObject



84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
# File 'lib/veracode/schema.rb', line 84

def self.archive_schema
  puts "Evaluating and archiving schema information"
  schema_file = File.join("db", "schema.rb")

  begin
    schema = 'Veracode::' + File.read(schema_file).each_line.reject {|l| l =~ /^\s*#/}.join      
  rescue Exception => e
    puts "Unable to retrieve schema information from 'db/schema.rb'. Are your migrations up to date?"
    log_error "Unable to retrieve schema from 'db/schema.rb' (#{e.message})"
    add_to_archive  %Q|module "Veracode::Schema"\n|
    add_to_archive  %Q|endmodule\n\n|
    return
  end

  add_to_archive  %Q|module "Veracode::Schema"\n|
  begin
    eval(schema)
  rescue Exception => e
    puts "Unable to evaluate schema information from 'db/schema.rb'. (#{e.message})"
    log_error "Unable to evaluate 'db/schema.rb' (#{e.message})"
  end
  add_to_archive  %Q|endmodule\n\n|
end

.baselineObject



238
239
240
241
242
243
# File 'lib/veracode.rb', line 238

def self.baseline
  self.update
  @baseline_objects = @objects
  @baseline_modules = @modules
  @baseline_classes = @classes
end

.class_header(c) ⇒ Object

Archiving Headers



459
460
461
462
463
464
465
466
467
468
469
470
471
472
473
474
475
476
477
478
479
# File 'lib/veracode.rb', line 459

def self.class_header(c)
  begin
    return "" unless c.is_a? Class

    puts "  class header" if $options[:verbose]

    case
    when c.superclass.nil? # this should only happen for BasicObject
      return ""
    when c.superclass.name.nil? # in case the parent is anonymous
      name = c.superclass.to_s.dump
    else
      name = c.superclass.name.dump
    end

    "superclass #{name}\n"
  rescue Exception => e
    log_error e.message
    return ""
  end
end

.cleanupObject



221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
# File 'lib/veracode.rb', line 221

def self.cleanup
  [@disasmlog_filename, @errorlog_filename, @index_filename, @manifest_filename, @gems_filename, @version_filename].each {|f|
    begin
      File.delete(f)
    rescue Exception => e
      log_error "Unable to delete #{f.to_s.dump} (#{e.message})"
    end
  }

  begin
    Dir.delete(@archive_dirname)
  rescue Exception => e
    puts "Unable to remove #{@archive_dirname.to_s.dump} (#{e.message})"
    log_error "Unable to remove #{@archive_dirname.to_s.dump} (#{e.message})"
  end
end

.compile_erb_templatesObject



782
783
784
785
786
787
788
789
790
791
792
793
794
795
796
797
798
799
800
801
802
803
804
805
806
807
808
809
810
811
812
813
814
815
816
817
818
819
820
821
822
823
824
825
826
827
828
829
830
831
832
833
834
835
836
837
838
839
840
# File 'lib/veracode.rb', line 782

def self.compile_erb_templates

  # Rails 3 has wrapped Erubis to handle block helpers in ERB templates
  # a little differently, e.g.:
  #   <%= form_for ... do %> 
  # vs the normal ERB:
  #   <% form_for ... do %>
  # 
  # This means if Rails 3 erb templates are compiled with ERB or Erubis
  # the resulting ruby source code will contain syntax errors.
  # To avoid this, use the ActionView templates and handlers

  view_paths = []
  view_paths += ActionController::Base.view_paths.to_a.map(&:to_s)
  view_paths |= [File.expand_path("app/views")]

  puts "Looking for erb templates in #{view_paths.join(", ")}" if $options[:verbose]

  templates = view_paths.map { |vp|
    Dir[File.join(vp, "**", "*.erb")]
  }.flatten

  return unless templates.count > 0

  puts "Found #{templates.count} erb templates" if $options[:verbose]

  templates.each {|template|

    puts "Compiling template #{template}" if $options[:verbose]

    begin

      t = ActionView::Template.new(
        File.read(template),
        template,
        ActionView::Template::Handlers::ERB,
        :locals => [],
        :virtual_path => template
      )

      case t.method(:compile).arity
      when 1 # Rails 6
        t.send(:compile, @view)
      when 2 # Rails 3.1.0+
        t.send(:compile, ActionView::Base.new, ActionView::CompiledTemplates)
      when 3
        t.send(:compile, {}, ActionView::Base.new, ActionView::CompiledTemplates)
      end

    rescue Exception => e
      puts "Unable to compile template #{template}"
      log_error "Unable to compile template #{template} (#{e.message})"
    end

  }

  puts "Compiled templates: " + ActionView::CompiledTemplates.instance_methods.count.to_s if $options[:verbose] && !@rails6

end

.compile_haml_templatesObject



842
843
844
845
846
847
848
849
850
851
852
853
854
855
856
857
858
859
860
861
862
863
864
865
866
867
868
869
870
871
872
873
874
875
876
877
878
879
880
881
882
883
884
885
886
887
888
889
890
891
892
893
894
895
896
897
898
# File 'lib/veracode.rb', line 842

def self.compile_haml_templates

  view_paths = []
  view_paths += ActionController::Base.view_paths.to_a.map(&:to_s)
  view_paths |= [File.expand_path("app/views")]

  puts "Looking for haml templates in #{view_paths.join(", ")}" if $options[:verbose]

  templates = view_paths.map {|vp|
    Dir[File.join(vp, "**", "*.haml")]
  }.flatten

  return unless templates.count > 0

  begin
    cond_require 'action_view'
    cond_require 'haml'
    cond_require 'haml/template/plugin'
  rescue Exception => e
    log_error "Unable to satisfy haml dependencies (#{e.message})"
    return
  end

  puts "Found #{templates.count} haml templates" if $options[:verbose]

  templates.each {|template|

    puts "Compiling template #{template}" if $options[:verbose]

    begin

      t = ActionView::Template.new(
        File.read(template),
        template,
        Haml::Plugin,
        :virtual_path => template
      )

      case t.method(:compile).arity
      when 1 # Rails 6
        t.send(:compile, @view) 
      when 2 # Rails 3.1.0+
        t.send(:compile, ActionView::Base.new, ActionView::CompiledTemplates)
      when 3
        t.send(:compile, {}, ActionView::Base.new, ActionView::CompiledTemplates)
      end

    rescue Exception => e
      puts "Unable to compile template #{template}"
      log_error "Unable to compile template #{template} (#{e.message})"
    end

  }

  puts "Compiled templates: " + ActionView::CompiledTemplates.instance_methods.count.to_s if $options[:verbose] && !@rails6

end

.compile_templatesObject



714
715
716
717
718
719
720
721
722
723
724
725
726
727
728
729
730
731
732
733
734
735
736
737
738
739
740
741
742
743
744
745
746
747
748
749
750
751
752
753
754
755
756
757
758
759
760
761
762
763
764
765
766
767
768
769
770
771
772
773
774
775
776
777
778
779
780
# File 'lib/veracode.rb', line 714

def self.compile_templates

  begin
    cond_require 'action_view' unless defined? ActionView
    cond_require 'action_controller' unless defined? ActionController
  rescue Exception => e
    log_error "Unable to satisfy haml dependencies (#{e.message})"
    return
  end

  types = %w{ erb builder haml }
  
  view_paths = []
  view_paths += ActionController::Base.view_paths.to_a.map(&:to_s)
  view_paths |= [File.expand_path("app/views")]

  puts "Looking for templates in #{view_paths.join(", ")}" if $options[:verbose]

  templates = view_paths.map { |vp|
    Dir[File.join(vp, "**", "*.erb")] + 
    Dir[File.join(vp, "**", "*.builder")] + 
    Dir[File.join(vp, "**", "*.haml")]
  }.flatten

  return unless templates.count > 0

  puts "Found #{templates.count} templates" if $options[:verbose]
  log_error "Found #{templates.count} templates"

  haml_templates = templates.grep(/\.haml$/)
  if haml_templates.any?
    begin
      cond_require 'haml' unless defined? Haml
      cond_require 'haml/template/plugin' unless defined? Haml::Plugin
    rescue Exception => e
      puts "Unable to satisfy haml dependencies"
      log_error "Unable to satisfy haml dependencies (#{e.message})"
      templates -= haml_templates
      puts "      #{templates.count} templates" if $options[:verbose]
    end
  end

  assigns = {}
  view = ActionView::Base.new(view_paths, assigns)
  begin
      
  rescue Exception => e
    log_error "Unable to get controller view context (#{e.message})"
  end

  templates.each { |template|
    puts "Compiling template #{template}" if $options[:verbose]

    begin
      # This render will fail, but will trigger compilation of template
      view.render(:file => template)
    rescue Exception => e
      log_error "Compiled template #{template} #{e.message}"
    end
  }

  unless @rails6
    puts "Compiled #{ActionView::CompiledTemplates.instance_methods.count.to_s} templates" if $options[:verbose]
    log_error "Compiled #{ActionView::CompiledTemplates.instance_methods.count.to_s} templates"
    log_error "Not all templates were compiled" if ActionView::CompiledTemplates.instance_methods.count < templates.count
  end
end

.cond_require(lib) ⇒ Object

Helpers



265
266
267
268
269
270
271
272
273
274
275
# File 'lib/veracode.rb', line 265

def self.cond_require(lib)
  if @required_libs.add?(lib)
    begin
      return require lib
    rescue Exception => e
      puts "(failed: require #{lib} #{e.message})" if $options[:verbose]
      log_error "Unable to require #{lib} (#{e.message})"
    end
  end
  return false
end

.finalize_archiveObject



412
413
414
# File 'lib/veracode.rb', line 412

def self.finalize_archive
  @disasmlog.close unless @disasmlog.nil?
end

.format_constant(c_symbol, c) ⇒ Object



449
450
451
452
453
454
# File 'lib/veracode.rb', line 449

def self.format_constant(c_symbol, c)
  puts "  constant #{quote(c_symbol)}" if $options[:verbose]

  "constant %s %s%s\n" % 
    [quote(c.class), quote(c_symbol), ( good_type?(c) ? " = #{safe_inspect(c)}" : "")]
end

.format_method(m, kind, with_disasm = true) ⇒ Object



424
425
426
427
428
429
430
431
432
433
434
435
436
437
438
439
440
# File 'lib/veracode.rb', line 424

def self.format_method(m, kind, with_disasm=true)
  return "" unless ((m.is_a? Method ) || (m.is_a? UnboundMethod))

  puts "  #{kind}_method #{quote(safe_name(m))}" if $options[:verbose]

  formatted = "#{kind}_method #{quote(safe_name(m))} #{m.parameters.to_s}\n"

  if with_disasm
    insns = RubyVM::InstructionSequence.disassemble(m)
    formatted += ( (insns.nil? || insns.empty? || insns[/.*#{@expanded_app_dir}.*/].nil?) ? 
                   "\n" :
                   "#{insns}== end disasm\n" 
                 )
  end

  formatted
end

.format_variable(v_symbol, v, kind) ⇒ Object



442
443
444
445
446
447
# File 'lib/veracode.rb', line 442

def self.format_variable(v_symbol, v, kind)
  puts "  #{quote(kind)} variable #{quote(v_symbol)}" if $options[:verbose]

  "#{kind}_variable %s %s%s\n" % 
    [quote(v.class), quote(v_symbol), ( good_type?(v) ? " = #{safe_inspect(v)}" : "")]
end

.glob_require(files) ⇒ Object



277
278
279
280
281
282
283
284
285
286
287
288
289
290
291
292
293
294
295
296
297
# File 'lib/veracode.rb', line 277

def self.glob_require(files)
  any_new = false
  total, count = 0, 0
  Dir.glob(files) do |f|
    print "Requiring #{f.to_s} " if $options[:verbose]
    
    begin
      required = require File.expand_path(f)
    rescue Exception => e
      puts "(failed: #{e.message})" if $options[:verbose]
      log_error "Unable to require #{File.expand_path(f).to_s.dump} (#{e.message})"
    else
      puts "(OK: #{(required ? "required" : "already required")})" if $options[:verbose]
    end
    any_new |= required
    total += 1
    count += 1 if required
  end
  puts "#{count}/#{total} files were required" if $options[:verbose]
  any_new
end

.good_type?(o) ⇒ Boolean

Returns:

  • (Boolean)


353
354
355
356
357
358
359
360
361
362
363
364
365
366
367
368
369
370
371
372
# File 'lib/veracode.rb', line 353

def self.good_type?(o)
  %w{
      Array
      Bignum
      Class
      FalseClass
      Fixnum
      Float
      Hash
      Module
      NilClass
      Range
      Rational
      Regexp
      String
      Symbol
      Time
      TrueClass
    }.include?(o.class.to_s)
end

.index_applicationObject



144
145
146
147
148
149
150
# File 'lib/veracode.rb', line 144

def self.index_application
  File.open(@index_filename, "wb") {|index_file|
    Dir[File.join("**","*")].keep_if {|f| File.file?(f)}.sort.each {|f|
      index_file.puts f.dump
    }
  }    
end

.initObject



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
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
# File 'lib/veracode.rb', line 41

def self.init
  if Gem::Dependency.new('', '~> 2.2.0').match?('', RUBY_VERSION.dup)
    $stderr.puts "Ruby 2.2 is not supported, please consult the compilation guide for all supported Ruby versions"
    exit
  end

  @run_id = Time.now.strftime("%Y%m%d%H%M%S")
  @archive_dirname = File.join("tmp","veracode-#{@run_id}")
  @required_libs.merge(["pathname", "set", "zlib", "zip/zip", "veracode"])

  if !Dir.exist?("tmp")
    begin
      Dir.mkdir("tmp")
    rescue Exception => e
      $stderr.puts "Directory 'tmp' does not exist and cannot be created: #{e.message}"
      exit
    end
  end

  while Dir.exist?(@archive_dirname)
    @run_id = Time.now.strftime("%Y%m%d%H%M%S")
    @archive_dirname = File.join("tmp","veracode-#{@run_id}")
  end

  begin
    Dir.mkdir(@archive_dirname)
  rescue Exception => e
    $stderr.puts "Unable to make directory #{@archive_dirname}: #{e.message}"
    exit
  end

  @archive_filename   = File.join("tmp","veracode-#{APP_NAME}-#{@run_id}.zip")

  @errorlog_filename  = File.join(@archive_dirname, @errorlog_filename)
  @disasmlog_filename = File.join(@archive_dirname, @disasmlog_filename)
  @index_filename     = File.join(@archive_dirname, @index_filename)
  @manifest_filename  = File.join(@archive_dirname, @manifest_filename)
  @gems_filename      = File.join(@archive_dirname, @gems_filename)
  @version_filename   = File.join(@archive_dirname, @version_filename)

  # Try touching each of the files to be written
  [@disasmlog_filename, @errorlog_filename, @index_filename, @manifest_filename, @gems_filename, @version_filename].each {|f|
    begin
      File.open(f, "wb") {}
    rescue Exception => e
      $stderr.puts "Unable to create file #{f}: #{e.message}"
      exit
    else
      @manifest << f
    end
  }

  begin
    @errorlog = File.open(@errorlog_filename, "wb")
    log_error "COMMAND: #{COMMAND}"
    log_error "RUBY_DESCRIPTION: #{RUBY_DESCRIPTION}"
    log_error "RAILS_VERSION: " + `rails --version`.chomp
    log_error "GEM_VERSION: #{Veracode::VERSION}"
    log_error "ARCHIVE_VERSION: #{Veracode::ARCHIVE_VERSION}"
    log_error "PWD: #{Dir.pwd.to_s.dump}"
    log_error "APP_NAME: #{APP_NAME.dump}"
    log_error "RUNID: #{@run_id}"
  rescue Exception => e
    $stderr.puts "Unable to create errorlog #{@errorlog_filename}: #{e.message}"
    @errorlog = $stderr
  else
    STDERR.reopen(@errorlog)
  end

  begin
    File.open(@version_filename, "wb") {|version_file|
      version_file.puts Veracode::ARCHIVE_VERSION
    }
  rescue Exception => e
    log_error "Unable to write to archive version file #{@version_filename}: #{e.message}"
  end

  list_gems

  index_application

  @manifest += Dir.glob("*").keep_if {|f| File.file?(f)}

  #{app config db doc lib log public script test tmp vendor}
  %w{app config lib log public script}.each {|dirname|
    @manifest += Dir[File.join(dirname, "**", "*")].keep_if {|f| File.file?(f)}
  }
  @manifest += Dir[File.join("vendor", "**", "*.rb")]
  @manifest += Dir[File.join("db", "**", "*.rb")]

  if $options[:archive_source]
    # Add any other ruby files not already added
    @manifest |= Dir[File.join("**","*.rb")]
    # Add any other erb files not already added
    @manifest |= Dir[File.join("**","*.erb")]
    # Add any other builder files not already added
    @manifest |= Dir[File.join("**","*.builder")]
    # Add any other haml files not already added
    @manifest |= Dir[File.join("**","*.haml")]
  end
  
end

.list_gemsObject



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
# File 'lib/veracode/gems.rb', line 19

def self.list_gems

  gems = `bundle list`.each_line
                      .reject {|line| line !~ /^  \* /}
                      .map {|line| line[4..-1]}
                      .map {|line| line.split.first}

  begin
    File.open(@gems_filename, "wb") {|gems_file|
      gems_file.puts '<messages>'
      gems.each {|gem|
        gems_file << "<message>\n  <platform>ruby</platform>\n  <name>\#{gem}</name>\n  <detailed_message>\#{gem}</detailed_message>\n  <token>\#{gem}</token>\n  <package>rubygem.\#{gem}</package>\n  <errorlevel>\#{(SupportedGems.include?(gem) ? \"info\" : \"warn\" )}</errorlevel>\n  <type>framework_unsupported</type>\n</message>\n"
      }
      gems_file.puts '</messages>'
    }
  rescue Exception => e
    log_error "Unable to write to gem list to file #{@gems_filename}: #{e.message}"
  end

end

.log_error(data) ⇒ Object



392
393
394
# File 'lib/veracode.rb', line 392

def self.log_error(data)
  @errorlog.printf "veracode [%s] %s\n", Time.now.to_s, data.to_s.chomp
end

.module_contents(m, with_disasm = true) ⇒ Object

Archiving Contents



512
513
514
515
516
517
518
519
520
521
522
523
524
525
526
527
528
529
530
531
532
533
534
535
536
537
538
539
540
541
542
543
544
545
546
547
548
549
550
551
552
553
554
555
556
557
558
559
560
561
562
563
564
565
566
567
568
569
570
571
572
573
574
575
576
577
578
579
580
581
582
583
584
# File 'lib/veracode.rb', line 512

def self.module_contents(m, with_disasm=true)
  return "" unless m.is_a? Module

  puts "  module contents" if $options[:verbose]

  formatted_contents = ""

  constants_method = m.method(:constants)
  original_constants_method = Module.instance_method(:constants)

  if constants_method != original_constants_method
    puts "  constants method has been overridden, fall back to original method" if $options[:verbose]
    constants = original_constants_method.bind(m).call($options[:include_inherited])
  else
    constants = m.constants($options[:include_inherited])
  end

  constants.each do |c_symbol|
    begin
      c = m.const_get(c_symbol) if m.const_defined? c_symbol
      formatted_contents += format_constant(c_symbol, c)
    rescue Exception => e
      log_error "Error archiving constant #{c_symbol.to_s.dump}: #{e.message}"
      formatted_contents += format_constant(c_symbol, :veracode_nil)
    end
  end

  m.class_variables.each do |v_symbol|
    begin
      v = m.class_variable_get(v_symbol)
      formatted_contents += format_variable(v_symbol, v, "class")
    rescue Exception => e
      log_error "Error archiving class variable #{v_symbol.to_s.dump}: #{e.message}"
      formatted_contents += format_variable(v_symbol, :veracode_nil, "class")
    end
  end

  begin
    if m == Kernel
      m.global_variables.each do |v_symbol|
        begin
          v = eval(v_symbol.to_s)
          formatted_contents += format_variable(v_symbol, v, "global")
        rescue Exception => e
          log_error "Error archiving global variable #{v_symbol.to_s.dump}: #{e.message}"
          formatted_contents += format_variable(v_symbol, :veracode_nil, "global")
        end
      end        
    end
  rescue Exception => e
    # m.respond_to?(:global_variables) was throwing exceptions
  end

  begin
    %w[ public protected private ].each {|p|
      get_methods = (p + "_instance_methods").to_sym
      if m.respond_to?(get_methods) && m.__send__(get_methods, $options[:include_inherited]).count > 0
        m.__send__(get_methods, $options[:include_inherited]).each do |m_symbol|
          begin
            method = m.instance_method(m_symbol)
            formatted_contents += format_method(method, "#{p.to_s}_instance", with_disasm)
          rescue Exception => e
            log_error "Error archiving #{p.to_s} instance method #{m_symbol.to_s.dump}: #{e.message}"
          end
        end
      end
    }
  rescue Exception => e
    # m.respond_to?(get_methods)
  end

  formatted_contents
end

.module_header(m) ⇒ Object



481
482
483
484
485
486
487
488
489
490
491
492
493
494
495
496
497
498
499
500
501
502
503
504
505
506
507
# File 'lib/veracode.rb', line 481

def self.module_header(m)
  return "" unless m.is_a? Module

  puts "  module header" if $options[:verbose]

  formatted_contents = ""

  begin
    formatted_contents += ( m.included_modules.count > 0 ? 
        m.included_modules.map {|m| "include #{m.inspect.dump}\n" }.join : 
        ""
      )
  rescue Exception => e
    log_error "Error archiving module header #{m.inspect.dump}: #{e.message}"
  end

  begin
      formatted_contents += ( m.respond_to?(:singleton_class) && m.singleton_class.included_modules.count > 0 ? 
          m.singleton_class.included_modules.map {|m| "extend #{m.inspect.dump}\n" }.join : 
          ""
        )
  rescue Exception => e
    log_error "Error archiving module header #{m.inspect.dump}: #{e.message}"
  end

  return formatted_contents
end

.object_contents(o, with_disasm = true) ⇒ Object



586
587
588
589
590
591
592
593
594
595
596
597
598
599
600
601
602
603
604
605
606
607
608
609
610
611
612
613
614
615
616
617
618
619
620
621
622
623
624
625
626
627
628
629
630
631
632
# File 'lib/veracode.rb', line 586

def self.object_contents(o, with_disasm=true)
  begin
    return "" unless !o.nil?
  rescue Exception => e
    log_error "Error testing #{o} with nil?. Probable monkey patching. #{e.message}"
    return "" if o == nil
  end

  return "" unless o.is_a?(Object)

  puts "  object contents" if $options[:verbose]

  formatted_contents = ""
  
  begin
    if o.respond_to?(:instance_variables) && o.instance_variables.count > 0
      o.instance_variables.each do |v_symbol|
        begin
          v = o.instance_variable_get(v_symbol)
          formatted_contents += format_variable(v_symbol, v, "instance")
        rescue Exception => e
          log_error "Error archiving instance variable #{v_symbol.to_s.dump}: #{e.message}"
          formatted_contents += format_variable(v_symbol, :veracode_nil, "instance")
        end
      end
    end
  rescue Exception => e
    log_error "Error getting :instance_variables for object #{o}: #{e.message}"
  end

  begin
    if o.respond_to?(:singleton_methods) && o.singleton_methods($options[:include_inherited]).count > 0
      o.singleton_methods($options[:include_inherited]).each do |m_symbol|
        begin
          m = o.method(m_symbol)
          formatted_contents += format_method(m, "singleton", with_disasm)
        rescue Exception => e
          log_error "Error archiving singleton method #{m_symbol.to_s.dump}: #{e.message}"
        end
      end
    end
  rescue Exception => e
    log_error "Error getting :singleton_methods for object #{o}: #{e.message}"
  end

  formatted_contents
end

.pack_manifestObject



152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
# File 'lib/veracode.rb', line 152

def self.pack_manifest

  puts "Archiving disassembly and source files"

  begin
    File.open(@manifest_filename, "wb") { |mf|
      @manifest.sort.each { |f|
        mf.puts f.to_s.dump        
      }
    }
  rescue Exception => e
    log_error "Unable to write manifest file #{@manifest_filename}: #{e.message}"
    puts "Unable to write manifest file #{@manifest_filename}: #{e.message}"
  end

  @errorlog.flush

  begin
    if Gem.loaded_specs.keys.include?("zipruby")
      log_error "zipruby gem detected, using it instead of rubyzip for creating archive"
      @errorlog.flush
      Zip::Archive.open(@archive_filename, Zip::CREATE) { |ar|
        @manifest.each { |file|

          if file.start_with?(@archive_dirname)
            name_in_archive = file.sub(/^#{@archive_dirname + File::SEPARATOR}/,"")
          else
            name_in_archive = File.join(APP_NAME, file)
          end        

          puts "Adding #{file} to archive as #{name_in_archive}" if $options[:verbose]
          ar.add_file(name_in_archive, file)
        }
      }
    else
      Zip.write_zip64_support = true
      zipper = -> (zf) { 
        @manifest.each { |file|
          if file.start_with?(@archive_dirname)
            name_in_archive = file.sub(/^#{@archive_dirname + File::SEPARATOR}/,"")
          else
            name_in_archive = File.join(APP_NAME, file)
          end        

          puts "Adding #{file} to archive as #{name_in_archive}" if $options[:verbose]
          zf.add(name_in_archive, file)
        }
      }
      if defined?(Zip::File::CREATE) 
        # rubyzip 2.X
        Zip::File.open(@archive_filename, Zip::File::CREATE) { |zf| zipper.call(zf) }
      else 
        #rubyzip 3.X
        Zip::File.open(@archive_filename, create: true) { |zf| zipper.call(zf) }
      end
    end
  rescue Exception => e
    log_error "Unable to create archive #{@manifest_filename}: #{e.message}"
    puts "Unable to create archive #{@manifest_filename}: #{e.message}"
    exit
  end

  if $options[:snapshot]
    puts "Please provide #{@archive_filename} to veracode for further investigation."
  else
    puts "Please upload #{@archive_filename}"
  end
end

.prepareObject

Subcommands



958
959
960
961
962
963
964
965
966
967
968
969
970
971
972
973
974
975
976
977
978
979
980
981
982
983
984
985
986
987
988
989
990
991
992
993
994
995
996
997
998
999
1000
1001
1002
1003
1004
1005
1006
1007
1008
1009
1010
1011
1012
1013
1014
1015
1016
1017
1018
1019
1020
1021
1022
1023
1024
1025
1026
1027
1028
1029
1030
1031
1032
1033
1034
1035
1036
1037
1038
1039
1040
1041
1042
1043
1044
1045
1046
1047
1048
1049
1050
1051
1052
1053
1054
1055
1056
1057
1058
1059
1060
1061
1062
1063
1064
1065
1066
1067
1068
1069
1070
1071
1072
1073
1074
1075
1076
1077
1078
1079
1080
1081
1082
1083
1084
1085
1086
1087
1088
1089
1090
1091
1092
1093
1094
1095
1096
1097
1098
1099
1100
1101
1102
1103
1104
1105
1106
1107
1108
1109
1110
1111
1112
1113
1114
1115
1116
1117
1118
1119
1120
1121
1122
1123
1124
1125
1126
1127
1128
1129
1130
1131
1132
1133
1134
1135
1136
1137
# File 'lib/veracode.rb', line 958

def self.prepare

  init

  puts "Preparing Ruby on Rails application #{APP_NAME.dump} for Veracode upload"
  puts "Source code will be included in the archive" if $options[:archive_source]

  if $options[:verbose]
    puts Dir.pwd.to_s.dump
    puts
  end


  ################################################################
  ## phase 1 - Create baseline
  self.baseline
  
  puts "Phase 1 - Initial State" if $options[:verbose]
  self.stats if $options[:verbose]
  
  ## /phase 1 - Create baseline
  ################################################################



  ################################################################
  ## phase 2 - Require rails

  puts "Phase 2 - Load Rails" if $options[:verbose]
  begin
    if $options[:skipactiverecord] || $options[:skipactionview] || $options[:skipsprockets]
      require "active_model/railtie"
      require "active_record/railtie" unless $options[:skipactiverecord]
      require "action_controller/railtie"
      require "action_mailer/railtie"
      require "action_view/railtie" unless $options[:skipactionview]
      require "sprockets/railtie" unless $options[:skipsprockets]
      require "rails/test_unit/railtie"
    else 
      require "rails/all"
    end
  rescue Exception => e
    puts "Unable to require rails: #{e.message}"
    log_error "Unable to require rails: #{e.message}"
    exit
  else
    puts "Required rails" if $options[:verbose]
  end

  @rails6 = Gem::Version.new(Rails.version) >= Gem::Version.new("6.0.0")
  ## Imitate script/rails
  # APP_PATH = File.expand_path('config/application')
  # APP_PATH is already set in bin/veracode
  #require File.expand_path('../../config/boot',  __FILE__)
  glob_require "config/boot.rb"
  #require 'rails/commands'
    # this will trigger the console to be launched
    # ARGV.clear
    # ARGV << 'console'
    # ARGV << '--sandbox'
    # require 'rails/commands'

  ## Imitate rails/commands when console
  if @rails6 || Gem::Version.new(Rails.version) >= Gem::Version.new("5.1.0")
    cond_require 'rails/command.rb'
    cond_require 'rails/command/actions.rb'
    cond_require 'rails/command/base.rb'
    cond_require 'rails/command/behavior.rb'
    cond_require 'rails/command/environment_argument.rb'
    cond_require 'rails/commands/console/console_command.rb'
  else 
    cond_require 'rails/commands/console.rb'
  end
  # require APP_PATH # => config/application.rb

  glob_require "config/application.rb"

  begin
    Rails.application.require_environment! unless $options[:skipenvironment]
  rescue Exception => e
    log_error "Unable to require environment: #{e.message}"
  end
  # Following line will actually kick off IRB
  # Rails::Console.start(Rails.application)
  
  # Imitate Rails::Console.initialize_console
  # require "pp"
  cond_require "rails/console/app.rb"
  cond_require "rails/console/helpers.rb"

  if $options[:environment]
    @stdlib = $:
    @gemdir = Gem.dir

    require_libs(@stdlib)
    require_rails(@gemdir)
  end

  self.rebaseline

  self.stats if $options[:verbose]

  ## /phase 2 - Require rails
  ################################################################
  
  
  
  ################################################################
  # phase 3 - require app

  puts "Phase 3 - Imitate Rails" if $options[:verbose]

  begin
    any_new = true
    while any_new
      any_new = false
      any_new |= glob_require "lib/**/*.rb"
      any_new |= glob_require "app/**/*.rb"
      puts "new successful requires? #{any_new.to_s}" if $options[:verbose]
    end

    begin
      if @rails6
        self.update
        @view = ActionView::Base.with_empty_template_cache
        @view_methods = @view.compiled_method_container.instance_methods
        compile_erb_templates
        compile_haml_templates
        self.stats if $options[:verbose]
      else
        compile_templates
        self.update
        self.stats if $options[:verbose]
      end

      # Ensure compiled templates are fully disassembled in archive
      @baseline_modules.delete(ActionView::CompiledTemplates) unless @rails6
    rescue Exception => e
      puts "Unable to compile templates: #{e.message}" if $options[:verbose]
      log_error "Unable to compile templates: #{e.message}"
    end

    if $options[:environment]
      puts "Processing and disassembling environment"
      archive(@modules.reject  {|o| safe_name(o) =~ /^#<(Class|Module):0x[0-9a-f]+>/i }
                      .reject  {|o| safe_name(o) =~ /^Veracode/ }
                      .reject  {|o| safe_name(o) =~ /^EmptyRails/ }
                      .reject  {|o| safe_name(o) =~ /^ActionView::CompiledTemplates$/ }, false)
    else
      puts "Processing Ruby and Rails classes and modules"
      archive(@baseline_modules, false)
      add_to_archive "\n# Phase 3 - App disassembly\n"
      puts "Processing and disassembling #{APP_NAME} classes and modules"
      safe_baseline_modules = @baseline_modules.each_with_object(Set.new) { |o, s| s << safe_name(o) }
      archive(@modules.reject {|o| safe_baseline_modules.include?(safe_name(o))}, true)
      if @rails6
        archive_rails6_templates()
      end
      archive_schema

    end

  rescue Exception => e
    if $options[:snapshot]
      log_error e.message
      log_error e.backtrace.join("\n")
    else
      puts "Failed to prepare veracode archive. Please see #{@errorlog_filename}."
      raise
    end
  end

  ## /phase 3 - require app
  ################################################################

  finalize_archive
  pack_manifest
  cleanup

end

.prepare_archiveObject

Archiving



399
400
401
402
403
404
405
406
407
408
409
410
# File 'lib/veracode.rb', line 399

def self.prepare_archive
  @disasmlog = Zlib::GzipWriter.new(File.open(@disasmlog_filename, "wb"), nil, nil)
  @disasmlog.puts "#{RUBY_ENGINE}-#{RUBY_VERSION}-p#{RUBY_PATCHLEVEL}"
  if $options[:environment]
    @disasmlog.puts "# EnvironmentDef %s-%s_rails-%s" % [RUBY_ENGINE, RUBY_VERSION, Rails.version]
  else
    @disasmlog.puts "# Environment %s-%s_rails-%s" % [RUBY_ENGINE, RUBY_VERSION, Rails.version]
  end
  @disasmlog.puts "# Ruby #{RUBY_ENGINE}-#{RUBY_VERSION}"
  @disasmlog.puts "# Rails #{Rails.version}"
  @disasmlog.puts
end

.quote(o) ⇒ Object



345
346
347
# File 'lib/veracode.rb', line 345

def self.quote(o)
  o.to_s.dump
end

.quote_if_string(o) ⇒ Object



349
350
351
# File 'lib/veracode.rb', line 349

def self.quote_if_string(o)
  ( o.is_a?(String) ? o.dump : o.inspect )
end

.rebaselineObject



245
246
247
# File 'lib/veracode.rb', line 245

def self.rebaseline
  self.baseline
end

.require_libs(lib_paths) ⇒ Object



900
901
902
903
904
905
906
907
908
909
910
911
912
913
914
915
916
917
918
919
920
921
922
923
924
925
926
927
# File 'lib/veracode.rb', line 900

def self.require_libs(lib_paths)
    for lib_path in lib_paths
      dirsToProcess = [Pathname(lib_path)]
      until dirsToProcess.count == 0 || !Dir.exist?(dirsToProcess[0])
        currentDir = dirsToProcess.delete_at(0)
        for child in currentDir.children
          if child.directory?
            dirsToProcess[dirsToProcess.count] = child
            base = child.to_s.partition("#{lib_path}/")[2]
            lib = ""
            for part in base.split('/').reverse
              lib = "#{part}/#{lib}"
              lib = lib[0..lib.length-2] if lib[lib.length-1] == '/'
            begin
              if @rails6 && (lib =~ /node_modules/ || lib == 'debug')
                next
              end
              if cond_require lib
                puts "requiring #{lib}" if $options[:verbose]
              end
            rescue Exception => e
            end
          end
        end
      end
    end
  end
end

.require_rails(gemdir) ⇒ Object



929
930
931
932
933
934
935
936
937
938
939
940
941
942
943
944
945
946
947
948
949
950
951
952
953
954
# File 'lib/veracode.rb', line 929

def self.require_rails(gemdir)
  dirsToProcess = [Pathname(gemdir)]
  until dirsToProcess.count == 0
    currentDir = dirsToProcess.delete_at(0)
    for child in currentDir.children
      if child.directory?
        dirsToProcess[dirsToProcess.count] = child
      end
      base = child.to_s.partition("#{gemdir}/")[2]
      if base.index("action_controller") != nil || base.index("action_view") != nil || base.index("active_record") != nil
        lib = ""
        for part in base.split('/').reverse
          lib = "#{part}/#{lib}"
          lib = lib[0..lib.length-2] if lib[lib.length-1] == '/'
          lib.chomp!(File.extname(lib))
          begin
            if cond_require lib
              puts "requiring #{lib}" if $options[:verbose]
            end
          rescue Exception => e
          end
        end
      end
    end
  end
end

.restore_original_class_method(obj) ⇒ Object

Some Ruby devs override the ‘class` method. This is bad practice but is still done sometimes. For example: github.com/faker-ruby/faker/blob/v2.2.1/lib/faker/games/heroes_of_the_storm.rb#L11-L13 This messes with our ability to get the class name. So we detect this and if it is overriden we restore the original method from `Kernel`



333
334
335
336
337
338
339
340
341
342
343
# File 'lib/veracode.rb', line 333

def self.restore_original_class_method(obj)
  original_class_method = Kernel.instance_method(:class)

  class_method_owner = obj.method(:class).owner

  if class_method_owner != Kernel
    obj.define_singleton_method(:class) do
      original_class_method.bind(self).call
    end
  end
end

.safe_inspect(o) ⇒ Object



374
375
376
377
378
379
380
381
382
383
384
385
386
387
388
389
390
# File 'lib/veracode.rb', line 374

def self.safe_inspect(o)
  if o.is_a?(Array)
    "[" + 
      o.map {|i| safe_inspect(i) }.join(", ") + 
    "]"
  elsif o.is_a?(Hash)
    "{" + 
      o.map {|k,v| "#{safe_inspect(k)}=>#{safe_inspect(v)}" }.join(", ") + 
    "}"
  elsif o.is_a?(Module)
    safe_name(o)
  elsif good_type?(o)
    quote_if_string(o)
  else
    ":veracode_nil" # not a white-listed type
  end
end

.safe_name(o) ⇒ Object



299
300
301
302
303
304
305
306
307
308
309
310
311
312
313
314
315
316
317
318
319
320
321
322
323
324
325
326
# File 'lib/veracode.rb', line 299

def self.safe_name(o)
  begin
    restore_original_class_method(o)
    case 
    when o == ActiveSupport::TimeWithZone
      "ActiveSupport::TimeWithZone"
    when o.is_a?(Module)
      begin
        ( o.name.nil? ? o.to_s : o.name.to_s )
      rescue Exception => e
        begin
          log_error "Exception rescued trying to call .name on object. Object: #{o.inspect}. Exception: #{e.inspect}"
          ( o.nil? ? "nil" : o.to_s )
        rescue Exception => e
          log_error "Exception rescued trying to call .nil on object. Object: #{o.inspect}. Exception: #{e.inspect}"
          ( o == nil ? "nil" : o.to_s ) # in case of monkey patched nil?
        end
      end
    when o.is_a?(Method), o.is_a?(UnboundMethod)
      o.name.to_s
    else
      o.to_s
    end
  rescue Exception => e
    log_error "Exception rescued trying to get safe_name on object. Dropping from archive. Exception: #{e.inspect}"
    "Veracode" #should result in this being dropped from the archive since we can't get a safe name for it
  end
end

.statsObject



255
256
257
258
259
260
# File 'lib/veracode.rb', line 255

def self.stats
  puts "#{ObjectSpace.each_object.count.to_s} objects"
  puts "#{ObjectSpace.each_object(Module).count.to_s} modules"
  puts "#{ObjectSpace.each_object(Class).count.to_s} classes"
  puts
end

.updateObject



249
250
251
252
253
# File 'lib/veracode.rb', line 249

def self.update
  @objects = ObjectSpace.each_object.to_a
  @modules = ObjectSpace.each_object(Module).to_a
  @classes = ObjectSpace.each_object(Class).to_a
end