Class: PdfScanner::Scanner

Inherits:
Object
  • Object
show all
Defined in:
lib/pdf_scanner/scanner.rb

Constant Summary collapse

DEFAULT_CONFIG_FILE =
"#{File.dirname(__FILE__)}/config/pdfcop.conf.yml"
DEFAULT_POLICY =
"standard"
SECURITY_POLICIES =
{}
ANNOTATION_RIGHTS =
{
  FileAttachment: i[allowAttachments allowFileAttachmentAnnotation],
  Sound: i[allowSoundAnnotation],
  Movie: i[allowMovieAnnotation],
  Screen: i[allowScreenAnnotation],
  Widget: i[allowAcroforms],
  RichMedia: i[allowRichMediaAnnotation],
  :"3D" => i[allow3DAnnotation]
}

Instance Method Summary collapse

Constructor Details

#initialize(params = {}) ⇒ Scanner



23
24
25
26
27
28
29
30
31
32
# File 'lib/pdf_scanner/scanner.rb', line 23

def initialize(params = {})
  @options = {}
  @options[:output_log] = params[:output_log] if params[:output_log].present?
  @options[:target_file] = params[:target_file] if params[:target_file].present?
  @options[:config_file] = params[:config_file] if params[:config_file].present?
  @options[:policy] = params[:policy] if params[:policy].present?
  @options[:move_dir] = params[:dir] if params[:dir].present?
  @options[:password] = params[:passwd] if params[:passwd].present? # for encrypted file
  @errors = { rejected_policies: [], analysis_failure: [] }
end

Instance Method Details

#analyze_3d_annotation(annot) ⇒ Object



224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
# File 'lib/pdf_scanner/scanner.rb', line 224

def analyze_3d_annotation(annot)
  # 3D annotation might pull in JavaScript for real-time driven behavior.
  return unless annot.key?(:"3DD")

  dd = annot[:"3DD"].solve
  u3dstream = nil

  case dd
  when Origami::Stream
      u3dstream = dd
  when Origami::Dictionary
      u3dstream = dd[:"3DD"].solve
  end

  if u3dstream.is_a?(Stream) and u3dstream.key?(:OnInstantiate)
    check_rights(:allowJS)

    if annot.key?(:"3DA") # is 3d view instantiated automatically?
      u3dactiv = annot[:"3DA"].solve

      check_rights(:allowJSAtOpening) if u3dactiv.is_a?(Origami::Dictionary) and (u3dactiv.A == :PO or u3dactiv.A == :PV)
    end
  end
end

#analyze_action(action, triggered_at_opening, level = 0) ⇒ Object



272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
287
288
289
290
291
292
293
294
295
296
297
298
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
327
328
329
330
331
332
# File 'lib/pdf_scanner/scanner.rb', line 272

def analyze_action(action, triggered_at_opening, level = 0)
  if action.is_a?(Origami::Dictionary)
    type = action[:S].is_a?(Origami::Reference) ? action[:S].solve : action[:S]

    case type.value
    when :JavaScript
      check_rights(:allowJS)
      check_rights(:allowJSAtOpening) if triggered_at_opening
    when :Launch
      check_rights(:allowLaunchAction)
    when :Named
      check_rights(:allowNamedAction)
    when :GoTo
      check_rights(:allowGoToAction)
      dest = action[:D].is_a?(Origami::Reference) ? action[:D].solve : action[:D]
      if dest.is_a?(Origami::Array) and dest.length > 0 and dest.first.is_a?(Origami::Reference)
        dest_page = dest.first.solve
        if dest_page.is_a?(Origami::Page)
          analyze_page(dest_page, level + 1)
        end
      end
    when :GoToE
      check_rights(:allowAttachments,:allowGoToEAction)
    when :GoToR
      check_rights(:allowGoToRAction)
    when :Thread
      check_rights(:allowGoToRAction) if action.key?(:F)
    when :URI
      check_rights(:allowURIAction)
    when :SubmitForm
      check_rights(:allowAcroForms,:allowSubmitFormAction)
    when :ImportData
      check_rights(:allowAcroForms,:allowImportDataAction)
    when :Rendition
      check_rights(:allowScreenAnnotation,:allowRenditionAction)
    when :Sound
      check_rights(:allowSoundAnnotation,:allowSoundAction)
    when :Movie
      check_rights(:allowMovieAnnotation,:allowMovieAction)
    when :RichMediaExecute
      check_rights(:allowRichMediaAnnotation,:allowRichMediaAction)
    when :GoTo3DView
      check_rights(:allow3DAnnotation,:allowGoTo3DAction)
    end

    if action.key?(:Next)
      check_rights(:allowChainedActions)
      analyze_action(action.Next)
    end

  elsif action.is_a?(Origami::Array)
    dest = action
    if dest.length > 0 and dest.first.is_a?(Origami::Reference)
      dest_page = dest.first.solve
      if dest_page.is_a?(Origami::Page)
        check_rights(:allowGoToAction)
        analyze_page(dest_page, level + 1)
      end
    end
  end
