Skip to content

IntelOwlClass

IntelOwl Class

Source code in docs/Submodules/pyintelowl/pyintelowl/pyintelowl.py
  19
  20
  21
  22
  23
  24
  25
  26
  27
  28
  29
  30
  31
  32
  33
  34
  35
  36
  37
  38
  39
  40
  41
  42
  43
  44
  45
  46
  47
  48
  49
  50
  51
  52
  53
  54
  55
  56
  57
  58
  59
  60
  61
  62
  63
  64
  65
  66
  67
  68
  69
  70
  71
  72
  73
  74
  75
  76
  77
  78
  79
  80
  81
  82
  83
  84
  85
  86
  87
  88
  89
  90
  91
  92
  93
  94
  95
  96
  97
  98
  99
 100
 101
 102
 103
 104
 105
 106
 107
 108
 109
 110
 111
 112
 113
 114
 115
 116
 117
 118
 119
 120
 121
 122
 123
 124
 125
 126
 127
 128
 129
 130
 131
 132
 133
 134
 135
 136
 137
 138
 139
 140
 141
 142
 143
 144
 145
 146
 147
 148
 149
 150
 151
 152
 153
 154
 155
 156
 157
 158
 159
 160
 161
 162
 163
 164
 165
 166
 167
 168
 169
 170
 171
 172
 173
 174
 175
 176
 177
 178
 179
 180
 181
 182
 183
 184
 185
 186
 187
 188
 189
 190
 191
 192
 193
 194
 195
 196
 197
 198
 199
 200
 201
 202
 203
 204
 205
 206
 207
 208
 209
 210
 211
 212
 213
 214
 215
 216
 217
 218
 219
 220
 221
 222
 223
 224
 225
 226
 227
 228
 229
 230
 231
 232
 233
 234
 235
 236
 237
 238
 239
 240
 241
 242
 243
 244
 245
 246
 247
 248
 249
 250
 251
 252
 253
 254
 255
 256
 257
 258
 259
 260
 261
 262
 263
 264
 265
 266
 267
 268
 269
 270
 271
 272
 273
 274
 275
 276
 277
 278
 279
 280
 281
 282
 283
 284
 285
 286
 287
 288
 289
 290
 291
 292
 293
 294
 295
 296
 297
 298
 299
 300
 301
 302
 303
 304
 305
 306
 307
 308
 309
 310
 311
 312
 313
 314
 315
 316
 317
 318
 319
 320
 321
 322
 323
 324
 325
 326
 327
 328
 329
 330
 331
 332
 333
 334
 335
 336
 337
 338
 339
 340
 341
 342
 343
 344
 345
 346
 347
 348
 349
 350
 351
 352
 353
 354
 355
 356
 357
 358
 359
 360
 361
 362
 363
 364
 365
 366
 367
 368
 369
 370
 371
 372
 373
 374
 375
 376
 377
 378
 379
 380
 381
 382
 383
 384
 385
 386
 387
 388
 389
 390
 391
 392
 393
 394
 395
 396
 397
 398
 399
 400
 401
 402
 403
 404
 405
 406
 407
 408
 409
 410
 411
 412
 413
 414
 415
 416
 417
 418
 419
 420
 421
 422
 423
 424
 425
 426
 427
 428
 429
 430
 431
 432
 433
 434
 435
 436
 437
 438
 439
 440
 441
 442
 443
 444
 445
 446
 447
 448
 449
 450
 451
 452
 453
 454
 455
 456
 457
 458
 459
 460
 461
 462
 463
 464
 465
 466
 467
 468
 469
 470
 471
 472
 473
 474
 475
 476
 477
 478
 479
 480
 481
 482
 483
 484
 485
 486
 487
 488
 489
 490
 491
 492
 493
 494
 495
 496
 497
 498
 499
 500
 501
 502
 503
 504
 505
 506
 507
 508
 509
 510
 511
 512
 513
 514
 515
 516
 517
 518
 519
 520
 521
 522
 523
 524
 525
 526
 527
 528
 529
 530
 531
 532
 533
 534
 535
 536
 537
 538
 539
 540
 541
 542
 543
 544
 545
 546
 547
 548
 549
 550
 551
 552
 553
 554
 555
 556
 557
 558
 559
 560
 561
 562
 563
 564
 565
 566
 567
 568
 569
 570
 571
 572
 573
 574
 575
 576
 577
 578
 579
 580
 581
 582
 583
 584
 585
 586
 587
 588
 589
 590
 591
 592
 593
 594
 595
 596
 597
 598
 599
 600
 601
 602
 603
 604
 605
 606
 607
 608
 609
 610
 611
 612
 613
 614
 615
 616
 617
 618
 619
 620
 621
 622
 623
 624
 625
 626
 627
 628
 629
 630
 631
 632
 633
 634
 635
 636
 637
 638
 639
 640
 641
 642
 643
 644
 645
 646
 647
 648
 649
 650
 651
 652
 653
 654
 655
 656
 657
 658
 659
 660
 661
 662
 663
 664
 665
 666
 667
 668
 669
 670
 671
 672
 673
 674
 675
 676
 677
 678
 679
 680
 681
 682
 683
 684
 685
 686
 687
 688
 689
 690
 691
 692
 693
 694
 695
 696
 697
 698
 699
 700
 701
 702
 703
 704
 705
 706
 707
 708
 709
 710
 711
 712
 713
 714
 715
 716
 717
 718
 719
 720
 721
 722
 723
 724
 725
 726
 727
 728
 729
 730
 731
 732
 733
 734
 735
 736
 737
 738
 739
 740
 741
 742
 743
 744
 745
 746
 747
 748
 749
 750
 751
 752
 753
 754
 755
 756
 757
 758
 759
 760
 761
 762
 763
 764
 765
 766
 767
 768
 769
 770
 771
 772
 773
 774
 775
 776
 777
 778
 779
 780
 781
 782
 783
 784
 785
 786
 787
 788
 789
 790
 791
 792
 793
 794
 795
 796
 797
 798
 799
 800
 801
 802
 803
 804
 805
 806
 807
 808
 809
 810
 811
 812
 813
 814
 815
 816
 817
 818
 819
 820
 821
 822
 823
 824
 825
 826
 827
 828
 829
 830
 831
 832
 833
 834
 835
 836
 837
 838
 839
 840
 841
 842
 843
 844
 845
 846
 847
 848
 849
 850
 851
 852
 853
 854
 855
 856
 857
 858
 859
 860
 861
 862
 863
 864
 865
 866
 867
 868
 869
 870
 871
 872
 873
 874
 875
 876
 877
 878
 879
 880
 881
 882
 883
 884
 885
 886
 887
 888
 889
 890
 891
 892
 893
 894
 895
 896
 897
 898
 899
 900
 901
 902
 903
 904
 905
 906
 907
 908
 909
 910
 911
 912
 913
 914
 915
 916
 917
 918
 919
 920
 921
 922
 923
 924
 925
 926
 927
 928
 929
 930
 931
 932
 933
 934
 935
 936
 937
 938
 939
 940
 941
 942
 943
 944
 945
 946
 947
 948
 949
 950
 951
 952
 953
 954
 955
 956
 957
 958
 959
 960
 961
 962
 963
 964
 965
 966
 967
 968
 969
 970
 971
 972
 973
 974
 975
 976
 977
 978
 979
 980
 981
 982
 983
 984
 985
 986
 987
 988
 989
 990
 991
 992
 993
 994
 995
 996
 997
 998
 999
