Statistics
| Branch: | Tag: | Revision:

root / snf-cyclades-app / synnefo / userdata / models.py @ 0c09b1c0

History | View | Annotate | Download (3.9 kB)

1
#
2
# Copyright 2011 GRNET S.A. All rights reserved.
3
#
4
# Redistribution and use in source and binary forms, with or
5
# without modification, are permitted provided that the following
6
# conditions are met:
7
#
8
#   1. Redistributions of source code must retain the above
9
#      copyright notice, this list of conditions and the following
10
#      disclaimer.
11
#
12
#   2. Redistributions in binary form must reproduce the above
13
#      copyright notice, this list of conditions and the following
14
#      disclaimer in the documentation and/or other materials
15
#      provided with the distribution.
16
#
17
# THIS SOFTWARE IS PROVIDED BY GRNET S.A. ``AS IS'' AND ANY EXPRESS
18
# OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE IMPLIED
19
# WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR
20
# PURPOSE ARE DISCLAIMED. IN NO EVENT SHALL GRNET S.A OR
21
# CONTRIBUTORS BE LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL,
22
# SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT
23
# LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES; LOSS OF
24
# USE, DATA, OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED
25
# AND ON ANY THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT
26
# LIABILITY, OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN
27
# ANY WAY OUT OF THE USE OF THIS SOFTWARE, EVEN IF ADVISED OF THE
28
# POSSIBILITY OF SUCH DAMAGE.
29
#
30
# The views and conclusions contained in the software and
31
# documentation are those of the authors and should not be
32
# interpreted as representing official policies, either expressed
33
# or implied, of GRNET S.A.
34

    
35
import base64
36
import binascii
37
import re
38

    
39
from hashlib import md5
40

    
41
from django.db import models
42
from django.conf import settings
43
from django.core.exceptions import ValidationError, NON_FIELD_ERRORS
44
from django.db.models.signals import pre_save
45

    
46
try:
47
    from paramiko import rsakey, dsskey, SSHException
48
except:
49
    pass
50

    
51

    
52
class ProfileModel(models.Model):
53
    """
54
    Abstract model, provides a basic interface for models that store
55
    user specific information
56
    """
57

    
58
    user = models.CharField(max_length=100)
59

    
60
    class Meta:
61
        abstract = True
62
        app_label = 'userdata'
63

    
64

    
65
class PublicKeyPair(ProfileModel):
66
    """
67
    Public key model
68
    """
69
    name = models.CharField(max_length=255, null=False, blank=False)
70
    content = models.TextField()
71
    fingerprint = models.CharField(max_length=100, null=False, blank=True)
72

    
73
    class Meta:
74
        app_label = 'userdata'
75

    
76
    def full_clean(self, *args, **kwargs):
77
        # update fingerprint before clean
78
        self.update_fingerprint()
79
        super(PublicKeyPair, self).full_clean(*args, **kwargs)
80

    
81
    def key_data(self):
82
        return self.content.split(" ", 1)
83

    
84
    def get_key_object(self):
85
        """
86
        Identify key contents and return appropriate paramiko public key object
87
        """
88
        key_type, data = self.key_data()
89
        data = base64.b64decode(data)
90

    
91
        if key_type == "ssh-rsa":
92
            key = rsakey.RSAKey(data=data)
93
        elif key_type == "ssh-dss":
94
            key = dsskey.DSSKey(data=data)
95
        else:
96
            raise Exception("Invalid key type")
97

    
98
        return key
99

    
100
    def clean_key(self):
101
        key = None
102
        try:
103
            key = self.get_key_object()
104
        except:
105
            raise ValidationError("Invalid SSH key")
106

    
107
    def clean(self):
108
        if PublicKeyPair.user_limit_exceeded(self.user):
109
            raise ValidationError("SSH keys limit exceeded.")
110

    
111
    def update_fingerprint(self):
112
        try:
113
            fp = binascii.hexlify(self.get_key_object().get_fingerprint())
114
            self.fingerprint = ":".join(re.findall(r"..", fp))
115
        except:
116
            self.fingerprint = "unknown fingerprint"
117

    
118
    def save(self, *args, **kwargs):
119
        self.update_fingerprint()
120
        super(PublicKeyPair, self).save(*args, **kwargs)
121

    
122
    @classmethod
123
    def user_limit_exceeded(cls, user):
124
        return (PublicKeyPair.objects.filter(user=user).count() >=
125
                settings.USERDATA_MAX_SSH_KEYS_PER_USER)