repo
stringclasses
454 values
file_path
stringlengths
5
201
extension
stringclasses
1 value
content
stringlengths
8
509k
num_lines
int64
3
16.9k
size_bytes
int64
8
511k
jumpserver
apps/common/sdk/gm/__init__.py
.py
from .base.device import Device from enum import Enum from common.sdk.gm import piico, ccupm, sctu class CryptoVendor(Enum): PIICO = "piico" CCUPM = "ccupm" SCTU = "sctu" @classmethod def from_str(cls, name: str | None): if name is None or not name.strip(): return cls.PIICO ...
31
778
jumpserver
apps/common/sdk/gm/piico/device.py
.py
from ..base.device import Device class PiicoDevice(Device): name = "piico" def __init__(self): self.open() # 默认去lib路径检索 def open(self, driver_path="libpiico_ccmu.so"): super().open(driver_path)
12
243
jumpserver
apps/common/sdk/gm/base/device.py
.py
import base64 from ctypes import * from .session import Session from .cipher import * from .digest import * from .const import SGD_SM2 from django.conf import settings class Device: _driver = None __device = None name = None def open(self, driver_path): if self.__device is not None: ...
96
2,819
jumpserver
apps/common/sdk/gm/base/ecc.py
.py
from ctypes import * from .const import ECC_POINT_UNCOMPRESSED ECCref_MAX_BITS = 512 ECCref_MAX_LEN = int((ECCref_MAX_BITS + 7) / 8) class EncodeMixin: def encode(self): raise NotImplementedError class ECCrefPublicKey(Structure, EncodeMixin): _fields_ = [ ("bits", c_uint), ("x", c_...
87
2,028
jumpserver
apps/common/sdk/gm/base/digest.py
.py
from .const import HASH_ALG_ID class Digest: def __init__(self, session, alg_name="sm3"): if HASH_ALG_ID.get(alg_name) is None: raise Exception("unsupported hash alg {}".format(alg_name)) self._alg_name = alg_name self._session = session self.__init_hash() def __...
27
633
jumpserver
apps/common/sdk/gm/base/exception.py
.py
class GMDeviceError(Exception): def __init__(self, msg, ret): super().__init__(self) self.__ret = ret self.__msg = msg def __str__(self): return "gm device error: {} return code: {}".format(self.__msg, self.hex_ret(self.__ret)) @staticmethod def hex_ret(ret): re...
13
352
jumpserver
apps/common/sdk/gm/base/session.py
.py
from ctypes import * from Cryptodome.Util.asn1 import DerSequence from .const import ECC_KEY_BITS_256 from .ecc import ECCrefPublicKey, ECCrefPrivateKey, ECCKeyPair, ECCSignature from .exception import GMDeviceError from .session_mixin import SM3Mixin, SM4Mixin, SM2Mixin class Session(SM2Mixin, SM3Mixin, SM4Mixin):...
74
2,633
jumpserver
apps/common/sdk/gm/base/session_mixin.py
.py
from .const import ECC_KEY_BITS_64 from .ecc import * from .exception import GMDeviceError class BaseMixin: def __init__(self): self._driver = None self._session = None class SM2Mixin(BaseMixin): def ecc_encrypt(self, public_key, plain_text, alg_id): pos = 0 k1 = bytes([0] ...
143
4,992
jumpserver
apps/common/sdk/gm/base/cipher.py
.py
from .const import CIPHER_ALG_ID, SGD_SM2_3 class ECCCipher: def __init__(self, session, public_key, private_key): self._session = session self.public_key = public_key self.private_key = private_key def encrypt(self, plain_text): return self._session.ecc_encrypt(self.public_ke...
57
1,660
jumpserver
apps/common/sdk/gm/base/const.py
.py
# ECC algorithm IDs SGD_SM2 = 0x00020200 SGD_SM2_3 = 0x00020800 # ECC key bits ECC_KEY_BITS_256 = 0x100 ECC_KEY_BITS_64 = 0x40 # ECC point format ECC_POINT_UNCOMPRESSED = 0x04 # Hash algorithm IDs SGD_SM3 = 0x00000001 SGD_SHA1 = 0x00000002 SGD_SHA256 = 0x00000004 SGD_SHA512 = 0x00000008 HASH_ALG_ID = { "sm3": S...
34
607
jumpserver
apps/common/sdk/gm/ccupm/device.py
.py
from ..base.device import Device class CCUPMDevice(Device): name = "ccupm" def __init__(self): self.open() def open(self, driver_path="libsdf_crypto.so"): super().open(driver_path) def reset_key_store(self): pass
15
258
jumpserver
apps/common/sdk/gm/sctu/device.py
.py
from ctypes import * from ..base.device import Device from .session import Session from .cipher import EBCCipher class SCTUDevice(Device): name = "sctu" def __init__(self): self.open("libhsctu_guomi_vpn.so") def open(self, driver_path): # load driver self.__load_driver(driver_pa...
51
1,497
jumpserver
apps/common/sdk/gm/sctu/session.py
.py
from ctypes import * from common.sdk.gm.base.exception import GMDeviceError from .session_mixin import SM4Mixin class Session(SM4Mixin): def __init__(self, driver, session): super().__init__() self._session = session self._driver = driver def get_device_info(self): pass ...
27
776
jumpserver
apps/common/sdk/gm/sctu/session_mixin.py
.py
from ctypes import * from common.sdk.gm.base.exception import GMDeviceError from common.sdk.gm.base.session_mixin import BaseMixin SGD_SM4_ECB = 0x00002001 SGD_SM4_CBC = 0x00002002 PADDING_PKCS7 = "pkcs7" PADDING_ZERO = "zero" PADDING_NONE = "none" def as_uchar_array(data: bytes): if data is None: ret...
207
5,736
jumpserver
apps/common/sdk/gm/sctu/cipher.py
.py
cipher_alg_id = { "sm4_ebc": 0x00002001, "sm4_cbc": 0x00002002, "sm4_mac": 0x00000405, } class ECCCipher: def __init__(self, session, public_key, private_key): self._session = session self.public_key = public_key self.private_key = private_key def encrypt(self, plain_text)...
60
1,610
jumpserver
apps/common/sdk/im/utils.py
.py
import hashlib import inspect from inspect import Parameter from common.utils.common import get_logger from common.sdk.im import exceptions as exce logger = get_logger(__name__) def digest(corp_id, corp_secret): md5 = hashlib.md5() md5.update(corp_id.encode()) md5.update(corp_secret.encode()) dist =...
73
1,949
jumpserver
apps/common/sdk/im/exceptions.py
.py
from django.utils.translation import gettext_lazy as _ from rest_framework.exceptions import APIException class HTTPNot200(APIException): default_code = 'http_not_200' default_detail = 'HTTP status is not 200' class ErrCodeNot0(APIException): default_code = 'errcode_not_0' default_detail = 'Error c...
24
610
jumpserver
apps/common/sdk/im/mixin.py
.py
import requests from requests import exceptions as req_exce from rest_framework.exceptions import PermissionDenied from django.core.cache import cache from .utils import DictWrapper from common.utils.common import get_logger from common.utils import lazyproperty from common.sdk.im.utils import set_default, as_request ...
150
4,627
jumpserver
apps/common/sdk/im/wecom/__init__.py
.py
from typing import Iterable, AnyStr from urllib.parse import urlencode from django.conf import settings from django.core.cache import cache from django.utils.translation import gettext_lazy as _ from rest_framework.exceptions import APIException from common.sdk.im.mixin import RequestMixin, BaseRequest from common.sd...
226
7,921
jumpserver
apps/common/sdk/im/dingtalk/__init__.py
.py
import base64 import hashlib import hmac import time from django.conf import settings from common.sdk.im.mixin import BaseRequest from common.sdk.im.utils import digest, as_request from common.utils import get_logger from users.utils import construct_user_email, flatten_dict, map_attributes logger = get_logger(__fil...
246
8,428
jumpserver
apps/common/sdk/im/slack/__init__.py
.py
import mistune import requests from django.conf import settings from django.utils.translation import gettext_lazy as _ from rest_framework.exceptions import APIException from common.utils.common import get_logger from jumpserver.utils import get_current_request from users.utils import construct_user_email, flatten_dic...
166
5,795
jumpserver
apps/common/sdk/im/lark/__init__.py
.py
from django.conf import settings from common.utils.common import get_logger from ..feishu import URL as FeiShuURL, FeishuRequests, FeiShu logger = get_logger(__name__) class URL(FeiShuURL): host = 'https://open.larksuite.com' class LarkRequests(FeishuRequests): url_instance = URL() class Lark(FeiShu): ...
23
439
jumpserver
apps/common/sdk/im/feishu/__init__.py
.py
import json from django.conf import settings from rest_framework.exceptions import APIException from common.sdk.im.mixin import RequestMixin, BaseRequest from common.sdk.im.utils import digest from common.utils.common import get_logger from users.utils import construct_user_email, flatten_dict, map_attributes logger...
170
5,467
jumpserver
apps/common/sdk/sms/tencent.py
.py
from collections import OrderedDict from django.conf import settings from common.exceptions import JMSException from common.utils import get_logger from tencentcloud.common import credential from tencentcloud.common.exception.tencent_cloud_sdk_exception import TencentCloudSDKException # 导入对应产品模块的client models。 from te...
100
4,692
jumpserver
apps/common/sdk/sms/exceptions.py
.py
from django.utils.translation import gettext_lazy as _ from common.exceptions import JMSException class CodeExpired(JMSException): default_code = 'verify_code_expired' default_detail = _('The verification code has expired. Please resend it') class CodeError(JMSException): default_code = 'verify_code_er...
22
636
jumpserver
apps/common/sdk/sms/endpoint.py
.py
import importlib from collections import OrderedDict from django.conf import settings from django.db.models import TextChoices from django.utils.translation import gettext_lazy as _ from common.exceptions import JMSException from common.utils import get_logger from .base import BaseSMSClient logger = get_logger(__na...
60
2,128
jumpserver
apps/common/sdk/sms/custom.py
.py
from collections import OrderedDict import requests from django.conf import settings from common.exceptions import JMSException from common.utils import get_logger from .base import BaseSMSClient logger = get_logger(__file__) class CustomSMS(BaseSMSClient): @classmethod def new_from_settings(cls): ...
46
1,361
jumpserver
apps/common/sdk/sms/cmpp2.py
.py
import hashlib import socket import struct import time from django.conf import settings from django.utils.translation import gettext_lazy as _ from common.exceptions import JMSException from common.utils import get_logger from .base import BaseSMSClient logger = get_logger(__file__) CMPP_CONNECT = 0x00000001 # 请求连...
328
11,960
jumpserver
apps/common/sdk/sms/huawei.py
.py
import base64 import hashlib import time import uuid import requests from collections import OrderedDict from django.conf import settings from common.exceptions import JMSException from common.utils import get_logger from .base import BaseSMSClient logger = get_logger(__file__) class HuaweiClient: def __init...
98
3,481
jumpserver
apps/common/sdk/sms/base.py
.py
from common.utils import get_logger logger = get_logger(__file__) class BaseSMSClient: """ 短信终端的基类 """ SIGN_AND_TMPL_SETTING_FIELD_PREFIX: str @classmethod def new_from_settings(cls): raise NotImplementedError def send_sms(self, phone_numbers: list, sign_name: str, template_cod...
25
476
jumpserver
apps/common/sdk/sms/custom_file.py
.py
import os from collections import OrderedDict from django.conf import settings from django.utils.translation import gettext_lazy as _ from django.utils.module_loading import import_string from common.utils import get_logger from common.exceptions import JMSException from jumpserver.settings import get_file_md5 from...
51
1,581
jumpserver
apps/common/sdk/sms/alibaba.py
.py
import json from django.utils.translation import gettext_lazy as _ from django.conf import settings from alibabacloud_dysmsapi20170525.client import Client as Dysmsapi20170525Client from alibabacloud_tea_openapi import models as open_api_models from alibabacloud_dysmsapi20170525 import models as dysmsapi_20170525_mode...
62
2,419
jumpserver
apps/common/drf/throttling.py
.py
# -*- coding: utf-8 -*- from rest_framework.throttling import SimpleRateThrottle __all__ = ['RateThrottle', 'FileTransferThrottle'] class RateThrottle(SimpleRateThrottle): def __init__(self): # Override the usual SimpleRateThrottle, because we can't determine # the rate until called by the view....
51
1,547
jumpserver
apps/common/drf/metadata.py
.py
# -*- coding: utf-8 -*- # from __future__ import unicode_literals import datetime from collections import OrderedDict from django.core.exceptions import ( FieldDoesNotExist, ImproperlyConfigured, PermissionDenied, ) from django.db import models from django.http import Http404 from django.utils.encoding import for...
538
19,679
jumpserver
apps/common/drf/reporting.py
.py
import json from collections import Counter, OrderedDict from datetime import date, datetime, time from django.conf import settings from django.http import HttpResponse from django.utils.encoding import force_str from django.utils.functional import Promise from django.utils import timezone from django.utils.translatio...
282
10,580
jumpserver
apps/common/drf/filters.py
.py
# -*- coding: utf-8 -*- # from rest_framework.filters import SearchFilter as SearchFilterBase import base64 import json import logging from functools import reduce from operator import and_, or_ from collections import defaultdict from django.utils import timezone from django.core.cache import cache from django.core.e...
1,033
37,542
jumpserver
apps/common/drf/exc_handlers.py
.py
import traceback from logging import getLogger from django.core.exceptions import PermissionDenied, ObjectDoesNotExist as DJObjectDoesNotExist from django.db.models.deletion import ProtectedError from django.http import Http404 from django.utils.translation import gettext from django.conf import settings from rest_fra...
64
2,139
jumpserver
apps/common/drf/parsers/excel.py
.py
import pyexcel from django.utils.translation import gettext as _ from .base import BaseFileParser class ExcelFileParser(BaseFileParser): media_type = 'text/xlsx' def generate_rows(self, stream_data): try: workbook = pyexcel.get_book(file_type='xlsx', file_content=stream_data) exc...
19
525
jumpserver
apps/common/drf/parsers/csv.py
.py
# ~*~ coding: utf-8 ~*~ # import chardet import unicodecsv from common.utils import lazyproperty from .base import BaseFileParser from ..const import CSV_FILE_ESCAPE_CHARS class CSVFileParser(BaseFileParser): media_type = 'text/csv' @lazyproperty def match_escape_chars(self): chars = [] ...
50
1,361
jumpserver
apps/common/drf/parsers/base.py
.py
import abc import codecs import json import re from django.utils.translation import gettext_lazy as _ from rest_framework import serializers from rest_framework import status from rest_framework.exceptions import ParseError, APIException from rest_framework.parsers import BaseParser from common.serializers.fields imp...
208
7,340
jumpserver
apps/common/drf/renders/__init__.py
.py
from rest_framework import renderers from .csv import * from .excel import * class PassthroughRenderer(renderers.BaseRenderer): """ Return data as-is. View should supply a Response. """ media_type = 'application/octet-stream' format = '' def render(self, data, accepted_media_type=None, r...
16
363
jumpserver
apps/common/drf/renders/excel.py
.py
from openpyxl import Workbook from openpyxl.cell.cell import ILLEGAL_CHARACTERS_RE from openpyxl.writer.excel import save_virtual_workbook from .base import BaseFileRenderer class ExcelFileRenderer(BaseFileRenderer): media_type = "application/xlsx" format = "xlsx" wb = None ws = None row_count =...
48
1,608
jumpserver
apps/common/drf/renders/csv.py
.py
# ~*~ coding: utf-8 ~*~ # import codecs import unicodecsv from six import BytesIO from .base import BaseFileRenderer from ..const import CSV_FILE_ESCAPE_CHARS class CSVFileRenderer(BaseFileRenderer): media_type = 'text/csv' format = 'csv' writer = None buffer = None escape_chars = tuple(CSV_FI...
43
1,031
jumpserver
apps/common/drf/renders/mixins.py
.py
from django.utils.translation import gettext_noop from audits.const import ActionChoices from audits.utils import record_operate_log_and_activity_log from common.utils import get_logger logger = get_logger(__file__) class LogMixin(object): @staticmethod def _clean_params(query_params): clean_params...
70
2,372
jumpserver
apps/common/drf/renders/base.py
.py
import abc import io import re from datetime import datetime import pyzipper from django.conf import settings from django.utils import timezone from django.utils.translation import gettext_lazy as _ from rest_framework import serializers from rest_framework.renderers import BaseRenderer from rest_framework.utils impor...
314
12,781
jumpserver
apps/common/sessions/cache.py
.py
import re from importlib import import_module from django.conf import settings from django.contrib.sessions.backends.cache import ( SessionStore as DjangoSessionStore ) from django.core.cache import cache, caches from common.utils import get_logger from jumpserver.utils import get_current_request logger = get_lo...
79
2,490
jumpserver
apps/common/auth/signature.py
.py
from rest_framework import authentication from rest_framework import exceptions from httpsig import HeaderVerifier, utils """ Reusing failure exceptions serves several purposes: 1. Lack of useful information regarding the failure inhibits attackers from learning about valid keyIDs or other forms of informati...
128
4,476
jumpserver
apps/common/const/choices.py
.py
import phonenumbers import pycountry from django.db import models from django.conf import settings from django.utils.translation import gettext_lazy as _ from phonenumbers import PhoneMetadata ADMIN = 'Admin' USER = 'User' AUDITOR = 'Auditor' def get_country_phone_codes(): phone_codes = [] for region_code in...
163
4,721
jumpserver
apps/common/const/signals.py
.py
""" `m2m_changed` ``` def m2m_signal_handler(action, instance, reverse, model, pk_set, using): pass ``` """ PRE_ADD = 'pre_add' POST_ADD = 'post_add' PRE_REMOVE = 'pre_remove' POST_REMOVE = 'post_remove' PRE_CLEAR = 'pre_clear' POST_CLEAR = 'post_clear' POST_PREFIX = 'post' PRE_PREFIX = 'pre' OP_LOG_SKIP_SIGNAL...
20
349
jumpserver
apps/common/const/http.py
.py
GET = 'GET' POST = 'POST' PUT = 'PUT' PATCH = 'PATCH' DELETE = 'DELETE' OPTIONS = 'OPTIONS'
8
93
jumpserver
apps/common/const/common.py
.py
import re from django.utils.translation import gettext_lazy as _ create_success_msg = _("%(name)s was created successfully") update_success_msg = _("%(name)s was updated successfully") FILE_END_GUARD = ">>> Content End <<<" celery_task_pre_key = "CELERY_" KEY_CACHE_RESOURCE_IDS = "RESOURCE_IDS_{}" RESOURCE_IDS_CACHE_...
16
600
jumpserver
apps/common/const/crontab.py
.py
CRONTAB_AT_AM_TWO = '0 2 * * *' CRONTAB_AT_AM_THREE = '0 3 * * *' CRONTAB_AT_AM_TEN = '0 10 * * *' CRONTAB_AT_PM_TWO = '0 14 * * *'
7
134
jumpserver
apps/common/hashers/sm3.py
.py
from gmssl import sm3, func from django.contrib.auth.hashers import PBKDF2PasswordHasher class Hasher: name = 'sm3' block_size = 64 digest_size = 32 def __init__(self, data): self.__data = data def hexdigest(self): return sm3.sm3_hash(func.bytes_to_list(self.__data)) def di...
35
671
jumpserver
apps/common/api/reporting.py
.py
from django.conf import settings __all__ = ['ReportExportMixin'] class ReportExportMixin: report_export_mode_param = 'export_mode' report_export_mode_value = 'report' report_exporter_class = None def get_report_exporter_class(self): return getattr(self, 'report_exporter_class', None) de...
43
1,589
jumpserver
apps/common/api/decorator.py
.py
from common.utils import get_logger logger = get_logger(__file__) def deprecated_api(replacement=None, sunset_date=None): """类视图废弃装饰器""" def decorator(cls): original_dispatch = cls.dispatch def new_dispatch(self, request, *args, **kwargs): logger.warning( f'The c...
31
1,090
jumpserver
apps/common/api/mixin.py
.py
# -*- coding: utf-8 -*- # from collections import defaultdict from contextlib import nullcontext from itertools import chain from typing import Callable from django.conf import settings from django.db import models from django.db.models.signals import m2m_changed from rest_framework.request import Request from rest_fr...
300
10,354
jumpserver
apps/common/api/permission.py
.py
# -*- coding: utf-8 -*- # from django.contrib.auth import get_user_model from django.db.models import Q from rest_framework.request import Request from common.utils import lazyproperty __all__ = ['AllowBulkDestroyMixin', 'RoleAdminMixin', 'RoleUserMixin'] class AllowBulkDestroyMixin: def allow_bulk_destroy(self...
65
1,868
jumpserver
apps/common/api/action.py
.py
# -*- coding: utf-8 -*- # from typing import Callable from django.conf import settings from django.utils.translation import gettext as _ from rest_framework.decorators import action from rest_framework.request import Request from rest_framework.response import Response from rest_framework.throttling import UserRateThr...
83
2,639
jumpserver
apps/common/api/patch.py
.py
# -*- coding: utf-8 -*- # import time from hashlib import md5 from threading import Thread from django.core.cache import cache from rest_framework.response import Response from common.utils import lazyproperty __all__ = ['InterceptMixin', 'AsyncApiMixin'] class InterceptMixin: """ Hack默认的dispatch, 让用户可以实现...
141
4,073
jumpserver
apps/common/api/generic.py
.py
from rest_framework.viewsets import GenericViewSet, ModelViewSet from rest_framework_bulk.generics import BulkModelViewSet from .mixin import CommonApiMixin, RelationMixin from .permission import AllowBulkDestroyMixin class JMSGenericViewSet(CommonApiMixin, GenericViewSet): pass class JMSModelViewSet(CommonApi...
22
564
jumpserver
apps/common/api/common.py
.py
# -*- coding: utf-8 -*- # import os import uuid from django.core.cache import cache from django.views.decorators.csrf import csrf_exempt from rest_framework import generics, serializers from rest_framework.permissions import AllowAny from rest_framework.response import Response from rest_framework.views import APIView...
117
3,469
jumpserver
apps/common/api/serializer.py
.py
# -*- coding: utf-8 -*- # from rest_framework.request import Request __all__ = ['SerializerMixin'] class SerializerMixin: """ 根据用户请求动作的不同,获取不同的 `serializer_class `""" action: str request: Request serializer_classes = None single_actions = ['put', 'retrieve', 'patch'] def get_serializer_cl...
51
1,780
jumpserver
apps/common/api/jdmc.py
.py
from requests import RequestException from rest_framework import status from rest_framework.generics import RetrieveAPIView from rest_framework.response import Response from common.jdmc import request_jdmc from common.permissions import CanViewJDMC from common.utils import get_logger __all__ = ['JdmcSSOTokenAPI'] ...
66
2,001
jumpserver
apps/common/utils/zip.py
.py
import os import stat import hashlib from pathlib import Path from rest_framework.exceptions import ValidationError from zipfile import ZipFile, BadZipFile # ------------------------- # 可按你们安全规范调整 # ------------------------- MAX_FILES = 1000 MAX_SINGLE_FILE_SIZE = 200 * 1024 * 1024 # 200MB MAX_TOTAL_SIZE = 1 * 1...
146
4,516
jumpserver
apps/common/utils/safe.py
.py
import logging import subprocess logger = logging.getLogger(__name__) def safe_run_cmd(cmd_args, shell=False, quiet=False): if shell: raise ValueError("shell=True is not allowed in safe_run_cmd. " "Pass command as a list with shell=False.") cmd_args = [str(arg) for arg in cmd_args] try: k...
40
1,264
jumpserver
apps/common/utils/strings.py
.py
import difflib import re def no_special_chars(s): return bool(re.match(r'\w+$', s)) def safe_str(s): return s.encode('utf-8', errors='ignore').decode('utf-8') def get_text_diff(old_text, new_text): diff = difflib.unified_diff( old_text.splitlines(), new_text.splitlines(), lineterm="" ) ...
45
1,096
jumpserver
apps/common/utils/encode.py
.py
# -*- coding: utf-8 -*- # import base64 import hashlib import json import os import re import time from io import StringIO import paramiko import sshpubkeys from cryptography.hazmat.primitives import serialization from django.conf import settings from django.core.serializers.json import DjangoJSONEncoder from itsdange...
280
8,060
jumpserver
apps/common/utils/timezone.py
.py
from datetime import datetime, timedelta from django.utils import timezone as dj_timezone from rest_framework.fields import DateTimeField def as_current_tz(dt: datetime): return dt.astimezone(dj_timezone.get_current_timezone()) def utc_now(): return dj_timezone.now() def local_now(): return dj_timezo...
88
2,372
jumpserver
apps/common/utils/inspect.py
.py
import inspect def copy_function_args(func, locals_dict: dict): signature = inspect.signature(func) keys = signature.parameters.keys() kwargs = {} for k in keys: kwargs[k] = locals_dict.get(k) return kwargs
11
237
jumpserver
apps/common/utils/random.py
.py
# -*- coding: utf-8 -*- # import random import secrets import socket import string import struct string_punctuation = '!#$%&()*+,-.:;<=?@[]_~' def random_datetime(date_start, date_end): random_delta = (date_end - date_start) * random.random() return date_start + random_delta def random_ip(): return soc...
88
2,701
jumpserver
apps/common/utils/verify_code.py
.py
from celery import shared_task from django.conf import settings from django.core.cache import cache from django.utils.translation import gettext_lazy as _ from common.exceptions import JMSException from common.sdk.sms.endpoint import SMS from common.sdk.sms.exceptions import CodeError, CodeExpired, CodeSendTooFrequent...
106
3,104
jumpserver
apps/common/utils/translate.py
.py
from django.utils.translation import gettext, gettext_noop def translate_value(value): if not value: return value sps = ['. ', ': '] spb = {str(sp in value): sp for sp in sps} sp = spb.get('True') if not sp: return value tpl, data = value.split(sp, 1) return gettext(tpl + ...
48
1,129
jumpserver
apps/common/utils/connection.py
.py
import json import threading import time import redis from django.core.cache import cache from redis.client import PubSub from common.db.utils import safe_db_connection from common.utils import get_logger logger = get_logger(__name__) def get_redis_client(db=0): client = cache.client.get_client() assert is...
127
3,657
jumpserver
apps/common/utils/http.py
.py
# -*- coding: utf-8 -*- # import calendar import threading import time from email.utils import formatdate from rest_framework.serializers import BooleanField _STRPTIME_LOCK = threading.Lock() _GMT_FORMAT = "%a, %d %b %Y %H:%M:%S GMT" _ISO8601_FORMAT = "%Y-%m-%dT%H:%M:%S.000Z" def to_unixtime(time_string, format_st...
48
1,348
jumpserver
apps/common/utils/django.py
.py
# -*- coding: utf-8 -*- # import re from django.conf import settings from django.db import models from django.db.models.signals import post_save, pre_save from django.shortcuts import reverse as dj_reverse from django.utils import timezone from django.utils.http import url_has_allowed_host_and_scheme UUID_PATTERN = r...
132
3,744
jumpserver
apps/common/utils/file.py
.py
import os import csv import pyzipper import requests import zipfile from hashlib import md5 from django.conf import settings def create_csv_file(filename, headers, rows, ): with open(filename, 'w', encoding='utf-8-sig') as f: w = csv.writer(f) w.writerow(headers) w.writerows(rows) def...
67
1,948
jumpserver
apps/common/utils/integer.py
.py
def bit(x): if x < 1: raise ValueError("x must be greater than 1") return 2 ** (x - 1)
5
103
jumpserver
apps/common/utils/gmssl_python.py
.py
# Copyright 2023 The GmSSL Project. All Rights Reserved. # # Licensed under the Apache License, Version 2.0 (the License); you may # not use this file except in compliance with the License. # # http://www.apache.org/licenses/LICENSE-2.0 # # GmSSL-Python - Python binding of the GmSSL library with `ctypes` # ===========...
1,058
31,511
jumpserver
apps/common/utils/common.py
.py
# -*- coding: utf-8 -*- # import datetime import ipaddress import logging import os import platform import re import socket import textwrap import time import uuid import hmac import hashlib from collections import OrderedDict from functools import wraps, cached_property from itertools import chain from bs4 import Bea...
520
13,345
jumpserver
apps/common/utils/yml.py
.py
import json import os import tempfile import yaml from ansible.utils.unsafe_proxy import wrap_var from django.conf import settings from jinja2 import StrictUndefined from jinja2.sandbox import SandboxedEnvironment class AnsibleUnsafeDumper(yaml.SafeDumper): pass UnsafeTextType = type(wrap_var('')) AnsibleUnsaf...
188
5,341
jumpserver
apps/common/utils/lock.py
.py
import threading from functools import wraps from django.db import transaction from redis_lock import ( Lock as RedisLock, NotAcquired, UNLOCK_SCRIPT, EXTEND_SCRIPT, RESET_SCRIPT, RESET_ALL_SCRIPT ) from common.local import thread_local from common.utils import get_logger from common.utils.connection import g...
198
7,222
jumpserver
apps/common/utils/jumpserver.py
.py
from django.core.cache import cache from django.shortcuts import reverse, redirect from django.utils.translation import gettext_noop from .random import random_string __all__ = ['FlashMessageUtil'] class FlashMessageUtil: """ 跳转到通用msg页面 message_data: { 'title': '', 'message': '', ...
49
1,175
jumpserver
apps/common/utils/crypto/__init__.py
.py
from django.conf import settings from django.core.exceptions import ImproperlyConfigured from common.sdk.gm import open_gm_device, CryptoVendor from .common import * from .session import * from .rsa_aes import * from .gm import * class Crypto: cryptor_map = { 'aes_ecb': aes_ecb_crypto, 'aes_gcm':...
73
2,196
jumpserver
apps/common/utils/crypto/gm.py
.py
import os import base64 from django.conf import settings from gmssl.sm4 import CryptSM4, SM4_ENCRYPT, SM4_DECRYPT from gmssl import sm2, sm3, func import logging from common.sdk.gm import Device from .base import BaseCrypto, BaseCryptoSuite from .common import padding_key class GMSM4EcbCrypto(BaseCrypto): def __...
142
3,841
jumpserver
apps/common/utils/crypto/session.py
.py
import logging from django.conf import settings from .rsa_aes import RsaAesCryptoSuite from .gm import GmCryptoSuite ENCRYPTED_SEPARATOR = '::encrypted::' def decrypt_session_password(value): from jumpserver.utils import current_request if not current_request: return value cipher = value.spl...
44
1,219
jumpserver
apps/common/utils/crypto/common.py
.py
import re secret_pattern = re.compile(r'password|secret|key|token', re.IGNORECASE) def padding_key(key, max_length=32): """ 返回32 bytes 的key """ if not isinstance(key, bytes): key = bytes(key, encoding='utf-8') if len(key) >= max_length: return key[:max_length] while len(key...
20
375
jumpserver
apps/common/utils/crypto/base.py
.py
import base64 class BaseCrypto: def encrypt(self, text): return base64.urlsafe_b64encode( self._encrypt(bytes(text, encoding='utf8')) ).decode('utf8') def encrypt_bin(self, data: bytes) -> bytes: return self._encrypt(data) def _encrypt(self, data: bytes) -> bytes: ...
45
1,133
jumpserver
apps/common/utils/crypto/rsa_aes.py
.py
import base64 import hashlib from django.conf import settings from Cryptodome import Random from Cryptodome.Cipher import AES, PKCS1_v1_5 from Cryptodome.PublicKey import RSA from Cryptodome.Random import get_random_bytes from Cryptodome.Util.Padding import pad from .base import BaseCryptoSuite from .common import p...
203
5,715
jumpserver
apps/common/utils/ip/utils.py
.py
import ipaddress import socket from ipaddress import ip_network, ip_address from django.conf import settings from django.utils.translation import gettext_lazy as _ from .geoip import get_ip_city_by_geoip from .ipip import get_ip_city_by_ipip def is_ip_address(address): """ 192.168.10.1 """ try: ip_a...
127
3,266
jumpserver
apps/common/utils/ip/geoip/utils.py
.py
# -*- coding: utf-8 -*- # import ipaddress import os import geoip2.database from django.conf import settings from django.utils.translation import gettext_lazy as _ from geoip2.errors import GeoIP2Error __all__ = ['get_ip_city_by_geoip'] reader = None def init_ip_reader(): global reader if reader: re...
50
1,208
jumpserver
apps/common/utils/ip/ipip/utils.py
.py
# -*- coding: utf-8 -*- # import os from django.conf import settings import ipdb __all__ = ['get_ip_city_by_ipip'] ipip_db = None def init_ipip_db(): global ipip_db if ipip_db is not None: return ipip_db_path = os.path.join(settings.DATA_DIR, 'system', 'ipipfree.ipdb') if not os.path.exists(...
34
850
jumpserver
apps/common/views/template.py
.py
import logging import os from django.conf import settings from django.template import Context from django.template import Engine, TemplateSyntaxError from django.template.loader import render_to_string from django.utils._os import safe_join logger = logging.getLogger(__name__) def safe_render_to_string(template_nam...
48
1,768
jumpserver
apps/common/views/http.py
.py
# -*- coding: utf-8 -*- # from django.http import HttpResponse from django.utils.encoding import iri_to_uri class HttpResponseTemporaryRedirect(HttpResponse): status_code = 307 def __init__(self, redirect_to): HttpResponse.__init__(self) self['Location'] = iri_to_uri(redirect_to)
14
309
jumpserver
apps/common/views/msg.py
.py
# from django.http import HttpResponse from django.utils.decorators import method_decorator from django.utils.translation import gettext_lazy as _ from django.views.decorators.cache import never_cache from django.views.generic.base import TemplateView from common.utils import bulk_get, FlashMessageUtil, safe_next_url ...
44
1,712
jumpserver
apps/common/views/mixins.py
.py
# -*- coding: utf-8 -*- # from django.contrib.auth.mixins import UserPassesTestMixin from django.http.response import JsonResponse from rest_framework import permissions from rest_framework.request import Request from common.exceptions import UserConfirmRequired __all__ = [ "PermissionsMixin", "UserConfirmRe...
42
1,099
jumpserver
apps/common/db/utils.py
.py
from contextlib import contextmanager import base64 from django.db import connections, transaction, connection from django.utils.encoding import force_str from common.utils import get_logger, signer, crypto logger = get_logger(__file__) def default_ip_group(): return ["*"] def get_object_if_need(model, pk): ...
166
4,817
jumpserver
apps/common/db/fields.py
.py
# -*- coding: utf-8 -*- # import ipaddress import json import logging import re from django.apps import apps from django.core.exceptions import ValidationError from django.core.validators import MinValueValidator, MaxValueValidator from django.db import models from django.db.models import Q, Manager, QuerySet from dj...
613
20,024
jumpserver
apps/common/db/models.py
.py
""" 此文件作为 `django.db.models` 的 shortcut 这样做的优点与缺点为: 优点: - 包命名都统一为 `models` - 用户在使用的时候只导入本文件即可 缺点: - 此文件中添加代码的时候,注意不要跟 `django.db.models` 中的命名冲突 """ import uuid from django.db import models from django.db import transaction from django.db.models import F, ExpressionWrapper, CASCADE from django.db.models i...
91
2,937
jumpserver
apps/common/db/encoder.py
.py
import json import logging import uuid from datetime import datetime from django.conf import settings from django.db import models from django.utils import timezone as dj_timezone from django.utils.translation import gettext_lazy as _ lazy_type = type(_('gettext_lazy')) class ModelJSONFieldEncoder(json.JSONEncoder)...
33
1,058
jumpserver
apps/common/db/mixins.py
.py
# -*- coding: utf-8 -*- # from django.db import models from django.utils import timezone from django.utils.translation import gettext_lazy as _ __all__ = [ "NoDeleteManager", "NoDeleteModelMixin", "NoDeleteQuerySet", ] class NoDeleteQuerySet(models.query.QuerySet): def delete(self): return self.upd...
44
1,138