1000
1001
1002
1003
1004
1005
1006
1007
1008
1009
1010
1011
1012
1013
1014
1015
1016
1017
1018
1019
1020
1021
1022
1023
1024
1025
1026
1027
1028
1029
1030
1031
1032
1033
1034
1035
1036
1037
1038
1039
1040
1041
1042
1043
1044
1045
1046
1047
1048
1049
1050
1051
1052
1053
1054
1055
1056
1057
1058
1059
1060
1061
1062
1063
1064
1065
1066
1067
1068
1069
1070
1071
1072
1073
1074
1075
1076
1077
1078
1079
1080
1081
1082
1083
1084
1085
1086
1087
class IntelOwl:
    logger: logging.Logger

    def __init__(
        self,
        token: str,
        instance_url: str,
        certificate: str = None,
        proxies: dict = None,
        logger: logging.Logger = None,
        cli: bool = False,
    ):
        self.token = token
        self.instance = instance_url
        self.certificate = certificate
        if logger:
            self.logger = logger
        else:
            self.logger = logging.getLogger(__name__)
        if proxies and not isinstance(proxies, dict):
            raise TypeError("proxies param must be a dictionary")
        self.proxies = proxies
        self.cli = cli

    @property
    def session(self) -> requests.Session:
        """
        Internal use only.
        """
        if not hasattr(self, "_session"):
            session = requests.Session()
            if self.certificate is not True:
                session.verify = self.certificate
            if self.proxies:
                session.proxies = self.proxies
            session.headers.update(
                {
                    "Authorization": f"Token {self.token}",
                    "User-Agent": f"PyIntelOwl/{__version__}",
                }
            )
            self._session = session

        return self._session

    def __make_request(
        self,
        method: Literal["GET", "POST", "PUT", "PATCH", "DELETE"] = "GET",
        *args,
        **kwargs,
    ) -> requests.Response:
        """
        For internal use only.
        """
        response: requests.Response = None
        requests_function_map: Dict[str, Callable] = {
            "GET": self.session.get,
            "POST": self.session.post,
            "PUT": self.session.put,
            "PATCH": self.session.patch,
            "DELETE": self.session.delete,
        }
        func = requests_function_map.get(method, None)
        if not func:
            raise RuntimeError(f"Unsupported method name: {method}")

        try:
            response = func(*args, **kwargs)
            self.logger.debug(
                msg=(response.url, response.status_code, response.content)
            )
            response.raise_for_status()
        except Exception as e:
            raise IntelOwlClientException(e, response=response)

        return response

    def ask_analysis_availability(
        self,
        md5: str,
        analyzers: List[str] = None,
        check_reported_analysis_too: bool = False,
        minutes_ago: int = None,
    ) -> Dict:
        """Search for already available analysis.\n
        Endpoint: ``/api/ask_analysis_availability``

        Args:
            md5 (str): md5sum of the observable or file
            analyzers (List[str], optional):
            list of analyzers to trigger.
            Defaults to `None` meaning automatically select all configured analyzers.
            check_reported_analysis_too (bool, optional):
            Check against all existing jobs. Defaults to ``False``.
            minutes_ago (int, optional):
            number of minutes to check back for analysis.
            Default is None so the check does not have any time limits.

        Raises:
            IntelOwlClientException: on client/HTTP error

        Returns:
            Dict: JSON body
        """
        if not analyzers:
            analyzers = []
        data = {"md5": md5, "analyzers": analyzers}
        if not check_reported_analysis_too:
            data["running_only"] = True
        if minutes_ago:
            data["minutes_ago"] = int(minutes_ago)
        url = self.instance + "/api/ask_analysis_availability"
        response = self.__make_request("POST", url=url, data=data)
        answer = response.json()
        status, job_id = answer.get("status", None), answer.get("job_id", None)
        # check sanity cases
        if not status:
            raise IntelOwlClientException(
                "API ask_analysis_availability gave result without status ?"
                f" Response: {answer}"
            )
        if status != "not_available" and not job_id:
            raise IntelOwlClientException(
                "API ask_analysis_availability gave result without job_id ?"
                f" Response: {answer}"
            )
        return answer

    def send_file_analysis_request(
        self,
        filename: str,
        binary: bytes,
        tlp: TLPType = "CLEAR",
        analyzers_requested: List[str] = None,
        connectors_requested: List[str] = None,
        runtime_configuration: Dict = None,
        tags_labels: List[str] = None,
    ) -> Dict:
        """Send analysis request for a file.\n
        Endpoint: ``/api/analyze_file``

        Args:

            filename (str):
                Filename
            binary (bytes):
                File contents as bytes
            analyzers_requested (List[str], optional):
                List of analyzers to invoke
                Defaults to ``[]`` i.e. all analyzers.
            connectors_requested (List[str], optional):
                List of specific connectors to invoke.
                Defaults to ``[]`` i.e. all connectors.
            tlp (str, optional):
                TLP for the analysis.
                (options: ``CLEAR, GREEN, AMBER, RED``).
            runtime_configuration (Dict, optional):
                Overwrite configuration for analyzers. Defaults to ``{}``.
            tags_labels (List[str], optional):
                List of tag labels to assign (creates non-existing tags)

        Raises:
            IntelOwlClientException: on client/HTTP error

        Returns:
            Dict: JSON body
        """
        try:
            if not tlp:
                tlp = "CLEAR"
            if not analyzers_requested:
                analyzers_requested = []
            if not connectors_requested:
                connectors_requested = []
            if not tags_labels:
                tags_labels = []
            if not runtime_configuration:
                runtime_configuration = {}
            data = {
                "file_name": filename,
                "analyzers_requested": analyzers_requested,
                "connectors_requested": connectors_requested,
                "tlp": tlp,
                "tags_labels": tags_labels,
            }
            if runtime_configuration:
                data["runtime_configuration"] = json.dumps(runtime_configuration)
            files = {"file": (filename, binary)}
            answer = self.__send_analysis_request(data=data, files=files)
        except Exception as e:
            raise IntelOwlClientException(e)
        return answer

    def send_file_analysis_playbook_request(
        self,
        filename: str,
        binary: bytes,
        playbook_requested: str,
        tlp: TLPType = "CLEAR",
        runtime_configuration: Dict = None,
        tags_labels: List[str] = None,
    ) -> Dict:
        """Send playbook analysis request for a file.\n
        Endpoint: ``/api/playbook/analyze_multiple_files``

        Args:

            filename (str):
                Filename
            binary (bytes):
                File contents as bytes
            playbook_requested (str, optional):
            tlp (str, optional):
                TLP for the analysis.
                (options: ``WHITE, GREEN, AMBER, RED``).
            runtime_configuration (Dict, optional):
                Overwrite configuration for analyzers. Defaults to ``{}``.
            tags_labels (List[str], optional):
                List of tag labels to assign (creates non-existing tags)

        Raises:
            IntelOwlClientException: on client/HTTP error

        Returns:
            Dict: JSON body
        """
        try:
            if not tags_labels:
                tags_labels = []
            if not runtime_configuration:
                runtime_configuration = {}
            data = {
                "playbook_requested": playbook_requested,
                "tags_labels": tags_labels,
            }
            # send this value only if populated,
            # otherwise the backend would give you 400
            if tlp:
                data["tlp"] = tlp

            if runtime_configuration:
                data["runtime_configuration"] = json.dumps(runtime_configuration)
            # `files` is wanted to be different from the other
            # /api/analyze_file endpoint
            # because the server is using different serializers
            files = {"files": (filename, binary)}
            answer = self.__send_analysis_request(
                data=data, files=files, playbook_mode=True
            )
        except Exception as e:
            raise IntelOwlClientException(e)
        return answer

    def send_observable_analysis_request(
        self,
        observable_name: str,
        tlp: TLPType = "CLEAR",
        analyzers_requested: List[str] = None,
        connectors_requested: List[str] = None,
        runtime_configuration: Dict = None,
        tags_labels: List[str] = None,
        observable_classification: str = None,
    ) -> Dict:
        """Send analysis request for an observable.\n
        Endpoint: ``/api/analyze_observable``

        Args:
            observable_name (str):
                Observable value
            analyzers_requested (List[str], optional):
                List of analyzers to invoke
                Defaults to ``[]`` i.e. all analyzers.
            connectors_requested (List[str], optional):
                List of specific connectors to invoke.
                Defaults to ``[]`` i.e. all connectors.
            tlp (str, optional):
                TLP for the analysis.
                (options: ``CLEAR, GREEN, AMBER, RED``).
            runtime_configuration (Dict, optional):
                Overwrite configuration for analyzers. Defaults to ``{}``.
            tags_labels (List[str], optional):
                List of tag labels to assign (creates non-existing tags)
            observable_classification (str):
                Observable classification, Default to None.
                By default launch analysis with an automatic classification.
                (options: ``url, domain, hash, ip, generic``)

        Raises:
            IntelOwlClientException: on client/HTTP error
            IntelOwlClientException: on wrong observable_classification

        Returns:
            Dict: JSON body
        """
        try:
            if not tlp:
                tlp = "CLEAR"
            if not analyzers_requested:
                analyzers_requested = []
            if not connectors_requested:
                connectors_requested = []
            if not tags_labels:
                tags_labels = []
            if not runtime_configuration:
                runtime_configuration = {}
            if not observable_classification:
                observable_classification = self._get_observable_classification(
                    observable_name
                )
            elif observable_classification not in [
                "generic",
                "hash",
                "ip",
                "domain",
                "url",
            ]:
                raise IntelOwlClientException(
                    "Observable classification only handle"
                    " 'generic', 'hash', 'ip', 'domain' and 'url' "
                )
            data = {
                "observable_name": observable_name,
                "observable_classification": observable_classification,
                "analyzers_requested": analyzers_requested,
                "connectors_requested": connectors_requested,
                "tlp": tlp,
                "tags_labels": tags_labels,
                "runtime_configuration": runtime_configuration,
            }
            answer = self.__send_analysis_request(data=data, files=None)
        except Exception as e:
            raise IntelOwlClientException(e)
        return answer

    def send_observable_analysis_playbook_request(
        self,
        observable_name: str,
        playbook_requested: str,
        tlp: TLPType = "CLEAR",
        runtime_configuration: Dict = None,
        tags_labels: List[str] = None,
        observable_classification: str = None,
    ) -> Dict:
        """Send playbook analysis request for an observable.\n
        Endpoint: ``/api/playbook/analyze_multiple_observables``

        Args:
            observable_name (str):
                Observable value
            playbook_requested str:
            tlp (str, optional):
                TLP for the analysis.
                (options: ``WHITE, GREEN, AMBER, RED``).
            runtime_configuration (Dict, optional):
                Overwrite configuration for analyzers. Defaults to ``{}``.
            tags_labels (List[str], optional):
                List of tag labels to assign (creates non-existing tags)
            observable_classification (str):
                Observable classification, Default to None.
                By default launch analysis with an automatic classification.
                (options: ``url, domain, hash, ip, generic``)

        Raises:
            IntelOwlClientException: on client/HTTP error
            IntelOwlClientException: on wrong observable_classification

        Returns:
            Dict: JSON body
        """
        try:
            if not tags_labels:
                tags_labels = []
            if not runtime_configuration:
                runtime_configuration = {}
            if not observable_classification:
                observable_classification = self._get_observable_classification(
                    observable_name
                )
            elif observable_classification not in [
                "generic",
                "hash",
                "ip",
                "domain",
                "url",
            ]:
                raise IntelOwlClientException(
                    "Observable classification only handle"
                    " 'generic', 'hash', 'ip', 'domain' and 'url' "
                )
            data = {
                "observables": [[observable_classification, observable_name]],
                "playbook_requested": playbook_requested,
                "tags_labels": tags_labels,
                "runtime_configuration": runtime_configuration,
            }
            # send this value only if populated,
            # otherwise the backend would give you 400
            if tlp:
                data["tlp"] = tlp
            answer = self.__send_analysis_request(
                data=data, files=None, playbook_mode=True
            )
        except Exception as e:
            raise IntelOwlClientException(e)
        return answer

    def send_analysis_batch(self, rows: List[Dict]):
        """
        Send multiple analysis requests.
        Can be mix of observable or file analysis requests.

        Used by the pyintelowl CLI.

        Args:
            rows (List[Dict]):
                Each row should be a dictionary with keys,
                `value`, `type`, `check`, `tlp`,
                `analyzers_list`, `connectors_list`, `runtime_config`
                `tags_list`.
        """
        for obj in rows:
            try:
                runtime_config = obj.get("runtime_config", {})
                if runtime_config:
                    with open(runtime_config) as fp:
                        runtime_config = json.load(fp)

                analyzers_list = obj.get("analyzers_list", [])
                connectors_list = obj.get("connectors_list", [])
                if isinstance(analyzers_list, str):
                    analyzers_list = analyzers_list.split(",")
                if isinstance(connectors_list, str):
                    connectors_list = connectors_list.split(",")

                self._new_analysis_cli(
                    obj["value"],
                    obj["type"],
                    obj.get("check", None),
                    obj.get("tlp", "WHITE"),
                    analyzers_list,
                    connectors_list,
                    runtime_config,
                    obj.get("tags_list", []),
                    obj.get("should_poll", False),
                )
            except IntelOwlClientException as e:
                self.logger.fatal(str(e))

    def __send_analysis_request(self, data=None, files=None, playbook_mode=False):
        """
        Internal use only.
        """
        response = None
        answer = {}
        if files is None:
            url = self.instance + "/api/analyze_observable"
            if playbook_mode:
                url = self.instance + "/api/playbook/analyze_multiple_observables"
            args = {"json": data}
        else:
            url = self.instance + "/api/analyze_file"
            if playbook_mode:
                url = self.instance + "/api/playbook/analyze_multiple_files"
            args = {"data": data, "files": files}
        try:
            response = self.session.post(url, **args)
            self.logger.debug(
                msg={
                    "url": response.url,
                    "code": response.status_code,
                    "request": response.request.headers,
                    "headers": response.headers,
                    "body": response.json(),
                }
            )
            answer = response.json()
            if playbook_mode:
                # right now, we are only supporting single input result
                answers = answer.get("results", [])
                if answers:
                    answer = answers[0]

            warnings = answer.get("warnings", [])
            errors = answer.get("errors", {})
            if self.cli:
                info_log = f"""New Job running..
                    ID: {answer.get('job_id')} | 
                    Status: [u blue]{answer.get('status')}[/].
                    Got {len(warnings)} warnings:
                    [i yellow]{warnings if warnings else None}[/]
                    Got {len(errors)} errors:
                    [i red]{errors if errors else None}[/]
                """
            else:
                info_log = (
                    f"New Job running.. ID: {answer.get('job_id')} "
                    f"| Status: {answer.get('status')}."
                    f" Got {len(warnings)} warnings:"
                    f" {warnings if warnings else None}"
                    f" Got {len(errors)} errors:"
                    f" {errors if errors else None}"
                )
            self.logger.info(info_log)
            response.raise_for_status()
        except Exception as e:
            raise IntelOwlClientException(e, response=response)
        return answer

    def create_tag(self, label: str, color: str):
        """Creates new tag by sending a POST Request
        Endpoint: ``/api/tags``

        Args:
            label ([str]): [Label of the tag to be created]
            color ([str]): [Color of the tag to be created]
        """
        url = self.instance + "/api/tags"
        data = {"label": label, "color": color}
        response = self.__make_request("POST", url=url, data=data)
        return response.json()

    def edit_tag(self, tag_id: Union[int, str], label: str, color: str):
        """Edits existing tag by sending PUT request
        Endpoint: ``api/tags``

        Args:
            id ([int]): [Id of the existing tag]
            label ([str]): [Label of the tag to be created]
            color ([str]): [Color of the tag to be created]
        """
        url = self.instance + "/api/tags/" + str(tag_id)
        data = {"label": label, "color": color}
        response = self.__make_request("PUT", url=url, data=data)
        return response.json()

    def get_all_tags(self) -> List[Dict[str, str]]:
        """
        Fetch list of all tags.\n
        Endpoint: ``/api/tags``

        Raises:
            IntelOwlClientException: on client/HTTP error

        Returns:
            List[Dict[str, str]]: List of tags
        """
        url = self.instance + "/api/tags"
        response = self.__make_request("GET", url=url)
        return response.json()

    def get_all_jobs(self) -> List[Dict[str, Any]]:
        """
        Fetch list of all jobs.\n
        Endpoint: ``/api/jobs``

        Raises:
            IntelOwlClientException: on client/HTTP error

        Returns:
            Dict: Dict with 3 keys: "count", "total_pages", "results"
        """
        url = self.instance + "/api/jobs"
        response = self.__make_request("GET", url=url)
        return response.json()

    def get_tag_by_id(self, tag_id: Union[int, str]) -> Dict[str, str]:
        """Fetch tag info by ID.\n
        Endpoint: ``/api/tag/{tag_id}``

        Args:
            tag_id (Union[int, str]): Tag ID

        Raises:
            IntelOwlClientException: on client/HTTP error

        Returns:
            Dict[str, str]: Dict with 3 keys: `id`, `label` and `color`.
        """

        url = self.instance + "/api/tags/" + str(tag_id)
        response = self.__make_request("GET", url=url)
        return response.json()

    def get_job_by_id(self, job_id: Union[int, str]) -> Dict[str, Any]:
        """Fetch job info by ID.
        Endpoint: ``/api/jobs/{job_id}``

        Args:
            job_id (Union[int, str]): Job ID

        Raises:
            IntelOwlClientException: on client/HTTP error

        Returns:
            Dict[str, Any]: JSON body.
        """
        url = self.instance + "/api/jobs/" + str(job_id)
        response = self.__make_request("GET", url=url)
        return response.json()

    @staticmethod
    def get_md5(
        to_hash: AnyStr,
        type_="observable",
    ) -> str:
        """Returns md5sum of given observable or file object.

        Args:
            to_hash (AnyStr):
                either an observable string, file contents as bytes or path to a file
            type_ (Union["observable", "binary", "file"], optional):
                `observable`, `binary`, `file`. Defaults to "observable".

        Raises:
            IntelOwlClientException: on client/HTTP error

        Returns:
            str: md5sum
        """
        md5 = ""
        if type_ == "observable":
            md5 = hashlib.md5(str(to_hash).lower().encode("utf-8")).hexdigest()
        elif type_ == "binary":
            md5 = hashlib.md5(to_hash).hexdigest()
        elif type_ == "file":
            path = pathlib.Path(to_hash)
            if not path.exists():
                raise IntelOwlClientException(f"{to_hash} does not exists")
            binary = path.read_bytes()
            md5 = hashlib.md5(binary).hexdigest()
        return md5

    def _new_analysis_cli(
        self,
        obj: str,
        type_: str,
        check,
        tlp: TLPType = None,
        analyzers_list: List[str] = None,
        connectors_list: List[str] = None,
        runtime_configuration: Dict = None,
        tags_labels: List[str] = None,
        should_poll: bool = False,
        minutes_ago: int = None,
    ) -> None:
        """
        For internal use by the pyintelowl CLI.
        """
        if not analyzers_list:
            analyzers_list = []
        if not connectors_list:
            connectors_list = []
        if not runtime_configuration:
            runtime_configuration = {}
        if not tags_labels:
            tags_labels = []
        self.logger.info(
            f"""Requesting analysis..
            {type_}: [blue]{obj}[/]
            analyzers: [i green]{analyzers_list if analyzers_list else 'none'}[/]
            connectors: [i green]{connectors_list if connectors_list else 'none'}[/]
            tags: [i green]{tags_labels}[/]
            """
        )
        # 1st step: ask analysis availability
        if check != "force-new":
            md5 = self.get_md5(obj, type_=type_)

            resp = self.ask_analysis_availability(
                md5,
                analyzers_list,
                True if check == "reported" else False,
                minutes_ago,
            )
            status, job_id = resp.get("status", None), resp.get("job_id", None)
            if status != "not_available":
                self.logger.info(
                    f"""Found existing analysis!
                Job: #{job_id}
                status: [u blue]{status}[/]

                [i]Hint: use [#854442]--check force-new[/] to perform new scan anyway[/]
                    """
                )
                return
        # 2nd step: send new analysis request
        if type_ == "observable":
            resp2 = self.send_observable_analysis_request(
                observable_name=obj,
                tlp=tlp,
                analyzers_requested=analyzers_list,
                connectors_requested=connectors_list,
                runtime_configuration=runtime_configuration,
                tags_labels=tags_labels,
            )
        else:
            path = pathlib.Path(obj)
            resp2 = self.send_file_analysis_request(
                filename=path.name,
                binary=path.read_bytes(),
                tlp=tlp,
                analyzers_requested=analyzers_list,
                connectors_requested=connectors_list,
                runtime_configuration=runtime_configuration,
                tags_labels=tags_labels,
            )
        # 3rd step: poll for result
        if should_poll:
            if resp2["status"] != "accepted":
                self.logger.fatal("Can't poll a failed job")
            # import poll function
            from .cli._jobs_utils import _poll_for_job_cli

            job_id = resp2["job_id"]
            _ = _poll_for_job_cli(self, job_id)
            self.logger.info(
                f"""
        Polling finished.
        Execute [i blue]pyintelowl jobs view {job_id}[/] to view the result
                """
            )

    def _new_analysis_playbook_cli(
        self,
        obj: str,
        type_: str,
        playbook: str,
        tlp: TLPType = None,
        runtime_configuration: Dict = None,
        tags_labels: List[str] = None,
        should_poll: bool = False,
    ) -> None:
        """
        For internal use by the pyintelowl CLI.
        """
        if not runtime_configuration:
            runtime_configuration = {}
        if not tags_labels:
            tags_labels = []

        self.logger.info(
            f"""Requesting analysis..
            {type_}: [blue]{obj}[/]
            playbook: [i green]{playbook}[/]
            tags: [i green]{tags_labels}[/]
            """
        )

        # 1st step, make request
        if type_ == "observable":
            resp = self.send_observable_analysis_playbook_request(
                observable_name=obj,
                playbook_requested=playbook,
                tlp=tlp,
                runtime_configuration=runtime_configuration,
                tags_labels=tags_labels,
            )
        else:
            path = pathlib.Path(obj)
            resp = self.send_file_analysis_playbook_request(
                filename=path.name,
                binary=path.read_bytes(),
                playbook_requested=playbook,
                tlp=tlp,
                runtime_configuration=runtime_configuration,
                tags_labels=tags_labels,
            )

        # 2nd step: poll for result
        if should_poll:
            if resp.get("status", "") != "accepted":
                self.logger.fatal("Can't poll a failed job")
            # import poll function
            from .cli._jobs_utils import _poll_for_job_cli

            job_id = resp.get("job_id", 0)
            _ = _poll_for_job_cli(self, job_id)
            self.logger.info(
                f"""
                    Polling finished.
                    Execute [i blue]pyintelowl jobs view {job_id}[/] to view the result
                """
            )

    def _get_observable_classification(self, value: str) -> str:
        """Returns observable classification for the given value.\n
        Only following types are supported:
        ip, domain, url, hash (md5, sha1, sha256), generic (if no match)

        Args:
            value (str):
                observable value

        Raises:
            IntelOwlClientException:
                if value type is not recognized

        Returns:
            str: one of `ip`, `url`, `domain`, `hash` or 'generic'.
        """
        try:
            ipaddress.ip_address(value)
        except ValueError:
            if re.match(
                r"^(?:htt|ft|tc)ps?://[a-z\d-]{1,63}(?:\.[a-z\d-]{1,63})+"
                r"(?:/[a-z\d-]{1,63})*(?:\.\w+)?",
                value,
            ):
                classification = "url"
            elif re.match(r"^(\.)?[a-z\d-]{1,63}(\.[a-z\d-]{1,63})+$", value):
                classification = "domain"
            elif (
                re.match(r"^[a-f\d]{32}$", value)
                or re.match(r"^[a-f\d]{40}$", value)
                or re.match(r"^[a-f\d]{64}$", value)
                or re.match(r"^[A-F\d]{32}$", value)
                or re.match(r"^[A-F\d]{40}$", value)
                or re.match(r"^[A-F\d]{64}$", value)
            ):
                classification = "hash"
            else:
                classification = "generic"
                self.logger.warning(
                    "Couldn't detect observable classification, setting as 'generic'..."
                )
        else:
            # its a simple IP
            classification = "ip"

        return classification

    def download_sample(self, job_id: int) -> bytes:
        """
        Download file sample from job.\n
        Method: GET
        Endpoint: ``/api/jobs/{job_id}/download_sample``

        Args:
            job_id (int):
                id of job to download sample from

        Raises:
            IntelOwlClientException: on client/HTTP error

        Returns:
            Bytes: Raw file data.
        """

        url = self.instance + f"/api/jobs/{job_id}/download_sample"
        response = self.__make_request("GET", url=url)
        return response.content

    def kill_running_job(self, job_id: int) -> bool:
        """Send kill_running_job request.\n
        Method: PATCH
        Endpoint: ``/api/jobs/{job_id}/kill``

        Args:
            job_id (int):
                id of job to kill

        Raises:
            IntelOwlClientException: on client/HTTP error

        Returns:
            Bool: killed or not
        """

        url = self.instance + f"/api/jobs/{job_id}/kill"
        response = self.__make_request("PATCH", url=url)
        killed = response.status_code == 204
        return killed

    def delete_job_by_id(self, job_id: int) -> bool:
        """Send delete job request.\n
        Method: DELETE
        Endpoint: ``/api/jobs/{job_id}``

        Args:
            job_id (int):
                id of job to kill

        Raises:
            IntelOwlClientException: on client/HTTP error

        Returns:
            Bool: deleted or not
        """
        url = self.instance + "/api/jobs/" + str(job_id)
        response = self.__make_request("DELETE", url=url)
        deleted = response.status_code == 204
        return deleted

    def delete_tag_by_id(self, tag_id: int) -> bool:
        """Send delete tag request.\n
        Method: DELETE
        Endpoint: ``/api/tags/{tag_id}``

        Args:
            tag_id (int):
                id of tag to delete

        Raises:
            IntelOwlClientException: on client/HTTP error

        Returns:
            Bool: deleted or not
        """

        url = self.instance + "/api/tags/" + str(tag_id)
        response = self.__make_request("DELETE", url=url)
        deleted = response.status_code == 204
        return deleted

    def __run_plugin_action(
        self, job_id: int, plugin_type: str, plugin_name: str, plugin_action: str
    ) -> bool:
        """Internal method for kill/retry for analyzer/connector"""
        response = None
        url = (
            self.instance
            + f"/api/jobs/{job_id}/{plugin_type}/{plugin_name}/{plugin_action}"
        )
        response = self.__make_request("PATCH", url=url)
        success = response.status_code == 204
        return success

    def kill_analyzer(self, job_id: int, analyzer_name: str) -> bool:
        """Send kill running/pending analyzer request.\n
        Method: PATCH
        Endpoint: ``/api/jobs/{job_id}/analyzer/{analyzer_name}/kill``

        Args:
            job_id (int):
                id of job
            analyzer_name (str):
                name of analyzer to kill

        Raises:
            IntelOwlClientException: on client/HTTP error

        Returns:
            Bool: killed or not
        """

        killed = self.__run_plugin_action(
            job_id=job_id,
            plugin_name=analyzer_name,
            plugin_type="analyzer",
            plugin_action="kill",
        )
        return killed

    def kill_connector(self, job_id: int, connector_name: str) -> bool:
        """Send kill running/pending connector request.\n
        Method: PATCH
        Endpoint: ``/api/jobs/{job_id}/connector/{connector_name}/kill``

        Args:
            job_id (int):
                id of job
            connector_name (str):
                name of connector to kill

        Raises:
            IntelOwlClientException: on client/HTTP error

        Returns:
            Bool: killed or not
        """

        killed = self.__run_plugin_action(
            job_id=job_id,
            plugin_name=connector_name,
            plugin_type="connector",
            plugin_action="kill",
        )
        return killed

    def retry_analyzer(self, job_id: int, analyzer_name: str) -> bool:
        """Send retry failed/killed analyzer request.\n
        Method: PATCH
        Endpoint: ``/api/jobs/{job_id}/analyzer/{analyzer_name}/retry``

        Args:
            job_id (int):
                id of job
            analyzer_name (str):
                name of analyzer to retry

        Raises:
            IntelOwlClientException: on client/HTTP error

        Returns:
            Bool: success or not
        """

        success = self.__run_plugin_action(
            job_id=job_id,
            plugin_name=analyzer_name,
            plugin_type="analyzer",
            plugin_action="retry",
        )
        return success

    def retry_connector(self, job_id: int, connector_name: str) -> bool:
        """Send retry failed/killed connector request.\n
        Method: PATCH
        Endpoint: ``/api/jobs/{job_id}/connector/{connector_name}/retry``

        Args:
            job_id (int):
                id of job
            connector_name (str):
                name of connector to retry

        Raises:
            IntelOwlClientException: on client/HTTP error

        Returns:
            Bool: success or not
        """

        success = self.__run_plugin_action(
            job_id=job_id,
            plugin_name=connector_name,
            plugin_type="connector",
            plugin_action="retry",
        )
        return success

    def analyzer_healthcheck(self, analyzer_name: str) -> Optional[bool]:
        """Send analyzer(docker-based) health check request.\n
        Method: GET
        Endpoint: ``/api/analyzer/{analyzer_name}/healthcheck``

        Args:
            analyzer_name (str):
                name of analyzer

        Raises:
            IntelOwlClientException: on client/HTTP error

        Returns:
            Bool: success or not
        """

        url = self.instance + f"/api/analyzer/{analyzer_name}/healthcheck"
        response = self.__make_request("GET", url=url)
        return response.json().get("status", None)

    def connector_healthcheck(self, connector_name: str) -> Optional[bool]:
        """Send connector health check request.\n
        Method: GET
        Endpoint: ``/api/connector/{connector_name}/healthcheck``

        Args:
            connector_name (str):
                name of connector

        Raises:
            IntelOwlClientException: on client/HTTP error

        Returns:
            Bool: success or not
        """
        url = self.instance + f"/api/connector/{connector_name}/healthcheck"
        response = self.__make_request("GET", url=url)
        return response.json().get("status", None)