end

#analyze_annotation(annot, _level = 0) ⇒ Object



214
215
216
217
218
219
220
221
222
# File 'lib/pdf_scanner/scanner.rb', line 214

def analyze_annotation(annot, _level = 0)
  check_rights(:allowAnnotations)

  if annot.is_a?(Origami::Dictionary) and annot.key?(:Subtype)
    check_annotation_rights(annot)

    analyze_3d_annotation(annot) if annot.Subtype.value == :"3D"
  end
end

#analyze_page(page, level = 0) ⇒ Object



249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
# File 'lib/pdf_scanner/scanner.rb', line 249

def analyze_page(page, level = 0)
  if page.is_a?(Origami::Dictionary)
    #
    # Checking page additional actions.
    #
    if page.key?(:AA)
      if page.AA.is_a?(Origami::Dictionary)

        aa = Origami::Page::AdditionalActions.new(page.AA); aa.parent = page.AA.parent
        analyze_action(aa.O, true, level + 1) if aa.key?(:O)
        analyze_action(aa.C, false, level + 1) if aa.key?(:C)
      end
    end

    #
    # Looking for page annotations.
    #
    page.each_annotation do |annot|
      analyze_annotation(annot, level + 1)
    end
  end
end

#analyze_xfa_forms(xfa) ⇒ Object



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
# File 'lib/pdf_scanner/scanner.rb', line 179

def analyze_xfa_forms(xfa)
  case xfa
  when Origami::Array then
    xml = ""
    i = 0
    xfa.each do |packet|
      if i % 2 == 1
        xml << packet.solve.data
      end

      i = i + 1
    end
  when Origami::Stream then
      xml = xfa.data
  else
      reject("Malformed XFA dictionary")
  end

  xfadoc = REXML::Document.new(xml)
  REXML::XPath.match(xfadoc, "//script").each do |script|
    case script.attributes["contentType"]
    when "application/x-formcalc" then
      check_rights(:allowFormCalc)
    else
      check_rights(:allowJS)
    end
  end
end

#check_annotation_rights(annot) ⇒ Object



208
209
210
211
212
# File 'lib/pdf_scanner/scanner.rb', line 208

def check_annotation_rights(annot)
  subtype = annot.Subtype.value

  check_rights(*ANNOTATION_RIGHTS[subtype]) if ANNOTATION_RIGHTS.include?(subtype)
end

#check_rights(*required_rights) ⇒ Object



173
174
175
176
177
# File 'lib/pdf_scanner/scanner.rb', line 173

def check_rights(*required_rights)
  current_rights = SECURITY_POLICIES["POLICY_#{@options[:policy].upcase}"]

  reject(required_rights) if required_rights.any?{|right| current_rights[right.to_s] == false}
end

#load_config_file(path) ⇒ Object



148
149
150
# File 'lib/pdf_scanner/scanner.rb', line 148

def load_config_file(path)
  SECURITY_POLICIES.update(Hash.new(false).update YAML.load(File.read(path)))
end

#quarantine(file, quarantine_folder) ⇒ Object



164
165
166
167
168
169
170
171
# File 'lib/pdf_scanner/scanner.rb', line 164

def quarantine(file, quarantine_folder)
  digest = Digest::SHA256.file(file)
  ext = File.extname(file)
  dest_name = "#{File.basename(file, ext)}_#{digest}#{ext}"
  dest_path = File.join(quarantine_folder, dest_name)

  FileUtils.move(file, dest_path)
end

#reject(cause, exception_message = nil) ⇒ Object



152
153
154
155
156
157
158
159
160
161
162
# File 'lib/pdf_scanner/scanner.rb', line 152

