1#!/usr/bin/env python
2
3"""
4Copyright (c) 2006-2019 sqlmap developers (http://sqlmap.org/)
5See the file 'LICENSE' for copying permission
6"""
7
8try:
9    import _mssql
10    import pymssql
11except:
12    pass
13
14import logging
15
16from lib.core.common import getSafeExString
17from lib.core.convert import getText
18from lib.core.data import conf
19from lib.core.data import logger
20from lib.core.exception import SqlmapConnectionException
21from plugins.generic.connector import Connector as GenericConnector
22
23class Connector(GenericConnector):
24    """
25    Homepage: http://pymssql.sourceforge.net/
26    User guide: http://pymssql.sourceforge.net/examples_pymssql.php
27    API: http://pymssql.sourceforge.net/ref_pymssql.php
28    Debian package: python-pymssql
29    License: LGPL
30
31    Possible connectors: http://wiki.python.org/moin/SQL%20Server
32
33    Important note: pymssql library on your system MUST be version 1.0.2
34    to work, get it from http://sourceforge.net/projects/pymssql/files/pymssql/1.0.2/
35    """
36
37    def connect(self):
38        self.initConnection()
39
40        try:
41            self.connector = pymssql.connect(host="%s:%d" % (self.hostname, self.port), user=self.user, password=self.password, database=self.db, login_timeout=conf.timeout, timeout=conf.timeout)
42        except (pymssql.Error, _mssql.MssqlDatabaseException) as ex:
43            raise SqlmapConnectionException(ex)
44        except ValueError:
45            raise SqlmapConnectionException
46
47        self.initCursor()
48        self.printConnected()
49
50    def fetchall(self):
51        try:
52            return self.cursor.fetchall()
53        except (pymssql.Error, _mssql.MssqlDatabaseException) as ex:
54            logger.log(logging.WARN if conf.dbmsHandler else logging.DEBUG, "(remote) '%s'" % getSafeExString(ex).replace("\n", " "))
55            return None
56
57    def execute(self, query):
58        retVal = False
59
60        try:
61            self.cursor.execute(getText(query))
62            retVal = True
63        except (pymssql.OperationalError, pymssql.ProgrammingError) as ex:
64            logger.log(logging.WARN if conf.dbmsHandler else logging.DEBUG, "(remote) '%s'" % getSafeExString(ex).replace("\n", " "))
65        except pymssql.InternalError as ex:
66            raise SqlmapConnectionException(getSafeExString(ex))
67
68        return retVal
69
70    def select(self, query):
71        retVal = None
72
73        if self.execute(query):
74            retVal = self.fetchall()
75
76            try:
77                self.connector.commit()
78            except pymssql.OperationalError:
79                pass
80
81        return retVal
82