session: requests.Session property

Internal use only.

__make_request(method='GET', *args, **kwargs)

For internal use only.

Source code in docs/Submodules/pyintelowl/pyintelowl/pyintelowl.py
def __make_request(
    self,
    method: Literal["GET", "POST", "PUT", "PATCH", "DELETE"] = "GET",
    *args,
    **kwargs,
) -> requests.Response:
    """
    For internal use only.
    """
    response: requests.Response = None
    requests_function_map: Dict[str, Callable] = {
        "GET": self.session.get,
        "POST": self.session.post,
        "PUT": self.session.put,
        "PATCH": self.session.patch,
        "DELETE": self.session.delete,
    }
    func = requests_function_map.get(method, None)
    if not func:
        raise RuntimeError(f"Unsupported method name: {method}")

    try:
        response = func(*args, **kwargs)
        self.logger.debug(
            msg=(response.url, response.status_code, response.content)
        )
        response.raise_for_status()
    except Exception as e:
        raise IntelOwlClientException(e, response=response)

    return response

__run_plugin_action(job_id, plugin_type, plugin_name, plugin_action)

Internal method for kill/retry for analyzer/connector

Source code in docs/Submodules/pyintelowl/pyintelowl/pyintelowl.py
def __run_plugin_action(
    self, job_id: int, plugin_type: str, plugin_name: str, plugin_action: str
) -> bool:
    """Internal method for kill/retry for analyzer/connector"""
    response = None
    url = (
        self.instance
        + f"/api/jobs/{job_id}/{plugin_type}/{plugin_name}/{plugin_action}"
    )
    response = self.__make_request("PATCH", url=url)
    success = response.status_code == 204
    return success

