Repository: mozilla/observatory-cli
Branch: master
Commit: 708a212d5f33
Files: 11
Total size: 44.6 KB
Directory structure:
gitextract_rmd2s6vf/
├── .eslintrc.yml
├── .gitignore
├── CODE_OF_CONDUCT.md
├── Dockerfile
├── LICENSE
├── README.md
├── index.js
├── package.json
└── shell_functions/
├── bash_completion/
│ └── observatory.bash
├── docker_perms.sh
└── observatory.sh
================================================
FILE CONTENTS
================================================
================================================
FILE: .eslintrc.yml
================================================
env:
browser: true
es6: true
node: true
extends:
- eslint:recommended
- plugin:node/recommended
plugins:
- node
- promise
root: true
rules:
comma-dangle: off
curly: warn
eol-last: error
eqeqeq: error
handle-callback-err: error
indent: [error, 2, {SwitchCase: 1}]
no-console: off
no-multi-spaces: error
no-unused-vars: [error, {vars: all, args: none}]
one-var: [error, never]
quotes: [error, double]
semi: [error, always]
node/no-unpublished-bin: error
promise/param-names: error
promise/always-return: error
promise/catch-or-return: error
promise/no-native: off
================================================
FILE: .gitignore
================================================
node_modules
npm-shrinkwrap.json
*.log
================================================
FILE: CODE_OF_CONDUCT.md
================================================
# Community Participation Guidelines
This repository is governed by Mozilla's code of conduct and etiquette guidelines.
For more details, please read the
[Mozilla Community Participation Guidelines](https://www.mozilla.org/about/governance/policies/participation/).
## How to Report
For more information on how to report violations of the Community Participation Guidelines, please read our '[How to Report](https://www.mozilla.org/about/governance/policies/participation/reporting/)' page.
================================================
FILE: Dockerfile
================================================
FROM node:alpine
MAINTAINER https://github.com/mozilla/observatory-cli
RUN adduser -h /home/observatory -g "Observatory CLI User" -s /bin/ash -D observatory
RUN npm install -g observatory-cli
USER observatory
WORKDIR /home/observatory
ENTRYPOINT ["observatory"]
CMD ["--help"]
================================================
FILE: LICENSE
================================================
Mozilla Public License Version 2.0
==================================
1. Definitions
--------------
1.1. "Contributor"
means each individual or legal entity that creates, contributes to
the creation of, or owns Covered Software.
1.2. "Contributor Version"
means the combination of the Contributions of others (if any) used
by a Contributor and that particular Contributor's Contribution.
1.3. "Contribution"
means Covered Software of a particular Contributor.
1.4. "Covered Software"
means Source Code Form to which the initial Contributor has attached
the notice in Exhibit A, the Executable Form of such Source Code
Form, and Modifications of such Source Code Form, in each case
including portions thereof.
1.5. "Incompatible With Secondary Licenses"
means
(a) that the initial Contributor has attached the notice described
in Exhibit B to the Covered Software; or
(b) that the Covered Software was made available under the terms of
version 1.1 or earlier of the License, but not also under the
terms of a Secondary License.
1.6. "Executable Form"
means any form of the work other than Source Code Form.
1.7. "Larger Work"
means a work that combines Covered Software with other material, in
a separate file or files, that is not Covered Software.
1.8. "License"
means this document.
1.9. "Licensable"
means having the right to grant, to the maximum extent possible,
whether at the time of the initial grant or subsequently, any and
all of the rights conveyed by this License.
1.10. "Modifications"
means any of the following:
(a) any file in Source Code Form that results from an addition to,
deletion from, or modification of the contents of Covered
Software; or
(b) any new file in Source Code Form that contains any Covered
Software.
1.11. "Patent Claims" of a Contributor
means any patent claim(s), including without limitation, method,
process, and apparatus claims, in any patent Licensable by such
Contributor that would be infringed, but for the grant of the
License, by the making, using, selling, offering for sale, having
made, import, or transfer of either its Contributions or its
Contributor Version.
1.12. "Secondary License"
means either the GNU General Public License, Version 2.0, the GNU
Lesser General Public License, Version 2.1, the GNU Affero General
Public License, Version 3.0, or any later versions of those
licenses.
1.13. "Source Code Form"
means the form of the work preferred for making modifications.
1.14. "You" (or "Your")
means an individual or a legal entity exercising rights under this
License. For legal entities, "You" includes any entity that
controls, is controlled by, or is under common control with You. For
purposes of this definition, "control" means (a) the power, direct
or indirect, to cause the direction or management of such entity,
whether by contract or otherwise, or (b) ownership of more than
fifty percent (50%) of the outstanding shares or beneficial
ownership of such entity.
2. License Grants and Conditions
--------------------------------
2.1. Grants
Each Contributor hereby grants You a world-wide, royalty-free,
non-exclusive license:
(a) under intellectual property rights (other than patent or trademark)
Licensable by such Contributor to use, reproduce, make available,
modify, display, perform, distribute, and otherwise exploit its
Contributions, either on an unmodified basis, with Modifications, or
as part of a Larger Work; and
(b) under Patent Claims of such Contributor to make, use, sell, offer
for sale, have made, import, and otherwise transfer either its
Contributions or its Contributor Version.
2.2. Effective Date
The licenses granted in Section 2.1 with respect to any Contribution
become effective for each Contribution on the date the Contributor first
distributes such Contribution.
2.3. Limitations on Grant Scope
The licenses granted in this Section 2 are the only rights granted under
this License. No additional rights or licenses will be implied from the
distribution or licensing of Covered Software under this License.
Notwithstanding Section 2.1(b) above, no patent license is granted by a
Contributor:
(a) for any code that a Contributor has removed from Covered Software;
or
(b) for infringements caused by: (i) Your and any other third party's
modifications of Covered Software, or (ii) the combination of its
Contributions with other software (except as part of its Contributor
Version); or
(c) under Patent Claims infringed by Covered Software in the absence of
its Contributions.
This License does not grant any rights in the trademarks, service marks,
or logos of any Contributor (except as may be necessary to comply with
the notice requirements in Section 3.4).
2.4. Subsequent Licenses
No Contributor makes additional grants as a result of Your choice to
distribute the Covered Software under a subsequent version of this
License (see Section 10.2) or under the terms of a Secondary License (if
permitted under the terms of Section 3.3).
2.5. Representation
Each Contributor represents that the Contributor believes its
Contributions are its original creation(s) or it has sufficient rights
to grant the rights to its Contributions conveyed by this License.
2.6. Fair Use
This License is not intended to limit any rights You have under
applicable copyright doctrines of fair use, fair dealing, or other
equivalents.
2.7. Conditions
Sections 3.1, 3.2, 3.3, and 3.4 are conditions of the licenses granted
in Section 2.1.
3. Responsibilities
-------------------
3.1. Distribution of Source Form
All distribution of Covered Software in Source Code Form, including any
Modifications that You create or to which You contribute, must be under
the terms of this License. You must inform recipients that the Source
Code Form of the Covered Software is governed by the terms of this
License, and how they can obtain a copy of this License. You may not
attempt to alter or restrict the recipients' rights in the Source Code
Form.
3.2. Distribution of Executable Form
If You distribute Covered Software in Executable Form then:
(a) such Covered Software must also be made available in Source Code
Form, as described in Section 3.1, and You must inform recipients of
the Executable Form how they can obtain a copy of such Source Code
Form by reasonable means in a timely manner, at a charge no more
than the cost of distribution to the recipient; and
(b) You may distribute such Executable Form under the terms of this
License, or sublicense it under different terms, provided that the
license for the Executable Form does not attempt to limit or alter
the recipients' rights in the Source Code Form under this License.
3.3. Distribution of a Larger Work
You may create and distribute a Larger Work under terms of Your choice,
provided that You also comply with the requirements of this License for
the Covered Software. If the Larger Work is a combination of Covered
Software with a work governed by one or more Secondary Licenses, and the
Covered Software is not Incompatible With Secondary Licenses, this
License permits You to additionally distribute such Covered Software
under the terms of such Secondary License(s), so that the recipient of
the Larger Work may, at their option, further distribute the Covered
Software under the terms of either this License or such Secondary
License(s).
3.4. Notices
You may not remove or alter the substance of any license notices
(including copyright notices, patent notices, disclaimers of warranty,
or limitations of liability) contained within the Source Code Form of
the Covered Software, except that You may alter any license notices to
the extent required to remedy known factual inaccuracies.
3.5. Application of Additional Terms
You may choose to offer, and to charge a fee for, warranty, support,
indemnity or liability obligations to one or more recipients of Covered
Software. However, You may do so only on Your own behalf, and not on
behalf of any Contributor. You must make it absolutely clear that any
such warranty, support, indemnity, or liability obligation is offered by
You alone, and You hereby agree to indemnify every Contributor for any
liability incurred by such Contributor as a result of warranty, support,
indemnity or liability terms You offer. You may include additional
disclaimers of warranty and limitations of liability specific to any
jurisdiction.
4. Inability to Comply Due to Statute or Regulation
---------------------------------------------------
If it is impossible for You to comply with any of the terms of this
License with respect to some or all of the Covered Software due to
statute, judicial order, or regulation then You must: (a) comply with
the terms of this License to the maximum extent possible; and (b)
describe the limitations and the code they affect. Such description must
be placed in a text file included with all distributions of the Covered
Software under this License. Except to the extent prohibited by statute
or regulation, such description must be sufficiently detailed for a
recipient of ordinary skill to be able to understand it.
5. Termination
--------------
5.1. The rights granted under this License will terminate automatically
if You fail to comply with any of its terms. However, if You become
compliant, then the rights granted under this License from a particular
Contributor are reinstated (a) provisionally, unless and until such
Contributor explicitly and finally terminates Your grants, and (b) on an
ongoing basis, if such Contributor fails to notify You of the
non-compliance by some reasonable means prior to 60 days after You have
come back into compliance. Moreover, Your grants from a particular
Contributor are reinstated on an ongoing basis if such Contributor
notifies You of the non-compliance by some reasonable means, this is the
first time You have received notice of non-compliance with this License
from such Contributor, and You become compliant prior to 30 days after
Your receipt of the notice.
5.2. If You initiate litigation against any entity by asserting a patent
infringement claim (excluding declaratory judgment actions,
counter-claims, and cross-claims) alleging that a Contributor Version
directly or indirectly infringes any patent, then the rights granted to
You by any and all Contributors for the Covered Software under Section
2.1 of this License shall terminate.
5.3. In the event of termination under Sections 5.1 or 5.2 above, all
end user license agreements (excluding distributors and resellers) which
have been validly granted by You or Your distributors under this License
prior to termination shall survive termination.
************************************************************************
* *
* 6. Disclaimer of Warranty *
* ------------------------- *
* *
* Covered Software is provided under this License on an "as is" *
* basis, without warranty of any kind, either expressed, implied, or *
* statutory, including, without limitation, warranties that the *
* Covered Software is free of defects, merchantable, fit for a *
* particular purpose or non-infringing. The entire risk as to the *
* quality and performance of the Covered Software is with You. *
* Should any Covered Software prove defective in any respect, You *
* (not any Contributor) assume the cost of any necessary servicing, *
* repair, or correction. This disclaimer of warranty constitutes an *
* essential part of this License. No use of any Covered Software is *
* authorized under this License except under this disclaimer. *
* *
************************************************************************
************************************************************************
* *
* 7. Limitation of Liability *
* -------------------------- *
* *
* Under no circumstances and under no legal theory, whether tort *
* (including negligence), contract, or otherwise, shall any *
* Contributor, or anyone who distributes Covered Software as *
* permitted above, be liable to You for any direct, indirect, *
* special, incidental, or consequential damages of any character *
* including, without limitation, damages for lost profits, loss of *
* goodwill, work stoppage, computer failure or malfunction, or any *
* and all other commercial damages or losses, even if such party *
* shall have been informed of the possibility of such damages. This *
* limitation of liability shall not apply to liability for death or *
* personal injury resulting from such party's negligence to the *
* extent applicable law prohibits such limitation. Some *
* jurisdictions do not allow the exclusion or limitation of *
* incidental or consequential damages, so this exclusion and *
* limitation may not apply to You. *
* *
************************************************************************
8. Litigation
-------------
Any litigation relating to this License may be brought only in the
courts of a jurisdiction where the defendant maintains its principal
place of business and such litigation shall be governed by laws of that
jurisdiction, without reference to its conflict-of-law provisions.
Nothing in this Section shall prevent a party's ability to bring
cross-claims or counter-claims.
9. Miscellaneous
----------------
This License represents the complete agreement concerning the subject
matter hereof. If any provision of this License is held to be
unenforceable, such provision shall be reformed only to the extent
necessary to make it enforceable. Any law or regulation which provides
that the language of a contract shall be construed against the drafter
shall not be used to construe this License against a Contributor.
10. Versions of the License
---------------------------
10.1. New Versions
Mozilla Foundation is the license steward. Except as provided in Section
10.3, no one other than the license steward has the right to modify or
publish new versions of this License. Each version will be given a
distinguishing version number.
10.2. Effect of New Versions
You may distribute the Covered Software under the terms of the version
of the License under which You originally received the Covered Software,
or under the terms of any subsequent version published by the license
steward.
10.3. Modified Versions
If you create software not governed by this License, and you want to
create a new license for such software, you may create and use a
modified version of this License if you rename the license and remove
any references to the name of the license steward (except to note that
such modified license differs from this License).
10.4. Distributing Source Code Form that is Incompatible With Secondary
Licenses
If You choose to distribute Source Code Form that is Incompatible With
Secondary Licenses under the terms of this version of the License, the
notice described in Exhibit B of this License must be attached.
Exhibit A - Source Code Form License Notice
-------------------------------------------
This Source Code Form is subject to the terms of the Mozilla Public
License, v. 2.0. If a copy of the MPL was not distributed with this
file, You can obtain one at http://mozilla.org/MPL/2.0/.
If it is not possible or desirable to put the notice in a particular
file, then You may include the notice in a location (such as a LICENSE
file in a relevant directory) where a recipient would be likely to look
for such a notice.
You may add additional accurate notices of copyright ownership.
Exhibit B - "Incompatible With Secondary Licenses" Notice
---------------------------------------------------------
This Source Code Form is "Incompatible With Secondary Licenses", as
defined by the Mozilla Public License, v. 2.0.
================================================
FILE: README.md
================================================
> [!IMPORTANT]
>
> ## ⚠️ Deprecation Announcement for Mozilla HTTP Observatory
>
> Dear Mozilla Observatory Users,
>
> This code repository is now deprecated. There is a [Node/Javascript based replacement available](https://github.com/mdn/mdn-http-observatory/), that has updated scoring and backs the [HTTP Observatory service on MDN](https://developer.mozilla.org/en-US/observatory).
>
> ### 🛠️ What This Means
>
> * No Further Updates: We will no longer be providing updates, bug fixes, or new features for this repository.
> * Limited Support: Official support will be discontinued.
> * Archival: The repository will be archived soon, making it read-only.
>
> 🔍 Alternatives and Recommendations
>
> We recommend transitioning to [HTTP Observatory](https://github.com/mdn/mdn-http-observatory/), maintained by [MDN](https://developer.mozilla.org).
>
> 📦 Migration Guide
>
> To assist you in transitioning, we have prepared a [Migration Guide](https://github.com/mdn/mdn-http-observatory/blob/main/README.md#migrating-from-the-public-v1-api-to-the-v2-api) that covers steps to migrate your existing setup to the alternative.
# Observatory by Mozilla CLI Client
The Mozilla HTTP Observatory is a set of tools to analyze your website and inform you if you are utilizing the many available methods to secure it.
It is split into three projects:
* [http-observatory](https://github.com/mozilla/http-observatory) - scanner/grader
* [observatory-cli](https://github.com/mozilla/observatory-cli) - command line interface
* [http-observatory-website](https://github.com/mozilla/http-observatory-website) - web interface
## Score your site's HTTPS practices
Observatory by Mozilla is a project designed to help developers, system administrators, and security professionals configure their sites safely and securely.
## Observatory in action!
-
- [FAQ](https://observatory.mozilla.org/faq.html)
### Example site report, with additional options

The [full report url](https://observatory.mozilla.org/analyze.html?host=ssllabs.com) has suggestions to **repair** each of these issues.
## Install
```
$ npm install -g observatory-cli
```
(Optional `Docker` instructions below.)
## Usage
1. **Scan a site** for `https` best practices.
```
# json!
$ observatory some.site.name
# include 'zero' scores, display as a tabular report
$ observatory some.site.name --zero --format=report
# attempt to force a re-scan
$ observatory some.site.name --rescan
```
2. **Test a site** as part of a Continuous Integration pipeline.
Script will FAIL unless the grade is AT LEAST `B+`
```
$ observatory some.site.name --min-grade B+
```
...and the score is at least 50.
```
$ observatory some.site.name --min-grade B+ --min-score 50
```
3. **Print the URL** for the expanded online report.
```
$ observatory some.site.name --format=url
```
4. **nagios** monitoring plugin mode.
For `--nagios `, `failcode` will be the exit code if the test fails.
`--min-score`, `--min-grade`, `--zero`, `--skip` affect the test.
```
$ observatory --nagios 2 --min-score 85 -z --skip cookies
CRITICAL ["content-security-policy",...,"x-xss-protection"]
```
Any **negative scores fail the test**, unless `--min-score` or `--min-grade` is specified.
```
# '2' maps to nagios 'critical.' Exits '2'
$ observatory ssllabs.com --nagios 2
CRITICAL ["redirection"]
```
We can `--skip` the failing rule, and affect the score.
```
$ observatory ssllabs.com --nagios 2 --skip redirection
observatory [INFO] modfiying score, because of --skip. was: 100, now: 105
OK
```
Quiet output with `-q`.
```
$ observatory ssllabs.com --nagios 2 --skip redirection -q
OK
```
## Help Ouput
```
$ observatory --help
Usage: observatory [options]
cli for interacting with Mozilla HTTP Observatory
https://observatory.mozilla.org/
Options:
-h, --help output usage information
-V, --version output the version number
--format [format] format for output. choice: (json|report|csv|url). `json` is default
--min-grade testing: this grade or better, or exit(1)
--min-score testing: this score or better, or exit(1)
--nagios [failcode] nagios mode, exits with [failcode] on failure
--rescan initiate a rescan instead of showing recent scan results
-z, --zero show test results that don't affect the final score
--attempts number of attempts to try before failing
--api-version [version] api version: defaults to 1
--skip skip rules by name. works with min-score only
--tls do tls checks instead
-q, --quiet turns off all logging
Output Formats (--format)
- json json of the report
- report plain-text tabular format
- csv alias for report
- url url for online version
Nagios Mode (--nagios)
- if `--min-score` and/or `--min-grade`, use those.
- else *any* negative rules fail the check.
- exits with integer `failcode`.
```
## Example Report, Text Version
Report, with options:
* `-z` to show '0' rules (all rules)
* `--skip` to skip a rule (affects SCORE, but not GRADE)
```
$ observatory some.site --format=report -z --skip redirection
observatory [INFO] modfiying score, because of --skip. was: 60, now: 65
HTTP Observatory Report: some.site
Score Description
-20 content-security-policy Content Security Policy (CSP) implemented, but allows 'unsafe-inline' inside script-src
-10 x-xss-protection X-XSS-Protection header not implemented
-5 x-content-type-options X-Content-Type-Options header not implemented
0 contribute Contribute.json implemented with the required contact information
0 cookies No cookies detected
0 cross-origin-resource-sharing Content is not visible via cross-origin resource sharing (CORS) files or headers
0 public-key-pinning HTTP Public Key Pinning (HPKP) header not implemented
0 strict-transport-security HTTP Strict Transport Security (HSTS) header set to a minimum of six months (15768000)
0 subresource-integrity Subresource Integrity (SRI) not implemented, but all scripts are loaded from a similar origin
0 x-frame-options X-Frame-Options (XFO) header set to SAMEORIGIN or DENY
Score: 65 (modified due to --skip)
Grade: C+
Full Report Url: https://observatory.mozilla.org/analyze/some.site
```
## Technical / Development
### Debug observatory api urls
```
NODE_DEBUG=request observatory --format report --rescan --zero www.mozilla.org
```
### API Documentation
https://github.com/mozilla/http-observatory/blob/master/httpobs/docs/api.md
### Dockerized `observatory-cli`
Use the provided [Dockerfile](./Dockerfile), to build and execute `observatory` in Docker container. Useful for Continuous Integration/Continuous Deployment (CI/CD) pipelines capable of running containers but that otherwise don't need a lot of extra software.
**To get started,**
1. Build the container. Tag it as `mozilla/observatory-cli`
```
docker build -t mozilla/observatory-cli .
```
2. Add a section like this to your `profile` (varies depending on your operating system and shell. `bash` shown).
```
## $HOME/.bashrc
if [[ -d $HOME/.bash_functions ]]; then
for file in $HOME/.bash_functions/*; do
. $file
done
fi
```
3. Create the directory referenced in point 2 and copy the files in `shell_functions` (not `bash_completion`) into that directory:
```
$ mkdir $HOME/.bash_functions
$ find shell_functions -maxdepth 1 -type f -executable | while read file; do cp $file $HOME/.bash_functions; done
```
4. *Optional*: Add Bash completion to your shell. (varies depending on your host operating system)
```
## On Red Hat based distributions:
sudo cp shell_functions/bash_completion/observatory.bash /etc/bash_completion.d/
```
5. Start a new shell and execute `observatory`. Now it's in a Docker container. Bash completion is available if you've added it.

## Related projects
- [HTTP Observatory](https://github.com/mozilla/http-observatory) by April King
- [Python observatory-cli](https://github.com/mozilla/http-observatory-cli) by April King
================================================
FILE: index.js
================================================
#!/usr/bin/env node
"use strict";
// https://github.com/mozilla/http-observatory-cli/blob/master/httpobscli/cli.py
// we are doing a lot of things in a sillier way
var chalk = require("chalk");
var program = require("commander");
var rp = require("request-promise");
var delay = require("timeout-as-promise");
var sprintf = require("sprintf-js").sprintf;
var util = require("util");
var url = require("url");
var SITE_URL = "https://observatory.mozilla.org/";
var API_URL = process.env.HTTPOBS_API_URL || "https://http-observatory.security.mozilla.org/api/v1/";
if (!API_URL.endsWith("/")) { API_URL += "/" ;}
/* utilities and ephemera */
var clim = require("clim");
var QUIET = false;
var hasSite = false;
function padright(s, len) {
if (s.length >= len) {
return s;
}
return s + Array(len).fill(" ").join("").slice(s.length);
}
clim.logWrite = function(level, prefixes, msg) {
if (QUIET) {
return;
}
var pfx = "";
if (prefixes.length > 0) {
pfx = prefixes.join(" ");
}
level = (f[level.toLowerCase()] || function(p) {
return p;
})(level);
var line = util.format("%s [%s] %s", pfx, level, msg);
switch (level) {
case "ERROR":
process.stderr.write(line + "\n");
break;
default:
process.stdout.write(line + "\n");
}
};
var logger = clim(chalk.grey("observatory"));
var f = {
error: chalk.red,
link: chalk.underline.blue,
info: chalk.blue,
log: chalk.blue,
warn: chalk.red,
bold: chalk.bold,
code: chalk.bold.grey,
header: chalk.bold.blue,
plain: chalk.stripColor
};
function collect(val, O) {
O[val] = true;
return O;
}
function helpAnywhere(rawArgs) {
return rawArgs.filter(function(x) {
return /^(-h|--help)$/.exec(x);
}).length;
}
var FORMATS = {
"json": {
"description": "json of the report",
"action": function(scores) {
console.log(JSON.stringify(scores, null, 2));
}
},
"report": {
"description": "plain-text tabular format",
"action": formatAnswersCsv
},
"csv": {
"description": util.format("alias for %s", f.code("report")),
"action": formatAnswersCsv
},
"url": {
"description": "url for online version",
// this one we handle early, so it has a different api
"action": function() {}
}
};
function validateFormatChoice(given) {
given = given.toLowerCase();
if (given in FORMATS) {
return given;
} else {
logger.error("not a valid format choice: %s. Allowed: %s",
f.error(given),
f.code(Object.keys(FORMATS).join("|")));
process.exit(1);
}
}
function longestInList(L) {
return Math.max.apply(null, L.map(function(x) {
return x.length;
}));
}
/* functions for retrieving reports */
class Scanner {
constructor (site, options) {
this.attempts = 0;
this.allowed = options.attempts || 10;
this.url = url.resolve(API_URL, "analyze");
}
promiseScan (site, options, method="post") {
var that = this;
this.attempts += 1;
site = site || this.site;
options = options || this.options;
if (this.attempts >= this.allowed) {
throw new Error(sprintf("too many attempts %s", this.attempts));
}
var qargs = {host: site};
["rescan", "zero"].forEach(function(k) {
if (options[k]) {
qargs[k] = "true";
}
});
// ininitalize with POST
return rp({
url: this.url,
json: true,
simple: true,
qs: {host: site},
formData: qargs,
method: method,
timeout: 1000
}).then(
function(scan) {
if (options.rescan && (scan.error === "rescan-attempt-too-soon")) {
logger.warn("Rescan attempt is sooner than the allowed cooldown period. Returning cached results instead.");
options.rescan = false;
return that.promiseScan(site, options, "get");
} else {
if (scan.error) {
throw new Error(util.format("Unable to get result. Host:%s Error:%s.", site, scan.error));
}
}
switch (scan.state) {
case "FINISHED": {
return scan;
}
case "ABORTED":
case "FAILED": {
throw new Error(util.format("Unable to get result from the HTTP Observatory. Host: %s Error: %s.", site, scan.state));
}
}
// try again
logger.warn(sprintf("retrying in 1 second (attempt %s/%s)", that.attempts, that.allowed));
return delay(1000).then(function() {
return that.promiseScan(site, options, "get");
});
}
);
}
}
/** related to grades */
var grades = ["F"];
"DCBA".split("").forEach(function(g) {
["-", "", "+"].forEach(function(mark) {
grades.push(g + mark);
});
});
function gradeCompare(seen, wanted) {
return grades.indexOf(wanted) <= grades.indexOf(seen);
}
function validateGrade(val) {
val = val.toUpperCase();
if (grades.indexOf(val) >= 0) {
return val;
} else {
throw new Error("invalid grade: " + val);
}
}
function openSite(url) {
logger.log(f.link(url));
}
function filterNegativeScores(scores) {
function isNegative(k) {
return scores[k].score_modifier < 0;
}
return Object.keys(scores).filter(isNegative);
}
function promiseReport(scan, options) {
var url = API_URL + "getScanResults?scan=" + scan.scan_id;
return rp({
url: url,
json: true,
simple: true
}).then(function(reportData) {
return formatAnswer(reportData, url, scan, options);
});
}
function formatAnswersCsv(scores, url, scan, options) {
// print("[{modifier:>4}] {reason}".format(modifier=score[0], reason=score[1].replace(""","\\"")))
function sortByScore(a, b) {
return a.score_modifier - b.score_modifier;
}
var longest = longestInList(Object.keys(scores));
var scoresList = [];
for (var k in scores) {
scoresList.push(scores[k]);
}
// sort and invert to positive
scoresList.sort(sortByScore);
console.log("\n%s: %s", f.header("HTTP Observatory Report"), options.site);
console.log("\n%s %s %s", f.header("Score"), f.header(padright("Rule",longest)), f.header("Description"));
scoresList.map(function(score) {
var points = score.score_modifier;
var fmt = f.plain;
if (points > 0) { fmt = f.info; }
if (points < 0) { fmt = f.error; }
var firstSentence = score.score_description.split(". ")[0];
console.log(sprintf("%5f %s %s.", score.score_modifier, fmt(padright(score.name, longest)), firstSentence));
});
var fullReportUrl = "https://observatory.mozilla.org/analyze/" + options.site;
if (Object.keys(options.skip).length) {
console.log("\nScore: %s (modified due to --skip)", scan.score);
} else {
console.log("\nScore: %s", scan.score);
}
console.log("Grade: %s", scan.grade);
console.log(sprintf("\n%s: %s\n", f.header("Full Report Url"), f.link(fullReportUrl)));
}
function handleNagiosMode(options, scan, scores) {
// https://github.com/mozilla/http-observatory-cli/issues/6
var nagiosExitCodes = {
1: "WARNING",
2: "CRITICAL",
3: "UNKNOWN"
};
if (!(options.nagios in nagiosExitCodes)) {
throw new Error("nagios exit code must be in %s", Object.keys(nagiosExitCodes).join("|"));
}
var codeName = nagiosExitCodes[options.nagios];
var negatives = filterNegativeScores(scores);
function OK() {
console.log("OK");
process.exit(0);
}
function FAIL() {
console.log("%s %j", codeName, negatives);
process.exit(codeName);
}
if (options.minGrade || (options.minScore !== undefined)) {
try {
handleExpectedScore(options, scan);
OK();
} catch (err) {
FAIL();
}
return;
} else {
if (negatives.length) {
FAIL();
} else {
OK();
}
}
}
function handleExpectedScore(options, scan) {
// side cases
var mingrade = options.minGrade;
var minscore = options.minScore;
if (mingrade) {
if (!gradeCompare(scan.grade, mingrade)) {
throw new Error(sprintf("bad grade. wanted %s, got %s", mingrade, scan.grade));
}
}
if (minscore !== undefined) {
if (scan.score < minscore) {
throw new Error(sprintf("bad score. wanted %s, got %s", minscore, scan.score));
}
}
return;
}
function formatAnswer(reportData, url, scan, options) {
/** Reporting: */
var scores = {};
/* filter out --zeros, and --skip or not */
for (var k in reportData) {
var v = reportData[k];
// --zero
if (v.score_modifier !== 0 || options.zero) {
// --skip
if (k in options.skip) { continue; }
// actually copy
scores[k] = v;
}
}
// rescore
var newScore = 100;
for (k in scores) {
newScore += scores[k].score_modifier;
}
if (Object.keys(options.skip).length) {
logger.info("modfiying score, because of --skip. was: %s, now: %s", f.info(scan.score), f.info(newScore));
scan.score = newScore;
}
if (options.nagios !== undefined) {
// nagios has
try {
handleNagiosMode(options, scan, scores);
} catch (err) {
logger.error(err);
process.exit(1);
}
}
if (options.minGrade || (options.minScore !== undefined)) {
try {
handleExpectedScore(options, scan);
} catch (err) {
logger.error(err);
process.exit(1);
}
return;
}
FORMATS[options.format || "json"].action(scores, url, scan, options);
}
var passedOn = [];
function preprocess(args) {
var dashed = false;
var out = [];
args.forEach(function(a) {
if (a === "--") {
dashed = true;
return;
}
if (dashed) {
passedOn.push(a);
} else {
out.push(a);
}
});
return out;
}
class Observatory {
handleNoSite (options) {
if (options.tls) {
logger.info("--tls is not yet implemented.");
logger.info("website: ", f.link("https://observatory.mozilla.org/"));
logger.info("go client: ", f.link("https://github.com/mozilla/tls-observatory"));
logger.info("comment: %s", f.link("https://github.com/mozilla/observatory-cli/issues/5"));
return;
}
// require site for everything else
logger.error(f.error("no given"));
return program.help();
}
}
let O = new Observatory();
program
.version(require("./package.json").version)
.description(util.format("cli for interacting with Mozilla HTTP Observatory \n\n %s", f.link(SITE_URL)));
program
//.command("check ")
.arguments("")
.option("--format [format]", util.format("format for output. choice: (%s). `json` is default",
f.code(Object.keys(FORMATS).join("|"))),
validateFormatChoice)
.option("--min-grade ", "testing: this grade or better, or exit(1)", validateGrade)
.option("--min-score ", "testing: this score or better, or exit(1)", Number)
.option("--nagios [failcode]", "nagios mode, exits with [failcode] on failure", Number)
.option("--rescan", "initiate a rescan instead of showing recent scan results")
.option("-z, --zero", "show test results that don't affect the final score")
.option("--attempts ", "number of attempts to try before failing", Number)
.option("--api-version [version]", "api version: defaults to 1", Number)
.option("--skip ", "skip rules by name. works with min-score only", collect, {})
.option("--tls", "do tls checks instead")
.option("-q, --quiet", "turns off all logging", function() {QUIET = true;})
.action(function mainAction(site, options) {
// everything here has a site
hasSite = true;
if (helpAnywhere(options.rawArgs)) {
program.help();
}
options.site = site; // stuff it in.
if (options.tls) {
return O.handleNoSite(options);
}
if (options.format === "url") {
return openSite(util.format("https://observatory.mozilla.org/analyze.html?host=%s", site));
}
var api = options.apiVersion;
if (api && api !== 1) {
logger.error(sprintf("V1 is only API supported, not %s", api));
process.exit(1);
}
var scanner = new Scanner(site, options);
scanner.promiseScan(site, options)
.then(function(reportId) {
return promiseReport(reportId, options);
})
.catch(function(err) {
logger.error(err.message);
process.exit(1);
});
});
function newHelp() {
var longest = longestInList(Object.keys(FORMATS));
var out =
f.header("\n Output Formats ") + f.code("(--format)") + "\n" +
Object.keys(FORMATS).map(
function(k) {
return util.format(" - %s %s\n",
f.info(padright(k, longest)),
FORMATS[k].description
);
}).join("") +
"\n\n" +
f.header(" Nagios Mode") + " " + f.code("(--nagios)") +
"\n" +
" - if `--min-score` and/or `--min-grade`, use those.\n" +
" - else *any* negative rules fail the check.\n" +
" - exits with integer `failcode`.\n";
return out;
}
program.on("--help", function() {
console.log(newHelp());
});
program.parse(preprocess(process.argv));
if (!hasSite) {
O.handleNoSite(program);
}
================================================
FILE: package.json
================================================
{
"name": "observatory-cli",
"description": "Command line client for Mozilla HTTP observatory service",
"version": "0.7.1",
"author": "Gregg Lind ",
"bin": {
"observatory": "./index.js"
},
"bugs": {
"url": "https://github.com/mozilla/observatory-cli/issues"
},
"dependencies": {
"chalk": "^1.1.3",
"clim": "^1.1.1",
"commander": "^2.9.0",
"request": "^2.74.0",
"request-promise": "^4.1.1",
"sprintf-js": "^1.0.3",
"timeout-as-promise": "^1.0.0"
},
"devDependencies": {
"depcheck": "^0.6.4",
"eslint": "^3.5.0",
"eslint-plugin-node": "^2.1.2",
"eslint-plugin-promise": "^3.0.0",
"fixpack": "^2.3.1",
"npm-run-all": "^3.1.0",
"nsp": "^2.6.1"
},
"engines": {
"node": ">=6"
},
"homepage": "https://github.com/mozilla/observatory-cli#readme",
"keywords": [
"https",
"mozilla",
"security"
],
"license": "MPL-2.0",
"main": "index.js",
"repository": {
"type": "git",
"url": "git+https://github.com/mozilla/observatory-cli.git"
},
"scripts": {
"lint": "npm-run-all lint:*",
"lint:depcheck": "depcheck --ignores=nsp,eslint-*",
"lint:eslint": "eslint .",
"lint:fixpack": "fixpack",
"lint:nsp": "nsp check -o summary",
"prepublish": "npm shrinkwrap",
"pretest": "npm run lint",
"test": "echo OK"
}
}
================================================
FILE: shell_functions/bash_completion/observatory.bash
================================================
# bash completion for observatory-cli
# Author: Jeremy Young
# Asurion 10/10/2016
_observatory_completion () {
local CUR=${COMP_WORDS[COMP_CWORD]}
local PREV=${COMP_WORDS[COMP_CWORD-1]}
local OPTIONS_ALL="-h -V -z -q --help --version --format --min-grade --min-score --nagios \
--rescan --zero --attempts --api-version --skip --tls --quiet"
local OPTIONS_BLANK=""
local OPTIONS_FORMAT="json report csv url"
local OPTIONS_GRADE="F D- D D+ C- C C+ B- B B+ A- A A+"
case $PREV in
-h|--help)
COMPREPLY=( $( compgen -W "${OPTIONS_BLANK}" -- "${CUR}" ) )
return 0
;;
-V|--version)
COMPREPLY=( $( compgen -W "${OPTIONS_BLANK}" -- "${CUR}" ) )
return 0
;;
--format)
COMPREPLY=( $( compgen -W "${OPTIONS_FORMAT}" -- "${CUR}" ) )
return 0
;;
--min-grade)
COMPREPLY=( $( compgen -W "${OPTIONS_GRADE}" -- "${CUR}" ) )
;;
--min-score)
COMPREPLY=( $( compgen -W "$( seq 1 100 )" -- "${CUR}" ) )
;;
--nagios)
## https://github.com/mozilla/observatory-cli/blob/master/index.js#L262
COMPREPLY=( $( compgen -W "$( seq 1 3 )" -- "${CUR}" ) )
;;
--rescan)
COMPREPLY=( $( compgen -W "${OPTIONS_BLANK}" -- "${CUR}" ) )
;;
-z|--zero)
COMPREPLY=( $( compgen -W "${OPTIONS_BLANK}" -- "${CUR}" ) )
;;
--attempts)
## 100 seems like a nice place to stop to determine if there was a failure connecting.
COMPREPLY=( $( compgen -W "$( seq 1 100 )" -- "${CUR}" ) )
;;
--api-version)
## Picking some ending value arbitrarily. 5 API versions is probably a lot.
COMPREPLY=( $( compgen -W "$( seq 1 5 )" -- "${CUR}" ) )
;;
--skip)
COMPREPLY=( $( compgen -W "${OPTIONS_SKIP}" -- "${CUR}" ) )
;;
--tls)
COMPREPLY=( $( compgen -W "${OPTIONS_BLANK}" -- "${CUR}" ) )
;;
-q|--quiet)
COMPREPLY=( $( compgen -W "${OPTIONS_BLANK}" -- "${CUR}" ) )
;;
*)
if [[ "${CUR}" == * ]]; then
COMPREPLY=( $( compgen -W "${OPTIONS_ALL}" -- "${CUR}" ) )
fi
return 0
;;
esac
}
complete -F _observatory_completion observatory
================================================
FILE: shell_functions/docker_perms.sh
================================================
_check_docker_sock_perms () {
local DOCKER_SOCKET=/var/run/docker.sock
case "$( uname )" in
Linux)
if [[ ! -w "${DOCKER_SOCKET}" ]]; then
sudo setfacl -m u:$( whoami ):rw "${DOCKER_SOCKET}"
fi
;;
Darwin)
if [[ ! -w "${DOCKER_SOCKET}" ]]; then
sudo chmod a+w "${DOCKER_SOCKET}"
fi
;;
*)
;;
esac
}
_check_docker_image_installed () {
local DOCKER_IMAGE="${1}";
local DOCKER_REPO="$( echo ${DOCKER_IMAGE} | cut -d : -f 1 )";
local DOCKER_TAG="$( echo ${DOCKER_IMAGE} | cut -d : -f 2 )";
if [[ -n "${DOCKER_TAG}" ]]; then
if [[ "$( docker images | grep -i "${DOCKER_TAG}" | grep -i "${DOCKER_REPO}" &>/dev/null; echo $? )" != "0" ]]; then
printf "Pulling "${DOCKER_IMAGE}" for use...\n";
docker pull "${DOCKER_IMAGE}" &> /dev/null;
fi;
else
if [[ "$( docker images | grep -i "${DOCKER_REPO}" &>/dev/null; echo $? )" != "0" ]]; then
printf "Pulling "${DOCKER_IMAGE}" for use...\n";
docker pull "${DOCKER_IMAGE}" &> /dev/null;
fi;
fi
}
================================================
FILE: shell_functions/observatory.sh
================================================
observatory () {
local DOCKER_IMAGE="mozilla/observatory-cli"
local OBSERVATORY_NETWORK="$( docker network ls | grep observatory | awk '{print $2}' )"
local OBSERVATORY_API="$( docker ps | grep website | awk '{print $NF}' )"
local COMMAND="docker run --rm -it --name observatory-cli --net=$OBSERVATORY_NETWORK -e HTTPOBS_API_URL=http://$OBSERVATORY_API:57001/api/v1/ --link $OBSERVATORY_API"
local NOBACKEND_COMMAND="docker run --rm -it --name observatory-cli"
local ARGS="${@}"
## Allow entering the container to test by hand
case "${1}" in
debug)
COMMAND="${COMMAND} --entrypoint=/bin/ash --user=root"
unset ARGS
;;
esac
_check_docker_sock_perms
_check_docker_image_installed "${DOCKER_IMAGE}"
## Check to see if we're running HTTP Observatory in containers. If not, use default public instance.
if [[ -z "$( docker ps | grep website | awk '{print $NF}' )" ]]; then
COMMAND="${NOBACKEND_COMMAND}"
fi
${COMMAND} ${DOCKER_IMAGE} ${ARGS}
}