├── test
├── test_helper.exs
├── ex_pwned_test.exs
└── ex_pwned
│ └── passwords_test.exs
├── .formatter.exs
├── lib
├── ex_pwned
│ ├── utils.ex
│ ├── pastes.ex
│ ├── api.ex
│ ├── passwords.ex
│ ├── parser.ex
│ └── breaches.ex
└── ex_pwned.ex
├── .gitignore
├── mix.exs
├── config
└── config.exs
├── mix.lock
├── README.md
└── LICENSE
/test/test_helper.exs:
--------------------------------------------------------------------------------
1 | ExUnit.start()
2 |
--------------------------------------------------------------------------------
/.formatter.exs:
--------------------------------------------------------------------------------
1 | # Used by "mix format"
2 | [
3 | inputs: ["mix.exs", "{config,lib,test}/**/*.{ex,exs}"]
4 | ]
5 |
--------------------------------------------------------------------------------
/lib/ex_pwned/utils.ex:
--------------------------------------------------------------------------------
1 | defmodule ExPwned.Utils do
2 | @moduledoc """
3 | Collection of helper functions for ExPwned
4 | """
5 |
6 | def ua,
7 | do: {"User-Agent", Application.get_env(:ex_pwned, :user_agent) || "ExPwned Elixir Client"}
8 |
9 | def api_version, do: {"api-version", 2}
10 | def headers, do: [ua(), api_version()]
11 | def base_url, do: "https://haveibeenpwned.com/api"
12 | def json_library, do: Application.get_env(:ex_pwned, :json_library) || Jason
13 | end
14 |
--------------------------------------------------------------------------------
/.gitignore:
--------------------------------------------------------------------------------
1 | # The directory Mix will write compiled artifacts to.
2 | /_build
3 |
4 | # If you run "mix test --cover", coverage assets end up here.
5 | /cover
6 |
7 | # The directory Mix downloads your dependencies sources to.
8 | /deps
9 |
10 | # Where 3rd-party dependencies like ExDoc output generated docs.
11 | /doc
12 |
13 | # If the VM crashes, it generates a dump, let's ignore it too.
14 | erl_crash.dump
15 |
16 | # Also ignore archive artifacts (built via "mix archive.build").
17 | *.ez
18 |
19 | .tool-versions
20 |
--------------------------------------------------------------------------------
/lib/ex_pwned/pastes.ex:
--------------------------------------------------------------------------------
1 | defmodule ExPwned.Pastes do
2 | @moduledoc """
3 | Module to interact with hibp API to retrive breaches data
4 | """
5 |
6 | use ExPwned.Api
7 |
8 | @doc """
9 | The API takes a single parameter which is the email address to be searched for.
10 | Unlike searching for breaches, usernames that are not email addresses cannot be searched for.
11 | The email is not case sensitive and will be trimmed of leading or trailing white spaces.
12 | The email should always be URL encoded.
13 |
14 | ## Examples
15 |
16 | iex> ExPwned.Pastes.pasteaccount("abc@example.com")
17 | """
18 | def pasteaccount(account), do: do_get("pasteaccount/#{account}")
19 | end
20 |
--------------------------------------------------------------------------------
/lib/ex_pwned/api.ex:
--------------------------------------------------------------------------------
1 | defmodule ExPwned.Api do
2 | @moduledoc """
3 | Base definition for Api client
4 | """
5 |
6 | defmacro __using__(_opts) do
7 | quote do
8 | alias ExPwned.Parser
9 | import ExPwned.Utils
10 |
11 | def build_url(path_arg, query_params \\ %{}) do
12 | "#{base_url()}/#{path_arg}?#{URI.encode_query(query_params)}"
13 | end
14 |
15 | def do_get(path_arg), do: do_get(path_arg, %{})
16 |
17 | def do_get(path_arg, query_params) when is_list(query_params),
18 | do: do_get(path_arg, Enum.into(query_params, %{}))
19 |
20 | def do_get(path_arg, query_params) do
21 | path_arg
22 | |> build_url(query_params)
23 | |> HTTPoison.get(headers())
24 | |> Parser.parse()
25 | end
26 | end
27 | end
28 | end
29 |
--------------------------------------------------------------------------------
/test/ex_pwned_test.exs:
--------------------------------------------------------------------------------
1 | defmodule ExPwnedTest do
2 | use ExUnit.Case
3 |
4 | describe "password_breached?/1" do
5 | test "Known breached password" do
6 | assert true == ExPwned.password_breached?("123456")
7 | end
8 |
9 | test "Probably good password" do
10 | assert false == ExPwned.password_breached?(UUID.uuid1())
11 | end
12 | end
13 |
14 | describe "password_breach_count?/1" do
15 | test "Known breached password" do
16 | result = ExPwned.password_breach_count("123456")
17 | assert result > 0
18 | end
19 |
20 | test "Probably good password" do
21 | result = ExPwned.password_breach_count(UUID.uuid1())
22 | assert result == 0
23 | end
24 | end
25 |
26 | describe "breached?/1" do
27 | test "Known breached account" do
28 | assert true == ExPwned.breached?("test@example.com")
29 | end
30 |
31 | test "Probably good account" do
32 | assert false == ExPwned.breached?("#{UUID.uuid1()}@example.com")
33 | end
34 | end
35 | end
36 |
--------------------------------------------------------------------------------
/mix.exs:
--------------------------------------------------------------------------------
1 | defmodule ExPwned.Mixfile do
2 | use Mix.Project
3 |
4 | def project do
5 | [
6 | app: :ex_pwned,
7 | version: "0.2.0",
8 | elixir: "~> 1.3",
9 | description: "Elixir client for haveibeenpwned.com",
10 | source_url: "https://github.com/techgaun/ex_pwned",
11 | package: package(),
12 | build_embedded: Mix.env() == :prod,
13 | start_permanent: Mix.env() == :prod,
14 | docs: [extras: ["README.md"]],
15 | deps: deps()
16 | ]
17 | end
18 |
19 | def application do
20 | [applications: [:logger, :httpoison]]
21 | end
22 |
23 | defp deps do
24 | [
25 | {:httpoison, ">= 0.9.0"},
26 | {:jason, "~> 1.2", optional: true},
27 | {:ex_doc, "~> 0.19", only: :dev},
28 | {:uuid, "~> 1.1", only: :test},
29 | {:credo, "~> 0.10.2", only: [:dev, :test], runtime: false}
30 | ]
31 | end
32 |
33 | defp package do
34 | [
35 | maintainers: [
36 | "Samar Acharya"
37 | ],
38 | licenses: ["Apache-2.0"],
39 | links: %{"GitHub" => "https://github.com/techgaun/ex_pwned"}
40 | ]
41 | end
42 | end
43 |
--------------------------------------------------------------------------------
/config/config.exs:
--------------------------------------------------------------------------------
1 | # This file is responsible for configuring your application
2 | # and its dependencies with the aid of the Mix.Config module.
3 | use Mix.Config
4 |
5 | # This configuration is loaded before any dependency and is restricted
6 | # to this project. If another project depends on this project, this
7 | # file won't be loaded nor affect the parent project. For this reason,
8 | # if you want to provide default values for your application for
9 | # 3rd-party users, it should be done in your "mix.exs" file.
10 |
11 | # You can configure for your application as:
12 | #
13 | # config :ex_pwned, key: :value
14 | #
15 | # And access this configuration in your application as:
16 | #
17 | # Application.get_env(:ex_pwned, :key)
18 | #
19 | # Or configure a 3rd-party app:
20 | #
21 | # config :logger, level: :info
22 | #
23 |
24 | # It is also possible to import configuration files, relative to this
25 | # directory. For example, you can emulate configuration per environment
26 | # by uncommenting the line below and defining dev.exs, test.exs and such.
27 | # Configuration from the imported file will override the ones defined
28 | # here (which is why it is important to import them last).
29 | #
30 | # import_config "#{Mix.env}.exs"
31 |
--------------------------------------------------------------------------------
/test/ex_pwned/passwords_test.exs:
--------------------------------------------------------------------------------
1 | defmodule ExPwned.PasswordsTest do
2 | use ExUnit.Case
3 | alias ExPwned.Passwords
4 |
5 | test "Check known breached password" do
6 | assert Passwords.breached?("123456")
7 | end
8 |
9 | test "handle_success/2 with breached passwords" do
10 | body = "00387259BECFC8B3CB0D27EBDDC2AC93758:1\r\n00BA633D4B050924FA8228526CE0F561B38:3"
11 | assert 1 === Passwords.handle_success(body, "00387259BECFC8B3CB0D27EBDDC2AC93758")
12 | assert 3 === Passwords.handle_success(body, "00BA633D4B050924FA8228526CE0F561B38")
13 | end
14 |
15 | test "handle_success/2 with hash not found" do
16 | body = "00387259BECFC8B3CB0D27EBDDC2AC93758:1\r\n00BA633D4B050924FA8228526CE0F561B38:3"
17 | assert 0 === Passwords.handle_success(body, "NOTFOUND")
18 | end
19 |
20 | test "handle_success/2 with only one response" do
21 | body = "00387259BECFC8B3CB0D27EBDDC2AC93758:1"
22 | assert 1 === Passwords.handle_success(body, "00387259BECFC8B3CB0D27EBDDC2AC93758")
23 | end
24 |
25 | test "parse_body/1" do
26 | body = "00387259BECFC8B3CB0D27EBDDC2AC93758:1\r\n00BA633D4B050924FA8228526CE0F561B38:3"
27 |
28 | result = Passwords.parse_body(body)
29 | assert is_list(result)
30 | assert ["00387259BECFC8B3CB0D27EBDDC2AC93758", "1"] in result
31 | assert ["00BA633D4B050924FA8228526CE0F561B38", "3"] in result
32 | end
33 | end
34 |
--------------------------------------------------------------------------------
/lib/ex_pwned.ex:
--------------------------------------------------------------------------------
1 | defmodule ExPwned do
2 | @moduledoc """
3 | ExPwned is a client library for Elixir to interact with [haveibeenpwned.com](https://haveibeenpwned.com/API/v2).
4 | """
5 | alias ExPwned.Breaches
6 | alias ExPwned.Passwords
7 |
8 | @doc """
9 | A convenience to check if an account has been breached or not.
10 |
11 | ## Example
12 |
13 | iex> ExPwned.breached?("abc@example.com")
14 | true
15 | iex> ExPwned.breached?("abcde@example.com")
16 | false
17 | """
18 | def breached?(account) do
19 | case Breaches.breachedaccount(account, truncateResponse: true) do
20 | {:ok, [_ | _], _} ->
21 | true
22 |
23 | {:ok, %{msg: "no breach was found for given input"}, _} ->
24 | false
25 |
26 | {:error, :rate, msg, retry_secs} ->
27 | {:error, :rate, msg, retry_secs}
28 | end
29 | end
30 |
31 | @doc """
32 | Returns true if this password has been seen in a data breach on Have I Been Pwned
33 |
34 | ## Example
35 |
36 | iex> ExPwned.password_breached?("123456")
37 | true
38 | iex> ExPwned.password_breached?("correcthorsebatterystaplexkcdrules")
39 | false
40 | """
41 | def password_breached?(password) do
42 | Passwords.breached?(password)
43 | end
44 |
45 | @doc """
46 | Returns the number of times a password has been seen in a data breach. It will
47 | return zero if the password has not yet been found in a breach.
48 |
49 | ## Example
50 |
51 | iex> ExPwned.password_breach_count("123456")
52 | 20760336
53 | iex> ExPwned.password_breach_count("correcthorsebatterystaplexkcdrules")
54 | 0
55 | """
56 | def password_breach_count(password) do
57 | Passwords.password_breach_count(password)
58 | end
59 | end
60 |
--------------------------------------------------------------------------------
/lib/ex_pwned/passwords.ex:
--------------------------------------------------------------------------------
1 | defmodule ExPwned.Passwords do
2 | @moduledoc """
3 | Module to interact with HIBP API to retrive breached passwords data.
4 | """
5 |
6 | @doc """
7 | Returns true|false, or {:error, "reason for error, probably HTTP/Network related"}
8 | """
9 | def breached?(password) do
10 | case password_breach_count(password) do
11 | 0 -> false
12 | x when x > 0 -> true
13 | {:error, error} -> {:error, error}
14 | unexpected -> unexpected
15 | end
16 | end
17 |
18 | @doc """
19 | Returns an integer representing the number of times this password has been
20 | seen in a breach. Can be zero, representing no breaches.
21 | """
22 | def password_breach_count(password) do
23 | {partial_hash, hash_suffix} =
24 | password
25 | |> hash_sha1()
26 | |> String.split_at(5)
27 |
28 | call_api(partial_hash, hash_suffix)
29 | end
30 |
31 | def call_api(partial_hash, hash_suffix) do
32 | case HTTPoison.get("https://api.pwnedpasswords.com/range/" <> partial_hash) do
33 | {:ok, %HTTPoison.Response{body: body, status_code: 200}} ->
34 | handle_success(body, hash_suffix)
35 |
36 | {:ok, %HTTPoison.Response{body: body, status_code: 429}} ->
37 | {:error, body}
38 |
39 | other ->
40 | {:error, other}
41 | end
42 | end
43 |
44 | def handle_success(body, hash_suffix) do
45 | [_suffix, count] =
46 | body
47 | |> parse_body()
48 | # default: ["", "0"]
49 | |> Enum.find(["", "0"], &matches_suffix(&1, hash_suffix))
50 |
51 | count |> String.to_integer()
52 | end
53 |
54 | def parse_body(body) do
55 | body
56 | |> String.split(~r/\r\n/, trim: true)
57 | |> Enum.map(&String.split(&1, ":"))
58 | end
59 |
60 | defp matches_suffix([line_suffix, _count], search_suffix) do
61 | line_suffix == search_suffix
62 | end
63 |
64 | defp hash_sha1(word) do
65 | :crypto.hash(:sha, word) |> Base.encode16()
66 | end
67 | end
68 |
--------------------------------------------------------------------------------
/lib/ex_pwned/parser.ex:
--------------------------------------------------------------------------------
1 | defmodule ExPwned.Parser do
2 | @moduledoc """
3 | Generic parser to parse all the api responses
4 | """
5 |
6 | import ExPwned.Utils, only: [json_library: 0]
7 |
8 | @doc """
9 | Parses the response from hibp API calls
10 | """
11 | def parse(response) do
12 | case response do
13 | {:ok, %HTTPoison.Response{body: body, headers: headers, status_code: 200}} ->
14 | {:ok, parse_success_response(body), process_headers(headers)}
15 |
16 | {:ok, %HTTPoison.Response{body: _body, headers: headers, status_code: 404}} ->
17 | {:ok, %{msg: "no breach was found for given input"}, process_headers(headers)}
18 |
19 | {:ok, %HTTPoison.Response{body: _, headers: _, status_code: 400}} ->
20 | {:error, "bad request - the parameter does not comply with an acceptable format", 400}
21 |
22 | {:ok, %HTTPoison.Response{body: _, headers: _, status_code: 403}} ->
23 | {:error, "no user agent has been specified in the request", 403}
24 |
25 | {:ok, %HTTPoison.Response{body: _, headers: headers, status_code: 429}} ->
26 | # headers to map
27 | h = Enum.into(headers, %{})
28 | retry = Map.fetch!(h, "Retry-After")
29 | {retry_secs, ""} = Integer.parse(retry)
30 | msg = "Rate limit exceeded. Retry-After seconds."
31 | {:error, :rate, msg, retry_secs}
32 |
33 | {:ok, %HTTPoison.Response{body: body, headers: _, status_code: status}} ->
34 | {:error, body, status}
35 |
36 | {:error, %HTTPoison.Error{id: _, reason: reason}} ->
37 | {:error, reason, -1}
38 |
39 | _ ->
40 | response
41 | end
42 | end
43 |
44 | defp parse_success_response(body) do
45 | json_library().decode!(body)
46 | end
47 |
48 | defp process_headers(headers) when is_list(headers) and length(headers) > 0 do
49 | {_, retry_after} = List.keyfind(headers, "Retry-After", 0, {nil, "0"})
50 | [retry_after: String.to_integer(retry_after)]
51 | end
52 |
53 | defp process_headers(_), do: [retry_after: 0]
54 | end
55 |
--------------------------------------------------------------------------------
/mix.lock:
--------------------------------------------------------------------------------
1 | %{
2 | "bunt": {:hex, :bunt, "0.2.0", "951c6e801e8b1d2cbe58ebbd3e616a869061ddadcc4863d0a2182541acae9a38", [:mix], [], "hexpm", "7af5c7e09fe1d40f76c8e4f9dd2be7cebd83909f31fee7cd0e9eadc567da8353"},
3 | "certifi": {:hex, :certifi, "2.5.1", "867ce347f7c7d78563450a18a6a28a8090331e77fa02380b4a21962a65d36ee5", [:rebar3], [{:parse_trans, "~>3.3", [hex: :parse_trans, repo: "hexpm", optional: false]}], "hexpm", "805abd97539caf89ec6d4732c91e62ba9da0cda51ac462380bbd28ee697a8c42"},
4 | "credo": {:hex, :credo, "0.10.2", "03ad3a1eff79a16664ed42fc2975b5e5d0ce243d69318060c626c34720a49512", [:mix], [{:bunt, "~> 0.2.0", [hex: :bunt, repo: "hexpm", optional: false]}, {:jason, "~> 1.0", [hex: :jason, repo: "hexpm", optional: false]}], "hexpm", "539596b6774069260d5938aa73042a2f5157e1c0215aa35f5a53d83889546d14"},
5 | "earmark": {:hex, :earmark, "1.2.6", "b6da42b3831458d3ecc57314dff3051b080b9b2be88c2e5aa41cd642a5b044ed", [:mix], [], "hexpm", "b42a23e9bd92d65d16db2f75553982e58519054095356a418bb8320bbacb58b1"},
6 | "ex_doc": {:hex, :ex_doc, "0.19.1", "519bb9c19526ca51d326c060cb1778d4a9056b190086a8c6c115828eaccea6cf", [:mix], [{:earmark, "~> 1.1", [hex: :earmark, repo: "hexpm", optional: false]}, {:makeup_elixir, "~> 0.7", [hex: :makeup_elixir, repo: "hexpm", optional: false]}], "hexpm", "dc87f778d8260da0189a622f62790f6202af72f2f3dee6e78d91a18dd2fcd137"},
7 | "hackney": {:hex, :hackney, "1.15.2", "07e33c794f8f8964ee86cebec1a8ed88db5070e52e904b8f12209773c1036085", [:rebar3], [{:certifi, "2.5.1", [hex: :certifi, repo: "hexpm", optional: false]}, {:idna, "6.0.0", [hex: :idna, repo: "hexpm", optional: false]}, {:metrics, "1.0.1", [hex: :metrics, repo: "hexpm", optional: false]}, {:mimerl, "~>1.1", [hex: :mimerl, repo: "hexpm", optional: false]}, {:ssl_verify_fun, "1.1.5", [hex: :ssl_verify_fun, repo: "hexpm", optional: false]}], "hexpm", "e0100f8ef7d1124222c11ad362c857d3df7cb5f4204054f9f0f4a728666591fc"},
8 | "httpoison": {:hex, :httpoison, "1.6.2", "ace7c8d3a361cebccbed19c283c349b3d26991eff73a1eaaa8abae2e3c8089b6", [:mix], [{:hackney, "~> 1.15 and >= 1.15.2", [hex: :hackney, repo: "hexpm", optional: false]}], "hexpm", "aa2c74bd271af34239a3948779612f87df2422c2fdcfdbcec28d9c105f0773fe"},
9 | "idna": {:hex, :idna, "6.0.0", "689c46cbcdf3524c44d5f3dde8001f364cd7608a99556d8fbd8239a5798d4c10", [:rebar3], [{:unicode_util_compat, "0.4.1", [hex: :unicode_util_compat, repo: "hexpm", optional: false]}], "hexpm", "4bdd305eb64e18b0273864920695cb18d7a2021f31a11b9c5fbcd9a253f936e2"},
10 | "jason": {:hex, :jason, "1.2.0", "10043418c42d2493d0ee212d3fddd25d7ffe484380afad769a0a38795938e448", [:mix], [{:decimal, "~> 1.0", [hex: :decimal, repo: "hexpm", optional: true]}], "hexpm", "116747dbe057794c3a3e4e143b7c8390b29f634e16c78a7f59ba75bfa6852e7f"},
11 | "makeup": {:hex, :makeup, "0.5.5", "9e08dfc45280c5684d771ad58159f718a7b5788596099bdfb0284597d368a882", [:mix], [{:nimble_parsec, "~> 0.4", [hex: :nimble_parsec, repo: "hexpm", optional: false]}], "hexpm", "d7152ff93f2eac07905f510dfa03397134345ba4673a00fbf7119bab98632940"},
12 | "makeup_elixir": {:hex, :makeup_elixir, "0.10.0", "0f09c2ddf352887a956d84f8f7e702111122ca32fbbc84c2f0569b8b65cbf7fa", [:mix], [{:makeup, "~> 0.5.5", [hex: :makeup, repo: "hexpm", optional: false]}], "hexpm", "4a36dd2d0d5c5f98d95b3f410d7071cd661d5af310472229dd0e92161f168a44"},
13 | "metrics": {:hex, :metrics, "1.0.1", "25f094dea2cda98213cecc3aeff09e940299d950904393b2a29d191c346a8486", [:rebar3], [], "hexpm", "69b09adddc4f74a40716ae54d140f93beb0fb8978d8636eaded0c31b6f099f16"},
14 | "mimerl": {:hex, :mimerl, "1.2.0", "67e2d3f571088d5cfd3e550c383094b47159f3eee8ffa08e64106cdf5e981be3", [:rebar3], [], "hexpm", "f278585650aa581986264638ebf698f8bb19df297f66ad91b18910dfc6e19323"},
15 | "nimble_parsec": {:hex, :nimble_parsec, "0.4.0", "ee261bb53214943679422be70f1658fff573c5d0b0a1ecd0f18738944f818efe", [:mix], [], "hexpm", "ebb595e19456a72786db6dcd370d320350cb624f0b6203fcc7e23161d49b0ffb"},
16 | "parse_trans": {:hex, :parse_trans, "3.3.0", "09765507a3c7590a784615cfd421d101aec25098d50b89d7aa1d66646bc571c1", [:rebar3], [], "hexpm", "17ef63abde837ad30680ea7f857dd9e7ced9476cdd7b0394432af4bfc241b960"},
17 | "ssl_verify_fun": {:hex, :ssl_verify_fun, "1.1.5", "6eaf7ad16cb568bb01753dbbd7a95ff8b91c7979482b95f38443fe2c8852a79b", [:make, :mix, :rebar3], [], "hexpm", "13104d7897e38ed7f044c4de953a6c28597d1c952075eb2e328bc6d6f2bfc496"},
18 | "unicode_util_compat": {:hex, :unicode_util_compat, "0.4.1", "d869e4c68901dd9531385bb0c8c40444ebf624e60b6962d95952775cac5e90cd", [:rebar3], [], "hexpm", "1d1848c40487cdb0b30e8ed975e34e025860c02e419cb615d255849f3427439d"},
19 | "uuid": {:hex, :uuid, "1.1.8", "e22fc04499de0de3ed1116b770c7737779f226ceefa0badb3592e64d5cfb4eb9", [:mix], [], "hexpm", "c790593b4c3b601f5dc2378baae7efaf5b3d73c4c6456ba85759905be792f2ac"},
20 | }
21 |
--------------------------------------------------------------------------------
/lib/ex_pwned/breaches.ex:
--------------------------------------------------------------------------------
1 | defmodule ExPwned.Breaches do
2 | @moduledoc """
3 | Module to interact with hibp API to retrive breaches data
4 | """
5 |
6 | use ExPwned.Api
7 |
8 | @doc """
9 | return a list of all breaches a particular account has been involved in.
10 | The API takes a single parameter which is the account to be searched for.
11 | The account is not case sensitive and will be trimmed of leading or trailing white spaces.
12 | The account should always be URL encoded.
13 |
14 | ## Examples
15 |
16 | iex> ExPwned.Breaches.breachedaccount("abc@example.com")
17 | iex> ExPwned.Breaches.breachedaccount("abc@example.com", [truncateResponse: true, domain: "adobe.com"])
18 | """
19 | def breachedaccount(account, opts \\ []), do: do_get("breachedaccount/#{account}", opts)
20 |
21 | @doc """
22 | Get all breaches in hibp.
23 |
24 | ## Examples
25 |
26 | iex> ExPwned.Breaches.breaches
27 | {:ok,
28 | [%{"AddedDate" => "2015-10-26T23:35:45Z", "BreachDate" => "2015-03-01",
29 | "DataClasses" => ["Email addresses", "IP addresses", "Names", "Passwords"],
30 | "Description" => "In approximately March 2015, the free web hosting provider 000webhost suffered a major data breach that exposed over 13 million customer records. The data was sold and traded before 000webhost was alerted in October. The breach included names, email addresses and plain text passwords.",
31 | "Domain" => "000webhost.com", "IsActive" => true, "IsRetired" => false,
32 | "IsSensitive" => false, "IsSpamList" => false, "IsVerified" => true,
33 | "LogoType" => "png", "Name" => "000webhost", "PwnCount" => 13545468,
34 | "Title" => "000webhost"},
35 | [retry_after: 0]
36 | }
37 | """
38 | def breaches, do: do_get("breaches")
39 |
40 | @doc """
41 | Filters the result set to only breaches against the domain specified
42 |
43 | ## Example
44 |
45 | iex> ExPwned.Breaches.breaches("000webhost.com")
46 | {:ok,
47 | [%{"AddedDate" => "2015-10-26T23:35:45Z", "BreachDate" => "2015-03-01",
48 | "DataClasses" => ["Email addresses", "IP addresses", "Names", "Passwords"],
49 | "Description" => "In approximately March 2015, the free web hosting provider 000webhost suffered a major data breach that exposed over 13 million customer records. The data was sold and traded before 000webhost was alerted in October. The breach included names, email addresses and plain text passwords.",
50 | "Domain" => "000webhost.com", "IsActive" => true, "IsRetired" => false,
51 | "IsSensitive" => false, "IsSpamList" => false, "IsVerified" => true,
52 | "LogoType" => "png", "Name" => "000webhost", "PwnCount" => 13545468,
53 | "Title" => "000webhost"}], [retry_after: 0]}
54 | """
55 | def breaches(domain), do: do_get("breaches", %{domain: domain})
56 |
57 | @doc """
58 | Sometimes just a single breach is required and this can be retrieved by the breach "name".
59 | This is the stable value which may or may not be the same as the breach "title" (which can change).
60 |
61 | ## Example
62 |
63 | iex> ExPwned.Breaches.breach("000webhost")
64 | {:ok,
65 | %{"AddedDate" => "2015-10-26T23:35:45Z", "BreachDate" => "2015-03-01",
66 | "DataClasses" => ["Email addresses", "IP addresses", "Names", "Passwords"],
67 | "Description" => "In approximately March 2015, the free web hosting provider 000webhost suffered a major data breach that exposed over 13 million customer records. The data was sold and traded before 000webhost was alerted in October. The breach included names, email addresses and plain text passwords.",
68 | "Domain" => "000webhost.com", "IsActive" => true, "IsRetired" => false,
69 | "IsSensitive" => false, "IsSpamList" => false, "IsVerified" => true,
70 | "LogoType" => "png", "Name" => "000webhost", "PwnCount" => 13545468,
71 | "Title" => "000webhost"}, [retry_after: 0]}
72 | """
73 | def breach(name), do: do_get("breach/#{name}")
74 |
75 | @doc """
76 | A "data class" is an attribute of a record compromised in a breach.
77 | For example, many breaches expose data classes such as "Email addresses" and "Passwords".
78 | The values returned by this service are ordered alphabetically in a string array
79 | and will expand over time as new breaches expose previously unseen classes of data.
80 |
81 | iex> ExPwned.Breaches.dataclasses
82 | {:ok,
83 | ["Account balances", "Age groups", "Astrological signs", "Avatars",
84 | "Bank account numbers", "Banking PINs", "Beauty ratings", "Biometric data",
85 | "Browser user agent details", "Car ownership statuses", "Career levels",
86 | "Chat logs", "Credit card CVV", "Credit cards", "Credit status information",
87 | "Customer feedback", "Customer interactions", "Dates of birth",
88 | "Deceased date", "Device information", "Device usage tracking data",
89 | "Drinking habits", "Drug habits", "Education levels", "Email addresses",
90 | "Email messages", "Employers", "Ethnicities", "Family members' names",
91 | "Family plans", "Family structure", "Financial transactions",
92 | "Fitness levels", "Genders", "Geographic locations", "Government issued IDs",
93 | "Historical passwords", "Home ownership statuses", "Homepage URLs",
94 | "Income levels", "Instant messenger identities", "IP addresses", "Job titles",
95 | "MAC addresses", "Marital statuses", "Names", "Nicknames", "Parenting plans",
96 | ...], [retry_after: 0]}
97 | """
98 | def dataclasses, do: do_get("dataclasses")
99 | end
100 |
--------------------------------------------------------------------------------
/README.md:
--------------------------------------------------------------------------------
1 | # ExPwned
2 |
3 | [](https://hex.pm/packages/ex_pwned) 
4 |
5 | > Elixir client for haveibeenpwned.com
6 |
7 | ## Installation
8 |
9 | The package can be installed as:
10 |
11 | 1. Add `ex_pwned` to your list of dependencies in `mix.exs`:
12 |
13 | ```elixir
14 | def deps do
15 | [{:ex_pwned, "~> 0.1.0"}]
16 | end
17 | ```
18 |
19 | 2. Ensure `ex_pwned` is started before your application:
20 |
21 | ```elixir
22 | def application do
23 | [applications: [:ex_pwned]]
24 | end
25 | ```
26 |
27 | ## Configuration
28 |
29 | You can set the user agent for ExPwned (defaults to `ExPwned Elixir Client`) by specifying user agent in config.
30 |
31 | ```elixir
32 | config :ex_pwned,
33 | user_agent: "ExMustang Slackbot"
34 | ```
35 |
36 | You can configure the json library to use for decoding body. By default, it is set to Jason.
37 | The json library is supposed to have implemented `decode!/1`.
38 |
39 | ```elixir
40 | config :ex_pwned,
41 | json_library: Poison
42 | ```
43 |
44 | ## Usage
45 |
46 | Using `ExPwned` is simple.
47 |
48 | #### Check if an account is breached or not
49 |
50 | ```elixir
51 | iex> ExPwned.breached?("abc@example.com")
52 | true
53 | ```
54 |
55 | #### Check if a password is breached, and how many times
56 | ```elixir
57 | # True/False Check
58 | iex> ExPwned.password_breached?("password123")
59 | true
60 |
61 | # Returns # of times password was seen in a breach. Zero if none.
62 | iex> ExPwned.password_breach_count("password123")
63 | 5032
64 | ```
65 |
66 | #### Check the breaches for an account
67 |
68 | ```elixir
69 | iex> ExPwned.Breaches.breachedaccount("abc@example.com")
70 | {:ok,
71 | [%{"AddedDate" => "2015-10-26T23:35:45Z", "BreachDate" => "2015-03-01",
72 | "DataClasses" => ["Email addresses", "IP addresses", "Names", "Passwords"],
73 | "Description" => "In approximately March 2015, the free web hosting provider 000webhost suffered a major data breach that exposed over 13 million customer records. The data was sold and traded before 000webhost was alerted in October. The breach included names, email addresses and plain text passwords.",
74 | "Domain" => "000webhost.com", "IsActive" => true, "IsRetired" => false,
75 | "IsSensitive" => false, "IsSpamList" => false, "IsVerified" => true,
76 | "LogoType" => "png", "Name" => "000webhost", "PwnCount" => 13545468,
77 | "Title" => "000webhost"}], [retry_after: 0]}
78 |
79 | iex> ExPwned.Breaches.breachedaccount("abc@example.com", [truncateResponse: true, domain: "adobe.com"])
80 | {:ok, [%{"Name" => "000webhost"}], [retry_after: 0]}
81 | ```
82 |
83 | #### Get all available breaches
84 |
85 | ```elixir
86 | iex> ExPwned.Breaches.breaches
87 | {:ok,
88 | [%{"AddedDate" => "2015-10-26T23:35:45Z", "BreachDate" => "2015-03-01",
89 | "DataClasses" => ["Email addresses", "IP addresses", "Names", "Passwords"],
90 | "Description" => "In approximately March 2015, the free web hosting provider 000webhost suffered a major data breach that exposed over 13 million customer records. The data was sold and traded before 000webhost was alerted in October. The breach included names, email addresses and plain text passwords.",
91 | "Domain" => "000webhost.com", "IsActive" => true, "IsRetired" => false,
92 | "IsSensitive" => false, "IsSpamList" => false, "IsVerified" => true,
93 | "LogoType" => "png", "Name" => "000webhost", "PwnCount" => 13545468,
94 | "Title" => "000webhost"},
95 | [retry_after: 0]
96 | }
97 |
98 | # or breaches for specific domain
99 | iex> ExPwned.Breaches.breaches("000webhost.com")
100 | {:ok,
101 | [%{"AddedDate" => "2015-10-26T23:35:45Z", "BreachDate" => "2015-03-01",
102 | "DataClasses" => ["Email addresses", "IP addresses", "Names", "Passwords"],
103 | "Description" => "In approximately March 2015, the free web hosting provider 000webhost suffered a major data breach that exposed over 13 million customer records. The data was sold and traded before 000webhost was alerted in October. The breach included names, email addresses and plain text passwords.",
104 | "Domain" => "000webhost.com", "IsActive" => true, "IsRetired" => false,
105 | "IsSensitive" => false, "IsSpamList" => false, "IsVerified" => true,
106 | "LogoType" => "png", "Name" => "000webhost", "PwnCount" => 13545468,
107 | "Title" => "000webhost"}], [retry_after: 0]}
108 | ```
109 |
110 | #### Get specific breach detail
111 |
112 | ```elixir
113 | iex> ExPwned.Breaches.breach("000webhost")
114 | {:ok,
115 | %{"AddedDate" => "2015-10-26T23:35:45Z", "BreachDate" => "2015-03-01",
116 | "DataClasses" => ["Email addresses", "IP addresses", "Names", "Passwords"],
117 | "Description" => "In approximately March 2015, the free web hosting provider 000webhost suffered a major data breach that exposed over 13 million customer records. The data was sold and traded before 000webhost was alerted in October. The breach included names, email addresses and plain text passwords.",
118 | "Domain" => "000webhost.com", "IsActive" => true, "IsRetired" => false,
119 | "IsSensitive" => false, "IsSpamList" => false, "IsVerified" => true,
120 | "LogoType" => "png", "Name" => "000webhost", "PwnCount" => 13545468,
121 | "Title" => "000webhost"}, [retry_after: 0]}
122 | ```
123 |
124 | #### Get all data classes for breaches
125 |
126 | ```elixir
127 | iex> ExPwned.Breaches.dataclasses
128 | {:ok,
129 | ["Account balances", "Age groups", "Astrological signs", "Avatars",
130 | "Bank account numbers", "Banking PINs", "Beauty ratings", "Biometric data",
131 | "Browser user agent details", "Car ownership statuses", "Career levels",
132 | "Chat logs", "Credit card CVV", "Credit cards", "Credit status information",
133 | "Customer feedback", "Customer interactions", "Dates of birth",
134 | "Deceased date", "Device information", "Device usage tracking data",
135 | "Drinking habits", "Drug habits", "Education levels", "Email addresses",
136 | "Email messages", "Employers", "Ethnicities", "Family members' names",
137 | "Family plans", "Family structure", "Financial transactions",
138 | "Fitness levels", "Genders", "Geographic locations", "Government issued IDs",
139 | "Historical passwords", "Home ownership statuses", "Homepage URLs",
140 | "Income levels", "Instant messenger identities", "IP addresses", "Job titles",
141 | "MAC addresses", "Marital statuses", "Names", "Nicknames", "Parenting plans",
142 | ...], [retry_after: 0]}
143 | ```
144 |
145 | #### Get the pastes for an account
146 |
147 | ```elixir
148 | iex> ExPwned.Pastes.pasteaccount("abc@example.com")
149 | {:ok,
150 | [%{"Date" => nil, "EmailCount" => 4788657,
151 | "Id" => "https://pred.me/gmail.html", "Source" => "AdHocUrl",
152 | "Title" => "pred.me"}], [retry_after: 0]}
153 | ```
154 |
155 | ### Response
156 |
157 | The response follows following patterns:
158 |
159 | ```elixir
160 | # result found
161 | {:ok, result, [retry_after: seconds_value]}
162 |
163 | # no breach
164 | {:ok, %{msg: "no breach was found for given input"}, [retry_after: seconds_value]}
165 |
166 | # for errors, the third arg is status code instead
167 |
168 | # 400 bad request
169 | {:error, "bad request - the parameter does not comply with an acceptable format", 400}
170 |
171 | # 403 forbidden
172 | {:error, "no user agent has been specified in the request", 403}
173 | ```
174 |
--------------------------------------------------------------------------------
/LICENSE:
--------------------------------------------------------------------------------
1 | Apache License
2 | Version 2.0, January 2004
3 | http://www.apache.org/licenses/
4 |
5 | TERMS AND CONDITIONS FOR USE, REPRODUCTION, AND DISTRIBUTION
6 |
7 | 1. Definitions.
8 |
9 | "License" shall mean the terms and conditions for use, reproduction,
10 | and distribution as defined by Sections 1 through 9 of this document.
11 |
12 | "Licensor" shall mean the copyright owner or entity authorized by
13 | the copyright owner that is granting the License.
14 |
15 | "Legal Entity" shall mean the union of the acting entity and all
16 | other entities that control, are controlled by, or are under common
17 | control with that entity. For the purposes of this definition,
18 | "control" means (i) the power, direct or indirect, to cause the
19 | direction or management of such entity, whether by contract or
20 | otherwise, or (ii) ownership of fifty percent (50%) or more of the
21 | outstanding shares, or (iii) beneficial ownership of such entity.
22 |
23 | "You" (or "Your") shall mean an individual or Legal Entity
24 | exercising permissions granted by this License.
25 |
26 | "Source" form shall mean the preferred form for making modifications,
27 | including but not limited to software source code, documentation
28 | source, and configuration files.
29 |
30 | "Object" form shall mean any form resulting from mechanical
31 | transformation or translation of a Source form, including but
32 | not limited to compiled object code, generated documentation,
33 | and conversions to other media types.
34 |
35 | "Work" shall mean the work of authorship, whether in Source or
36 | Object form, made available under the License, as indicated by a
37 | copyright notice that is included in or attached to the work
38 | (an example is provided in the Appendix below).
39 |
40 | "Derivative Works" shall mean any work, whether in Source or Object
41 | form, that is based on (or derived from) the Work and for which the
42 | editorial revisions, annotations, elaborations, or other modifications
43 | represent, as a whole, an original work of authorship. For the purposes
44 | of this License, Derivative Works shall not include works that remain
45 | separable from, or merely link (or bind by name) to the interfaces of,
46 | the Work and Derivative Works thereof.
47 |
48 | "Contribution" shall mean any work of authorship, including
49 | the original version of the Work and any modifications or additions
50 | to that Work or Derivative Works thereof, that is intentionally
51 | submitted to Licensor for inclusion in the Work by the copyright owner
52 | or by an individual or Legal Entity authorized to submit on behalf of
53 | the copyright owner. For the purposes of this definition, "submitted"
54 | means any form of electronic, verbal, or written communication sent
55 | to the Licensor or its representatives, including but not limited to
56 | communication on electronic mailing lists, source code control systems,
57 | and issue tracking systems that are managed by, or on behalf of, the
58 | Licensor for the purpose of discussing and improving the Work, but
59 | excluding communication that is conspicuously marked or otherwise
60 | designated in writing by the copyright owner as "Not a Contribution."
61 |
62 | "Contributor" shall mean Licensor and any individual or Legal Entity
63 | on behalf of whom a Contribution has been received by Licensor and
64 | subsequently incorporated within the Work.
65 |
66 | 2. Grant of Copyright License. Subject to the terms and conditions of
67 | this License, each Contributor hereby grants to You a perpetual,
68 | worldwide, non-exclusive, no-charge, royalty-free, irrevocable
69 | copyright license to reproduce, prepare Derivative Works of,
70 | publicly display, publicly perform, sublicense, and distribute the
71 | Work and such Derivative Works in Source or Object form.
72 |
73 | 3. Grant of Patent License. Subject to the terms and conditions of
74 | this License, each Contributor hereby grants to You a perpetual,
75 | worldwide, non-exclusive, no-charge, royalty-free, irrevocable
76 | (except as stated in this section) patent license to make, have made,
77 | use, offer to sell, sell, import, and otherwise transfer the Work,
78 | where such license applies only to those patent claims licensable
79 | by such Contributor that are necessarily infringed by their
80 | Contribution(s) alone or by combination of their Contribution(s)
81 | with the Work to which such Contribution(s) was submitted. If You
82 | institute patent litigation against any entity (including a
83 | cross-claim or counterclaim in a lawsuit) alleging that the Work
84 | or a Contribution incorporated within the Work constitutes direct
85 | or contributory patent infringement, then any patent licenses
86 | granted to You under this License for that Work shall terminate
87 | as of the date such litigation is filed.
88 |
89 | 4. Redistribution. You may reproduce and distribute copies of the
90 | Work or Derivative Works thereof in any medium, with or without
91 | modifications, and in Source or Object form, provided that You
92 | meet the following conditions:
93 |
94 | (a) You must give any other recipients of the Work or
95 | Derivative Works a copy of this License; and
96 |
97 | (b) You must cause any modified files to carry prominent notices
98 | stating that You changed the files; and
99 |
100 | (c) You must retain, in the Source form of any Derivative Works
101 | that You distribute, all copyright, patent, trademark, and
102 | attribution notices from the Source form of the Work,
103 | excluding those notices that do not pertain to any part of
104 | the Derivative Works; and
105 |
106 | (d) If the Work includes a "NOTICE" text file as part of its
107 | distribution, then any Derivative Works that You distribute must
108 | include a readable copy of the attribution notices contained
109 | within such NOTICE file, excluding those notices that do not
110 | pertain to any part of the Derivative Works, in at least one
111 | of the following places: within a NOTICE text file distributed
112 | as part of the Derivative Works; within the Source form or
113 | documentation, if provided along with the Derivative Works; or,
114 | within a display generated by the Derivative Works, if and
115 | wherever such third-party notices normally appear. The contents
116 | of the NOTICE file are for informational purposes only and
117 | do not modify the License. You may add Your own attribution
118 | notices within Derivative Works that You distribute, alongside
119 | or as an addendum to the NOTICE text from the Work, provided
120 | that such additional attribution notices cannot be construed
121 | as modifying the License.
122 |
123 | You may add Your own copyright statement to Your modifications and
124 | may provide additional or different license terms and conditions
125 | for use, reproduction, or distribution of Your modifications, or
126 | for any such Derivative Works as a whole, provided Your use,
127 | reproduction, and distribution of the Work otherwise complies with
128 | the conditions stated in this License.
129 |
130 | 5. Submission of Contributions. Unless You explicitly state otherwise,
131 | any Contribution intentionally submitted for inclusion in the Work
132 | by You to the Licensor shall be under the terms and conditions of
133 | this License, without any additional terms or conditions.
134 | Notwithstanding the above, nothing herein shall supersede or modify
135 | the terms of any separate license agreement you may have executed
136 | with Licensor regarding such Contributions.
137 |
138 | 6. Trademarks. This License does not grant permission to use the trade
139 | names, trademarks, service marks, or product names of the Licensor,
140 | except as required for reasonable and customary use in describing the
141 | origin of the Work and reproducing the content of the NOTICE file.
142 |
143 | 7. Disclaimer of Warranty. Unless required by applicable law or
144 | agreed to in writing, Licensor provides the Work (and each
145 | Contributor provides its Contributions) on an "AS IS" BASIS,
146 | WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or
147 | implied, including, without limitation, any warranties or conditions
148 | of TITLE, NON-INFRINGEMENT, MERCHANTABILITY, or FITNESS FOR A
149 | PARTICULAR PURPOSE. You are solely responsible for determining the
150 | appropriateness of using or redistributing the Work and assume any
151 | risks associated with Your exercise of permissions under this License.
152 |
153 | 8. Limitation of Liability. In no event and under no legal theory,
154 | whether in tort (including negligence), contract, or otherwise,
155 | unless required by applicable law (such as deliberate and grossly
156 | negligent acts) or agreed to in writing, shall any Contributor be
157 | liable to You for damages, including any direct, indirect, special,
158 | incidental, or consequential damages of any character arising as a
159 | result of this License or out of the use or inability to use the
160 | Work (including but not limited to damages for loss of goodwill,
161 | work stoppage, computer failure or malfunction, or any and all
162 | other commercial damages or losses), even if such Contributor
163 | has been advised of the possibility of such damages.
164 |
165 | 9. Accepting Warranty or Additional Liability. While redistributing
166 | the Work or Derivative Works thereof, You may choose to offer,
167 | and charge a fee for, acceptance of support, warranty, indemnity,
168 | or other liability obligations and/or rights consistent with this
169 | License. However, in accepting such obligations, You may act only
170 | on Your own behalf and on Your sole responsibility, not on behalf
171 | of any other Contributor, and only if You agree to indemnify,
172 | defend, and hold each Contributor harmless for any liability
173 | incurred by, or claims asserted against, such Contributor by reason
174 | of your accepting any such warranty or additional liability.
175 |
176 | END OF TERMS AND CONDITIONS
177 |
178 | APPENDIX: How to apply the Apache License to your work.
179 |
180 | To apply the Apache License to your work, attach the following
181 | boilerplate notice, with the fields enclosed by brackets "{}"
182 | replaced with your own identifying information. (Don't include
183 | the brackets!) The text should be enclosed in the appropriate
184 | comment syntax for the file format. We also recommend that a
185 | file or class name and description of purpose be included on the
186 | same "printed page" as the copyright notice for easier
187 | identification within third-party archives.
188 |
189 | Copyright {yyyy} {name of copyright owner}
190 |
191 | Licensed under the Apache License, Version 2.0 (the "License");
192 | you may not use this file except in compliance with the License.
193 | You may obtain a copy of the License at
194 |
195 | http://www.apache.org/licenses/LICENSE-2.0
196 |
197 | Unless required by applicable law or agreed to in writing, software
198 | distributed under the License is distributed on an "AS IS" BASIS,
199 | WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
200 | See the License for the specific language governing permissions and
201 | limitations under the License.
202 |
--------------------------------------------------------------------------------