__send_analysis_request(data=None, files=None, playbook_mode=False)

Internal use only.

Source code in docs/Submodules/pyintelowl/pyintelowl/pyintelowl.py
def __send_analysis_request(self, data=None, files=None, playbook_mode=False):
    """
    Internal use only.
    """
    response = None
    answer = {}
    if files is None:
        url = self.instance + "/api/analyze_observable"
        if playbook_mode:
            url = self.instance + "/api/playbook/analyze_multiple_observables"
        args = {"json": data}
    else:
        url = self.instance + "/api/analyze_file"
        if playbook_mode:
            url = self.instance + "/api/playbook/analyze_multiple_files"
        args = {"data": data, "files": files}
    try:
        response = self.session.post(url, **args)
        self.logger.debug(
            msg={
                "url": response.url,
                "code": response.status_code,
                "request": response.request.headers,
                "headers": response.headers,
                "body": response.json(),
            }
        )
        answer = response.json()
        if playbook_mode:
            # right now, we are only supporting single input result
            answers = answer.get("results", [])
            if answers:
                answer = answers[0]

        warnings = answer.get("warnings", [])
        errors = answer.get("errors", {})
        if self.cli:
            info_log = f"""New Job running..
                ID: {answer.get('job_id')} | 
                Status: [u blue]{answer.get('status')}[/].
                Got {len(warnings)} warnings:
                [i yellow]{warnings if warnings else None}[/]
                Got {len(errors)} errors:
                [i red]{errors if errors else None}[/]
            """
        else:
            info_log = (
                f"New Job running.. ID: {answer.get('job_id')} "
                f"| Status: {answer.get('status')}."
                f" Got {len(warnings)} warnings:"
                f" {warnings if warnings else None}"
                f" Got {len(errors)} errors:"
                f" {errors if errors else None}"
            )
        self.logger.info(info_log)
        response.raise_for_status()
    except Exception as e:
        raise IntelOwlClientException(e, response=response)
    return answer