def reject(cause, exception_message = nil)
  if @options.key?(:move_dir)
    quarantine(@options[:target_file], @options[:move_dir])
  end

  if exception_message.nil?
    @errors[:rejected_policies] << { policy: @options[:policy], message: cause.inspect }
  else
    @errors[:analysis_failure] << { error: exception_message.to_s, message: cause.inspect }
  end
end

#scanObject



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
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
143
144
145
146
# File 'lib/pdf_scanner/scanner.rb', line 34

def scan
  begin
    @errors = { rejected_policies: [], analysis_failure: [] }
    if !@options.key?(:policy)
      @options[:policy] = DEFAULT_POLICY
    end

    if @options.key?(:move_dir) and !File.directory?(@options[:move_dir])
      abort "Error: #{@options[:move_dir]} is not a valid directory."
    end

    load_config_file(@options[:config_file] || DEFAULT_CONFIG_FILE)

    unless SECURITY_POLICIES.key?("POLICY_#{@options[:policy].upcase}")
      return "Undeclared policy `#{@options[:policy]}'"
    end

    @pdf = Origami::PDF.read(@options[:target_file],
      verbosity: Origami::Parser::VERBOSE_QUIET,
      ignore_errors: SECURITY_POLICIES["POLICY_#{@options[:policy].upcase}"]['allowParserErrors'],
      decrypt: SECURITY_POLICIES["POLICY_#{@options[:policy].upcase}"]['allowEncryption'],
      prompt_password: lambda { '' },
      password: @options[:password]
    )

    if @pdf.encrypted?
      check_rights(:allowEncryption)
    end

    catalog = @pdf.Catalog
    reject("Invalid document catalog") unless catalog.is_a?(Origami::Catalog)

    if catalog.key?(:OpenAction)
      check_rights(:allowOpenAction)
      action = catalog.OpenAction
      analyze_action(action, true, 1)
    end

    if catalog.key?(:AA)
      if catalog.AA.is_a?(Origami::Dictionary)
        aa = Origami::CatalogAdditionalActions.new(catalog.AA); aa.parent = catalog;
        analyze_action(aa.WC, false, 1) if aa.key?(:WC)
        analyze_action(aa.WS, false, 1) if aa.key?(:WS)
        analyze_action(aa.DS, false, 1) if aa.key?(:DS)
        analyze_action(aa.WP, false, 1) if aa.key?(:WP)
        analyze_action(aa.DP, false, 1) if aa.key?(:DP)
      end
    end

    if catalog.key?(:AcroForm)
      acroform = catalog.AcroForm
      if acroform.is_a?(Origami::Dictionary)
        check_rights(:allowAcroForms)
        if acroform.key?(:XFA)
          check_rights(:allowXFAForms)

          analyze_xfa_forms(acroform[:XFA].solve)
        end
      end
    end

    if @pdf.each_named_script.any?
      check_rights(:allowJS)
      check_rights(:allowJSAtOpening)
    end

    if @pdf.each_attachment.any?
      check_rights(:allowAttachments)
    end

    @pdf.each_page do |page|
      analyze_page(page, 1)
    end

    @pdf.each_object.select{|obj| obj.is_a?(Origami::Stream)}.each do |stream|
      if stream.dictionary.key?(:Filter)
        filters = stream.Filter
        filters = [ filters ] if filters.is_a?(Origami::Name)

        if filters.is_a?(Origami::Array)
          filters.each do |filter|
            case filter.value
            when :ASCIIHexDecode
              check_rights(:allowASCIIHexFilter)
            when :ASCII85Decode
              check_rights(:allowASCII85Filter)
            when :LZWDecode
              check_rights(:allowLZWFilter)
            when :FlateDecode
              check_rights(:allowFlateDecode)
            when :RunLengthDecode
              check_rights(:allowRunLengthFilter)
            when :CCITTFaxDecode
              check_rights(:allowCCITTFaxFilter)
            when :JBIG2Decode
              check_rights(:allowJBIG2Filter)
            when :DCTDecode
              check_rights(:allowDCTFilter)
            when :JPXDecode
              check_rights(:allowJPXFilter)
            when :Crypt
              check_rights(:allowCryptFilter)
            end
          end
        end
      end
    end
  rescue StandardError => ex
    reject("Analysis failure", ex)
  end

  @errors
end