analyzer_healthcheck(analyzer_name)

Send analyzer(docker-based) health check request.

Method: GET Endpoint: /api/analyzer/{analyzer_name}/healthcheck

Parameters:

Name Type Description Default
analyzer_name str

name of analyzer

required

Raises:

Type Description
IntelOwlClientException

on client/HTTP error

Returns:

Name Type Description
Bool Optional[bool]

success or not

Source code in docs/Submodules/pyintelowl/pyintelowl/pyintelowl.py
def analyzer_healthcheck(self, analyzer_name: str) -> Optional[bool]:
    """Send analyzer(docker-based) health check request.\n
    Method: GET
    Endpoint: ``/api/analyzer/{analyzer_name}/healthcheck``

    Args:
        analyzer_name (str):
            name of analyzer

    Raises:
        IntelOwlClientException: on client/HTTP error

    Returns:
        Bool: success or not
    """

    url = self.instance + f"/api/analyzer/{analyzer_name}/healthcheck"
    response = self.__make_request("GET", url=url)
    return response.json().get("status", None)

ask_analysis_availability(md5, analyzers=None, check_reported_analysis_too=False, minutes_ago=None)

Search for already available analysis.

Endpoint: /api/ask_analysis_availability

Parameters:

Name Type Description Default
md5 str

md5sum of the observable or file

required
analyzers List[str]
None
check_reported_analysis_too bool
False
minutes_ago int
None

Raises:

Type Description
IntelOwlClientException

on client/HTTP error

Returns:

Name Type Description
Dict Dict

JSON body

Source code in docs/Submodules/pyintelowl/pyintelowl/pyintelowl.py
def ask_analysis_availability(
    self,
    md5: str,
    analyzers: List[str] = None,
    check_reported_analysis_too: bool = False,
    minutes_ago: int = None,
) -> Dict:
    """Search for already available analysis.\n
    Endpoint: ``/api/ask_analysis_availability``

    Args:
        md5 (str): md5sum of the observable or file
        analyzers (List[str], optional):
        list of analyzers to trigger.
        Defaults to `None` meaning automatically select all configured analyzers.
        check_reported_analysis_too (bool, optional):
        Check against all existing jobs. Defaults to ``False``.
        minutes_ago (int, optional):
        number of minutes to check back for analysis.
        Default is None so the check does not have any time limits.

    Raises:
        IntelOwlClientException: on client/HTTP error

    Returns:
        Dict: JSON body
    """
    if not analyzers:
        analyzers = []
    data = {"md5": md5, "analyzers": analyzers}
    if not check_reported_analysis_too:
        data["running_only"] = True
    if minutes_ago:
        data["minutes_ago"] = int(minutes_ago)
    url = self.instance + "/api/ask_analysis_availability"
    response = self.__make_request("POST", url=url, data=data)
    answer = response.json()
    status, job_id = answer.get("status", None), answer.get("job_id", None)
    # check sanity cases
    if not status:
        raise IntelOwlClientException(
            "API ask_analysis_availability gave result without status ?"
            f" Response: {answer}"
        )
    if status != "not_available" and not job_id:
        raise IntelOwlClientException(
            "API ask_analysis_availability gave result without job_id ?"
            f" Response: {answer}"
        )
    return answer

connector_healthcheck(connector_name)

Send connector health check request.

Method: GET Endpoint: /api/connector/{connector_name}/healthcheck

Parameters:

Name Type Description Default
connector_name str

name of connector

required

Raises:

Type Description
IntelOwlClientException

on client/HTTP error

Returns:

Name Type Description
Bool Optional[bool]

success or not

Source code in docs/Submodules/pyintelowl/pyintelowl/pyintelowl.py
def connector_healthcheck(self, connector_name: str) -> Optional[bool]:
    """Send connector health check request.\n
    Method: GET
    Endpoint: ``/api/connector/{connector_name}/healthcheck``

    Args:
        connector_name (str):
            name of connector

    Raises:
        IntelOwlClientException: on client/HTTP error

    Returns:
        Bool: success or not
    """
    url = self.instance + f"/api/connector/{connector_name}/healthcheck"
    response = self.__make_request("GET", url=url)
    return response.json().get("status", None)

create_tag(label, color)

Creates new tag by sending a POST Request Endpoint: /api/tags

Parameters:

Name Type Description Default
label [str]

[Label of the tag to be created]

required
color [str]

[Color of the tag to be created]

required
Source code in docs/Submodules/pyintelowl/pyintelowl/pyintelowl.py
def create_tag(self, label: str, color: str):
    """Creates new tag by sending a POST Request
    Endpoint: ``/api/tags``

    Args:
        label ([str]): [Label of the tag to be created]
        color ([str]): [Color of the tag to be created]
    """
    url = self.instance + "/api/tags"
    data = {"label": label, "color": color}
    response = self.__make_request("POST", url=url, data=data)
    return response.json()

delete_job_by_id(job_id)

Send delete job request.

Method: DELETE Endpoint: /api/jobs/{job_id}

Parameters:

Name Type Description Default
job_id int

id of job to kill

required

Raises:

Type Description
IntelOwlClientException

on client/HTTP error

Returns:

Name Type Description
Bool bool

deleted or not

Source code in docs/Submodules/pyintelowl/pyintelowl/pyintelowl.py
def delete_job_by_id(self, job_id: int) -> bool:
    """Send delete job request.\n
    Method: DELETE
    Endpoint: ``/api/jobs/{job_id}``

    Args:
        job_id (int):
            id of job to kill

    Raises:
        IntelOwlClientException: on client/HTTP error

    Returns:
        Bool: deleted or not
    """
    url = self.instance + "/api/jobs/" + str(job_id)
    response = self.__make_request("DELETE", url=url)
    deleted = response.status_code == 204
    return deleted

delete_tag_by_id(tag_id)

Send delete tag request.

Method: DELETE Endpoint: /api/tags/{tag_id}

Parameters:

Name Type Description Default
tag_id int

id of tag to delete

required

Raises:

Type Description
IntelOwlClientException

on client/HTTP error

Returns:

Name Type Description
Bool bool

deleted or not

Source code in docs/Submodules/pyintelowl/pyintelowl/pyintelowl.py
def delete_tag_by_id(self, tag_id: int) -> bool:
    """Send delete tag request.\n
    Method: DELETE
    Endpoint: ``/api/tags/{tag_id}``

    Args:
        tag_id (int):
            id of tag to delete

    Raises:
        IntelOwlClientException: on client/HTTP error

    Returns:
        Bool: deleted or not
    """

    url = self.instance + "/api/tags/" + str(tag_id)
    response = self.__make_request("DELETE", url=url)
    deleted = response.status_code == 204
    return deleted

download_sample(job_id)

Download file sample from job.

Method: GET Endpoint: /api/jobs/{job_id}/download_sample

Parameters:

Name Type Description Default
job_id int

id of job to download sample from

required

Raises:

Type Description
IntelOwlClientException

on client/HTTP error

Returns:

Name Type Description
Bytes bytes

Raw file data.

Source code in docs/Submodules/pyintelowl/pyintelowl/pyintelowl.py
def download_sample(self, job_id: int) -> bytes:
    """
    Download file sample from job.\n
    Method: GET
    Endpoint: ``/api/jobs/{job_id}/download_sample``

    Args:
        job_id (int):
            id of job to download sample from

    Raises:
        IntelOwlClientException: on client/HTTP error

    Returns:
        Bytes: Raw file data.
    """

    url = self.instance + f"/api/jobs/{job_id}/download_sample"
    response = self.__make_request("GET", url=url)
    return response.content

edit_tag(tag_id, label, color)

Edits existing tag by sending PUT request Endpoint: api/tags

Parameters:

Name Type Description Default
id [int]

[Id of the existing tag]

required
label [str]

[Label of the tag to be created]

required
color [str]

[Color of the tag to be created]

required
Source code in docs/Submodules/pyintelowl/pyintelowl/pyintelowl.py
def edit_tag(self, tag_id: Union[int, str], label: str, color: str):
    """Edits existing tag by sending PUT request
    Endpoint: ``api/tags``

    Args:
        id ([int]): [Id of the existing tag]
        label ([str]): [Label of the tag to be created]
        color ([str]): [Color of the tag to be created]
    """
    url = self.instance + "/api/tags/" + str(tag_id)
    data = {"label": label, "color": color}
    response = self.__make_request("PUT", url=url, data=data)
    return response.json()

get_all_jobs()

Fetch list of all jobs.

Endpoint: /api/jobs

Raises:

Type Description
IntelOwlClientException

on client/HTTP error

Returns:

Name Type Description
Dict List[Dict[str, Any]]

Dict with 3 keys: "count", "total_pages", "results"

Source code in docs/Submodules/pyintelowl/pyintelowl/pyintelowl.py
def get_all_jobs(self) -> List[Dict[str, Any]]:
    """
    Fetch list of all jobs.\n
    Endpoint: ``/api/jobs``

    Raises:
        IntelOwlClientException: on client/HTTP error

    Returns:
        Dict: Dict with 3 keys: "count", "total_pages", "results"
    """
    url = self.instance + "/api/jobs"
    response = self.__make_request("GET", url=url)
    return response.json()

get_all_tags()

Fetch list of all tags.

Endpoint: /api/tags

Raises:

Type Description
IntelOwlClientException

on client/HTTP error

Returns:

Type Description
List[Dict[str, str]]

List[Dict[str, str]]: List of tags

Source code in docs/Submodules/pyintelowl/pyintelowl/pyintelowl.py
def get_all_tags(self) -> List[Dict[str, str]]:
    """
    Fetch list of all tags.\n
    Endpoint: ``/api/tags``

    Raises:
        IntelOwlClientException: on client/HTTP error

    Returns:
        List[Dict[str, str]]: List of tags
    """
    url = self.instance + "/api/tags"
    response = self.__make_request("GET", url=url)
    return response.json()

get_job_by_id(job_id)

Fetch job info by ID. Endpoint: /api/jobs/{job_id}

Parameters:

Name Type Description Default
job_id Union[int, str]

Job ID

required

Raises:

Type Description
IntelOwlClientException

on client/HTTP error

Returns:

Type Description
Dict[str, Any]

Dict[str, Any]: JSON body.

Source code in docs/Submodules/pyintelowl/pyintelowl/pyintelowl.py
def get_job_by_id(self, job_id: Union[int, str]) -> Dict[str, Any]:
    """Fetch job info by ID.
    Endpoint: ``/api/jobs/{job_id}``

    Args:
        job_id (Union[int, str]): Job ID

    Raises:
        IntelOwlClientException: on client/HTTP error

    Returns:
        Dict[str, Any]: JSON body.
    """
    url = self.instance + "/api/jobs/" + str(job_id)
    response = self.__make_request("GET", url=url)
    return response.json()

get_md5(to_hash, type_='observable') staticmethod

Returns md5sum of given observable or file object.

Parameters:

Name Type Description Default
to_hash AnyStr

either an observable string, file contents as bytes or path to a file

required
type_ Union[observable, binary, file]

observable, binary, file. Defaults to "observable".

'observable'

Raises:

Type Description
IntelOwlClientException

on client/HTTP error

Returns:

Name Type Description
str str

md5sum

Source code in docs/Submodules/pyintelowl/pyintelowl/pyintelowl.py
@staticmethod
def get_md5(
    to_hash: AnyStr,
    type_="observable",
) -> str:
    """Returns md5sum of given observable or file object.

    Args:
        to_hash (AnyStr):
            either an observable string, file contents as bytes or path to a file
        type_ (Union["observable", "binary", "file"], optional):
            `observable`, `binary`, `file`. Defaults to "observable".

    Raises:
        IntelOwlClientException: on client/HTTP error

    Returns:
        str: md5sum
    """
    md5 = ""
    if type_ == "observable":
        md5 = hashlib.md5(str(to_hash).lower().encode("utf-8")).hexdigest()
    elif type_ == "binary":
        md5 = hashlib.md5(to_hash).hexdigest()
    elif type_ == "file":
        path = pathlib.Path(to_hash)
        if not path.exists():
            raise IntelOwlClientException(f"{to_hash} does not exists")
        binary = path.read_bytes()
        md5 = hashlib.md5(binary).hexdigest()
    return md5

get_tag_by_id(tag_id)

Fetch tag info by ID.

Endpoint: /api/tag/{tag_id}

Parameters:

Name Type Description Default
tag_id Union[int, str]

Tag ID

required

Raises:

Type Description
IntelOwlClientException

on client/HTTP error

Returns:

Type Description
Dict[str, str]

Dict[str, str]: Dict with 3 keys: id, label and color.

Source code in docs/Submodules/pyintelowl/pyintelowl/pyintelowl.py
def get_tag_by_id(self, tag_id: Union[int, str]) -> Dict[str, str]:
    """Fetch tag info by ID.\n
    Endpoint: ``/api/tag/{tag_id}``

    Args:
        tag_id (Union[int, str]): Tag ID

    Raises:
        IntelOwlClientException: on client/HTTP error

    Returns:
        Dict[str, str]: Dict with 3 keys: `id`, `label` and `color`.
    """

    url = self.instance + "/api/tags/" + str(tag_id)
    response = self.__make_request("GET", url=url)
    return response.json()

kill_analyzer(job_id, analyzer_name)

Send kill running/pending analyzer request.

Method: PATCH Endpoint: /api/jobs/{job_id}/analyzer/{analyzer_name}/kill

Parameters:

Name Type Description Default
job_id int

id of job

required
analyzer_name str

name of analyzer to kill

required

Raises:

Type Description
IntelOwlClientException

on client/HTTP error

Returns:

Name Type Description
Bool bool

killed or not

Source code in docs/Submodules/pyintelowl/pyintelowl/pyintelowl.py
def kill_analyzer(self, job_id: int, analyzer_name: str) -> bool:
    """Send kill running/pending analyzer request.\n
    Method: PATCH
    Endpoint: ``/api/jobs/{job_id}/analyzer/{analyzer_name}/kill``

    Args:
        job_id (int):
            id of job
        analyzer_name (str):
            name of analyzer to kill

    Raises:
        IntelOwlClientException: on client/HTTP error

    Returns:
        Bool: killed or not
    """

    killed = self.__run_plugin_action(
        job_id=job_id,
        plugin_name=analyzer_name,
        plugin_type="analyzer",
        plugin_action="kill",
    )
    return killed

kill_connector(job_id, connector_name)

Send kill running/pending connector request.

Method: PATCH Endpoint: /api/jobs/{job_id}/connector/{connector_name}/kill

Parameters:

Name Type Description Default
job_id int

id of job

required
connector_name str

name of connector to kill

required

Raises:

Type Description
IntelOwlClientException

on client/HTTP error

Returns:

Name Type Description
Bool bool

killed or not

Source code in docs/Submodules/pyintelowl/pyintelowl/pyintelowl.py
def kill_connector(self, job_id: int, connector_name: str) -> bool:
    """Send kill running/pending connector request.\n
    Method: PATCH
    Endpoint: ``/api/jobs/{job_id}/connector/{connector_name}/kill``

    Args:
        job_id (int):
            id of job
        connector_name (str):
            name of connector to kill

    Raises:
        IntelOwlClientException: on client/HTTP error

    Returns:
        Bool: killed or not
    """

    killed = self.__run_plugin_action(
        job_id=job_id,
        plugin_name=connector_name,
        plugin_type="connector",
        plugin_action="kill",
    )
    return killed

kill_running_job(job_id)

Send kill_running_job request.

Method: PATCH Endpoint: /api/jobs/{job_id}/kill

Parameters:

Name Type Description Default
job_id int

id of job to kill

required

Raises:

Type Description
IntelOwlClientException

on client/HTTP error

Returns:

Name Type Description
Bool bool

killed or not

Source code in docs/Submodules/pyintelowl/pyintelowl/pyintelowl.py
def kill_running_job(self, job_id: int) -> bool:
    """Send kill_running_job request.\n
    Method: PATCH
    Endpoint: ``/api/jobs/{job_id}/kill``

    Args:
        job_id (int):
            id of job to kill

    Raises:
        IntelOwlClientException: on client/HTTP error

    Returns:
        Bool: killed or not
    """

    url = self.instance + f"/api/jobs/{job_id}/kill"
    response = self.__make_request("PATCH", url=url)
    killed = response.status_code == 204
    return killed

retry_analyzer(job_id, analyzer_name)

Send retry failed/killed analyzer request.

Method: PATCH Endpoint: /api/jobs/{job_id}/analyzer/{analyzer_name}/retry

Parameters:

Name Type Description Default
job_id int

id of job

required
analyzer_name str

name of analyzer to retry

required

Raises:

Type Description
IntelOwlClientException

on client/HTTP error

Returns:

Name Type Description
Bool bool

success or not

Source code in docs/Submodules/pyintelowl/pyintelowl/pyintelowl.py
def retry_analyzer(self, job_id: int, analyzer_name: str) -> bool:
    """Send retry failed/killed analyzer request.\n
    Method: PATCH
    Endpoint: ``/api/jobs/{job_id}/analyzer/{analyzer_name}/retry``

    Args:
        job_id (int):
            id of job
        analyzer_name (str):
            name of analyzer to retry

    Raises:
        IntelOwlClientException: on client/HTTP error

    Returns:
        Bool: success or not
    """

    success = self.__run_plugin_action(
        job_id=job_id,
        plugin_name=analyzer_name,
        plugin_type="analyzer",
        plugin_action="retry",
    )
    return success

retry_connector(job_id, connector_name)

Send retry failed/killed connector request.

Method: PATCH Endpoint: /api/jobs/{job_id}/connector/{connector_name}/retry

Parameters:

Name Type Description Default
job_id int

id of job

required
connector_name str

name of connector to retry

required

Raises:

Type Description
IntelOwlClientException

on client/HTTP error

Returns:

Name Type Description
Bool bool

success or not

Source code in docs/Submodules/pyintelowl/pyintelowl/pyintelowl.py
def retry_connector(self, job_id: int, connector_name: str) -> bool:
    """Send retry failed/killed connector request.\n
    Method: PATCH
    Endpoint: ``/api/jobs/{job_id}/connector/{connector_name}/retry``

    Args:
        job_id (int):
            id of job
        connector_name (str):
            name of connector to retry

    Raises:
        IntelOwlClientException: on client/HTTP error

    Returns:
        Bool: success or not
    """

    success = self.__run_plugin_action(
        job_id=job_id,
        plugin_name=connector_name,
        plugin_type="connector",
        plugin_action="retry",
    )
    return success

send_analysis_batch(rows)

Send multiple analysis requests. Can be mix of observable or file analysis requests.

Used by the pyintelowl CLI.

Parameters:

Name Type Description Default
rows List[Dict]

Each row should be a dictionary with keys, value, type, check, tlp, analyzers_list, connectors_list, runtime_config tags_list.

required
Source code in docs/Submodules/pyintelowl/pyintelowl/pyintelowl.py
def send_analysis_batch(self, rows: List[Dict]):
    """
    Send multiple analysis requests.
    Can be mix of observable or file analysis requests.

    Used by the pyintelowl CLI.

    Args:
        rows (List[Dict]):
            Each row should be a dictionary with keys,
            `value`, `type`, `check`, `tlp`,
            `analyzers_list`, `connectors_list`, `runtime_config`
            `tags_list`.
    """
    for obj in rows:
        try:
            runtime_config = obj.get("runtime_config", {})
            if runtime_config:
                with open(runtime_config) as fp:
                    runtime_config = json.load(fp)

            analyzers_list = obj.get("analyzers_list", [])
            connectors_list = obj.get("connectors_list", [])
            if isinstance(analyzers_list, str):
                analyzers_list = analyzers_list.split(",")
            if isinstance(connectors_list, str):
                connectors_list = connectors_list.split(",")

            self._new_analysis_cli(
                obj["value"],
                obj["type"],
                obj.get("check", None),
                obj.get("tlp", "WHITE"),
                analyzers_list,
                connectors_list,
                runtime_config,
                obj.get("tags_list", []),
                obj.get("should_poll", False),
            )
        except IntelOwlClientException as e:
            self.logger.fatal(str(e))

send_file_analysis_playbook_request(filename, binary, playbook_requested, tlp='CLEAR', runtime_configuration=None, tags_labels=None)

Send playbook analysis request for a file.

Endpoint: /api/playbook/analyze_multiple_files

Args:

filename (str):
    Filename
binary (bytes):
    File contents as bytes
playbook_requested (str, optional):
tlp (str, optional):
    TLP for the analysis.
    (options: ``WHITE, GREEN, AMBER, RED``).
runtime_configuration (Dict, optional):
    Overwrite configuration for analyzers. Defaults to ``{}``.
tags_labels (List[str], optional):
    List of tag labels to assign (creates non-existing tags)

Raises:

Type Description
IntelOwlClientException

on client/HTTP error

Returns:

Name Type Description
Dict Dict

JSON body

Source code in docs/Submodules/pyintelowl/pyintelowl/pyintelowl.py
def send_file_analysis_playbook_request(
    self,
    filename: str,
    binary: bytes,
    playbook_requested: str,
    tlp: TLPType = "CLEAR",
    runtime_configuration: Dict = None,
    tags_labels: List[str] = None,
) -> Dict:
    """Send playbook analysis request for a file.\n
    Endpoint: ``/api/playbook/analyze_multiple_files``

    Args:

        filename (str):
            Filename
        binary (bytes):
            File contents as bytes
        playbook_requested (str, optional):
        tlp (str, optional):
            TLP for the analysis.
            (options: ``WHITE, GREEN, AMBER, RED``).
        runtime_configuration (Dict, optional):
            Overwrite configuration for analyzers. Defaults to ``{}``.
        tags_labels (List[str], optional):
            List of tag labels to assign (creates non-existing tags)

    Raises:
        IntelOwlClientException: on client/HTTP error

    Returns:
        Dict: JSON body
    """
    try:
        if not tags_labels:
            tags_labels = []
        if not runtime_configuration:
            runtime_configuration = {}
        data = {
            "playbook_requested": playbook_requested,
            "tags_labels": tags_labels,
        }
        # send this value only if populated,
        # otherwise the backend would give you 400
        if tlp:
            data["tlp"] = tlp

        if runtime_configuration:
            data["runtime_configuration"] = json.dumps(runtime_configuration)
        # `files` is wanted to be different from the other
        # /api/analyze_file endpoint
        # because the server is using different serializers
        files = {"files": (filename, binary)}
        answer = self.__send_analysis_request(
            data=data, files=files, playbook_mode=True
        )
    except Exception as e:
        raise IntelOwlClientException(e)
    return answer

send_file_analysis_request(filename, binary, tlp='CLEAR', analyzers_requested=None, connectors_requested=None, runtime_configuration=None, tags_labels=None)

Send analysis request for a file.

Endpoint: /api/analyze_file

Args:

filename (str):
    Filename
binary (bytes):
    File contents as bytes
analyzers_requested (List[str], optional):
    List of analyzers to invoke
    Defaults to ``[]`` i.e. all analyzers.
connectors_requested (List[str], optional):
    List of specific connectors to invoke.
    Defaults to ``[]`` i.e. all connectors.
tlp (str, optional):
    TLP for the analysis.
    (options: ``CLEAR, GREEN, AMBER, RED``).
runtime_configuration (Dict, optional):
    Overwrite configuration for analyzers. Defaults to ``{}``.
tags_labels (List[str], optional):
    List of tag labels to assign (creates non-existing tags)

Raises:

Type Description
IntelOwlClientException

on client/HTTP error

Returns:

Name Type Description
Dict Dict

JSON body

Source code in docs/Submodules/pyintelowl/pyintelowl/pyintelowl.py
def send_file_analysis_request(
    self,
    filename: str,
    binary: bytes,
    tlp: TLPType = "CLEAR",
    analyzers_requested: List[str] = None,
    connectors_requested: List[str] = None,
    runtime_configuration: Dict = None,
    tags_labels: List[str] = None,
) -> Dict:
    """Send analysis request for a file.\n
    Endpoint: ``/api/analyze_file``

    Args:

        filename (str):
            Filename
        binary (bytes):
            File contents as bytes
        analyzers_requested (List[str], optional):
            List of analyzers to invoke
            Defaults to ``[]`` i.e. all analyzers.
        connectors_requested (List[str], optional):
            List of specific connectors to invoke.
            Defaults to ``[]`` i.e. all connectors.
        tlp (str, optional):
            TLP for the analysis.
            (options: ``CLEAR, GREEN, AMBER, RED``).
        runtime_configuration (Dict, optional):
            Overwrite configuration for analyzers. Defaults to ``{}``.
        tags_labels (List[str], optional):
            List of tag labels to assign (creates non-existing tags)

    Raises:
        IntelOwlClientException: on client/HTTP error

    Returns:
        Dict: JSON body
    """
    try:
        if not tlp:
            tlp = "CLEAR"
        if not analyzers_requested:
            analyzers_requested = []
        if not connectors_requested:
            connectors_requested = []
        if not tags_labels:
            tags_labels = []
        if not runtime_configuration:
            runtime_configuration = {}
        data = {
            "file_name": filename,
            "analyzers_requested": analyzers_requested,
            "connectors_requested": connectors_requested,
            "tlp": tlp,
            "tags_labels": tags_labels,
        }
        if runtime_configuration:
            data["runtime_configuration"] = json.dumps(runtime_configuration)
        files = {"file": (filename, binary)}
        answer = self.__send_analysis_request(data=data, files=files)
    except Exception as e:
        raise IntelOwlClientException(e)
    return answer

send_observable_analysis_playbook_request(observable_name, playbook_requested, tlp='CLEAR', runtime_configuration=None, tags_labels=None, observable_classification=None)

Send playbook analysis request for an observable.

Endpoint: /api/playbook/analyze_multiple_observables

Parameters:

Name Type Description Default
observable_name str

Observable value

required
playbook_requested str
required
tlp str

TLP for the analysis. (options: WHITE, GREEN, AMBER, RED).

'CLEAR'
runtime_configuration Dict

Overwrite configuration for analyzers. Defaults to {}.

None
tags_labels List[str]

List of tag labels to assign (creates non-existing tags)

None
observable_classification str

Observable classification, Default to None. By default launch analysis with an automatic classification. (options: url, domain, hash, ip, generic)

None

Raises:

Type Description
IntelOwlClientException

on client/HTTP error

IntelOwlClientException

on wrong observable_classification

Returns:

Name Type Description
Dict Dict

JSON body

Source code in docs/Submodules/pyintelowl/pyintelowl/pyintelowl.py
def send_observable_analysis_playbook_request(
    self,
    observable_name: str,
    playbook_requested: str,
    tlp: TLPType = "CLEAR",
    runtime_configuration: Dict = None,
    tags_labels: List[str] = None,
    observable_classification: str = None,
) -> Dict:
    """Send playbook analysis request for an observable.\n
    Endpoint: ``/api/playbook/analyze_multiple_observables``

    Args:
        observable_name (str):
            Observable value
        playbook_requested str:
        tlp (str, optional):
            TLP for the analysis.
            (options: ``WHITE, GREEN, AMBER, RED``).
        runtime_configuration (Dict, optional):
            Overwrite configuration for analyzers. Defaults to ``{}``.
        tags_labels (List[str], optional):
            List of tag labels to assign (creates non-existing tags)
        observable_classification (str):
            Observable classification, Default to None.
            By default launch analysis with an automatic classification.
            (options: ``url, domain, hash, ip, generic``)

    Raises:
        IntelOwlClientException: on client/HTTP error
        IntelOwlClientException: on wrong observable_classification

    Returns:
        Dict: JSON body
    """
    try:
        if not tags_labels:
            tags_labels = []
        if not runtime_configuration:
            runtime_configuration = {}
        if not observable_classification:
            observable_classification = self._get_observable_classification(
                observable_name
            )
        elif observable_classification not in [
            "generic",
            "hash",
            "ip",
            "domain",
            "url",
        ]:
            raise IntelOwlClientException(
                "Observable classification only handle"
                " 'generic', 'hash', 'ip', 'domain' and 'url' "
            )
        data = {
            "observables": [[observable_classification, observable_name]],
            "playbook_requested": playbook_requested,
            "tags_labels": tags_labels,
            "runtime_configuration": runtime_configuration,
        }
        # send this value only if populated,
        # otherwise the backend would give you 400
        if tlp:
            data["tlp"] = tlp
        answer = self.__send_analysis_request(
            data=data, files=None, playbook_mode=True
        )
    except Exception as e:
        raise IntelOwlClientException(e)
    return answer

send_observable_analysis_request(observable_name, tlp='CLEAR', analyzers_requested=None, connectors_requested=None, runtime_configuration=None, tags_labels=None, observable_classification=None)

Send analysis request for an observable.

Endpoint: /api/analyze_observable

Parameters:

Name Type Description Default
observable_name str

Observable value

required
analyzers_requested List[str]

List of analyzers to invoke Defaults to [] i.e. all analyzers.

None
connectors_requested List[str]

List of specific connectors to invoke. Defaults to [] i.e. all connectors.

None
tlp str

TLP for the analysis. (options: CLEAR, GREEN, AMBER, RED).

'CLEAR'
runtime_configuration Dict

Overwrite configuration for analyzers. Defaults to {}.

None
tags_labels List[str]

List of tag labels to assign (creates non-existing tags)

None
observable_classification str

Observable classification, Default to None. By default launch analysis with an automatic classification. (options: url, domain, hash, ip, generic)

None

Raises:

Type Description
IntelOwlClientException

on client/HTTP error

IntelOwlClientException

on wrong observable_classification

Returns:

Name Type Description
Dict Dict

JSON body

Source code in docs/Submodules/pyintelowl/pyintelowl/pyintelowl.py
def send_observable_analysis_request(
    self,
    observable_name: str,
    tlp: TLPType = "CLEAR",
    analyzers_requested: List[str] = None,
    connectors_requested: List[str] = None,
    runtime_configuration: Dict = None,
    tags_labels: List[str] = None,
    observable_classification: str = None,
) -> Dict:
    """Send analysis request for an observable.\n
    Endpoint: ``/api/analyze_observable``

    Args:
        observable_name (str):
            Observable value
        analyzers_requested (List[str], optional):
            List of analyzers to invoke
            Defaults to ``[]`` i.e. all analyzers.
        connectors_requested (List[str], optional):
            List of specific connectors to invoke.
            Defaults to ``[]`` i.e. all connectors.
        tlp (str, optional):
            TLP for the analysis.
            (options: ``CLEAR, GREEN, AMBER, RED``).
        runtime_configuration (Dict, optional):
            Overwrite configuration for analyzers. Defaults to ``{}``.
        tags_labels (List[str], optional):
            List of tag labels to assign (creates non-existing tags)
        observable_classification (str):
            Observable classification, Default to None.
            By default launch analysis with an automatic classification.
            (options: ``url, domain, hash, ip, generic``)

    Raises:
        IntelOwlClientException: on client/HTTP error
        IntelOwlClientException: on wrong observable_classification

    Returns:
        Dict: JSON body
    """
    try:
        if not tlp:
            tlp = "CLEAR"
        if not analyzers_requested:
            analyzers_requested = []
        if not connectors_requested:
            connectors_requested = []
        if not tags_labels:
            tags_labels = []
        if not runtime_configuration:
            runtime_configuration = {}
        if not observable_classification:
            observable_classification = self._get_observable_classification(
                observable_name
            )
        elif observable_classification not in [
            "generic",
            "hash",
            "ip",
            "domain",
            "url",
        ]:
            raise IntelOwlClientException(
                "Observable classification only handle"
                " 'generic', 'hash', 'ip', 'domain' and 'url' "
            )
        data = {
            "observable_name": observable_name,
            "observable_classification": observable_classification,
            "analyzers_requested": analyzers_requested,
            "connectors_requested": connectors_requested,
            "tlp": tlp,
            "tags_labels": tags_labels,
            "runtime_configuration": runtime_configuration,
        }
        answer = self.__send_analysis_request(data=data, files=None)
    except Exception as e:
        raise IntelOwlClientException(e)
    return answer